Example #1
0
File: port.py Project: Pyomo/pyomo
    def construct(self, data=None):
        if __debug__ and logger.isEnabledFor(logging.DEBUG):  #pragma:nocover
            logger.debug( "Constructing Port, name=%s, from data=%s"
                          % (self.name, data) )

        if self._constructed:
            return

        timer = ConstructionTimer(self)
        self._constructed = True

        # Construct _PortData objects for all index values
        if self.is_indexed():
            self._initialize_members(self._index)
        else:
            self._data[None] = self
            self._initialize_members([None])

        # get rid of these references
        self._rule = None
        self._initialize = None
        self._implicit = None
        self._extends = None # especially important as this is another port

        timer.report()
Example #2
0
File: arc.py Project: Pyomo/pyomo
    def construct(self, data=None):
        """Initialize the Arc"""
        if __debug__ and logger.isEnabledFor(logging.DEBUG):
            logger.debug("Constructing Arc %s" % self.name)

        if self._constructed:
            return

        timer = ConstructionTimer(self)
        self._constructed = True

        if self._rule is None and self._init_vals is None:
            # No construction rule or values specified
            return
        elif self._rule is not None and self._init_vals is not None:
            raise ValueError(
                "Cannot specify rule along with source/destination/ports "
                "keywords for arc '%s'" % self.name)

        self_parent = self._parent()

        if not self.is_indexed():
            if self._rule is None:
                tmp = self._init_vals
                tmp["directed"] = self._init_directed
            else:
                try:
                    tmp = self._rule(self_parent)
                except Exception:
                    err = sys.exc_info()[1]
                    logger.error(
                        "Rule failed when generating values for "
                        "arc %s:\n%s: %s"
                        % (self.name, type(err).__name__, err))
                    raise
                tmp = _iterable_to_dict(tmp, self._init_directed, self.name)
            self._setitem_when_not_present(None, tmp)
        else:
            if self._init_vals is not None:
                raise IndexError(
                    "Arc '%s': Cannot initialize multiple indices "
                    "of an arc with single ports" % self.name)
            for idx in self._index:
                try:
                    tmp = apply_indexed_rule(self, self._rule, self_parent, idx)
                except Exception:
                    err = sys.exc_info()[1]
                    logger.error(
                        "Rule failed when generating values for "
                        "arc %s with index %s:\n%s: %s"
                        % (self.name, str(idx), type(err).__name__, err))
                    raise
                tmp = _iterable_to_dict(tmp, self._init_directed, self.name)
                self._setitem_when_not_present(idx, tmp)
        timer.report()
Example #3
0
    def construct(self, data=None):
        if __debug__ and logger.isEnabledFor(logging.DEBUG):        #pragma:nocover
            logger.debug("Constructing %s '%s', from data=%s",
                         self.__class__.__name__, self.name, str(data))
        if self._constructed:                                       #pragma:nocover
            return
        timer = ConstructionTimer(self)

        #
        _self_rule = self._rule
        self._rule = None
        super(Complementarity, self).construct()
        self._rule = _self_rule
        #
        if _self_rule is None and self._expr is None:
            # No construction rule or expression specified.
            return
        #
        if not self.is_indexed():
            #
            # Scalar component
            #
            if _self_rule is None:
                self.add(None, self._expr)
            else:
                try:
                    tmp = _self_rule(self.parent_block())
                    self.add(None, tmp)
                except Exception:
                    err = sys.exc_info()[1]
                    logger.error(
                        "Rule failed when generating expression for "
                        "complementarity %s:\n%s: %s"
                        % ( self.name, type(err).__name__, err ) )
                    raise
        else:
            if not self._expr is None:
                raise IndexError(
                    "Cannot initialize multiple indices of a Complementarity "
                    "component with a single expression")
            _self_parent = self._parent()
            for idx in self._index:
                try:
                    tmp = apply_indexed_rule( self, _self_rule, _self_parent, idx )
                    self.add(idx, tmp)
                except Exception:
                    err = sys.exc_info()[1]
                    logger.error(
                        "Rule failed when generating expression for "
                        "complementarity %s with index %s:\n%s: %s"
                        % ( self.name, idx, type(err).__name__, err ) )
                    raise
        timer.report()
Example #4
0
    def construct(self, data=None):
        """ Apply the rule to construct values in this set """

        if __debug__ and logger.isEnabledFor(logging.DEBUG):
            logger.debug(
                "Constructing Expression, name=%s, from data=%s"
                % (self.name, str(data)))

        if self._constructed:
            return
        timer = ConstructionTimer(self)
        self._constructed = True

        _init_expr = self._init_expr
        _init_rule = self._init_rule
        #
        # We no longer need these
        #
        self._init_expr = None
        # Utilities like DAE assume this stays around
        #self._init_rule = None

        if not self.is_indexed():
            self._data[None] = self

        #
        # Construct and initialize members
        #
        if _init_rule is not None:
            # construct and initialize with a rule
            if self.is_indexed():
                for key in self._index:
                    self.add(key,
                             apply_indexed_rule(
                                 self,
                                 _init_rule,
                                 self._parent(),
                                 key))
            else:
                self.add(None, _init_rule(self._parent()))
        else:
            # construct and initialize with a value
            if _init_expr.__class__ is dict:
                for key in self._index:
                    if key not in _init_expr:
                        continue
                    self.add(key, _init_expr[key])
            else:
                for key in self._index:
                    self.add(key, _init_expr)
        timer.report()
Example #5
0
File: alias.py Project: Pyomo/pyomo
 def construct(self, data=None):
     if __debug__ and logger.isEnabledFor(logging.DEBUG):   #pragma:nocover
         try:
             name = str(self.name)
         except:
             name = type(self)
             if logger.isEnabledFor(logging.DEBUG):
                 logger.debug("Constructing Alias, name=%s, "
                              "from data=%s", name, str(data))
     if self._constructed:
         return
     timer = ConstructionTimer(self)
     self._constructed = True
     timer.report()
Example #6
0
 def construct(self, values=None):
     """
     Initialize set data
     """
     if self._constructed:
         return
     timer = ConstructionTimer(self)
     self._constructed=True
     #
     # We call value() here for cases like Expressions, mutable
     # Params and the like
     #
     self._start_val = value(self._start)
     self._end_val = value(self._end)
     self._step_val = value(self._step)
     #
     # The set generates integer values if the starting value,
     # step and end value are all integers.  Otherwise, the set
     # generates real values.
     #
     if type(self._start_val) is int and type(self._step) is int and type(self._end_val) is int:
         self.domain = Integers
     else:
         self.domain = Reals
     #
     # Compute the set length and upper bound
     #
     if self.filter is None and self.validate is None:
         #
         # Directly compute the number of elements in the set, from
         # which the upper-bound is computed.
         #
         self._len = int(math.floor((self._end_val-self._start_val+self._step_val+1e-7)//self._step_val))
         ub = self._start_val + (self._len-1)*self._step_val
     else:
         #
         # Iterate through the set to compute the upper bound
         # and number of elements.
         #
         ub = self._start_val
         ctr=0
         for i in self:
             ub = i
             ctr += 1
         self._len = ctr
     #
     # Set the bounds information
     #
     self._bounds = (self._start_val, ub)
     timer.report()
Example #7
0
    def construct(self, values=None):
        """ Constructs a :py:class:`ContinuousSet` component

        """
        timer = ConstructionTimer(self)
        OrderedSimpleSet.construct(self, values)

        for val in self.value:
            if type(val) is tuple:
                raise ValueError("ContinuousSet cannot contain tuples")
            if val.__class__ not in native_numeric_types:
                raise ValueError("ContinuousSet can only contain numeric "
                                 "values")

        if self._bounds is None:
            raise ValueError("ContinuousSet '%s' must have at least two values"
                             " indicating the range over which a differential "
                             "equation is to be discretized" % self.name)

        # If bounds were set using pyomo parameters, get their values
        lb = value(self._bounds[0])
        ub = value(self._bounds[1])
        self._bounds = (lb, ub)

        if self._bounds[0].__class__ not in native_numeric_types:
            raise ValueError("Bounds on ContinuousSet must be numeric values")
        if self._bounds[1].__class__ not in native_numeric_types:
            raise ValueError("Bounds on ContinuousSet must be numeric values")

        # TBD: If a user specifies bounds they will be added to the set
        # unless the user specified bounds have been overwritten during
        # OrderedSimpleSet construction. This can lead to some unintuitive
        # behavior when the ContinuousSet is both initialized with values and
        # bounds are specified. The current implementation is consistent
        # with how 'Set' treats this situation.
        if self._bounds[0] not in self.value:
            self.add(self._bounds[0])
            self._sort()
        if self._bounds[1] not in self.value:
            self.add(self._bounds[1])
            self._sort()

        if len(self) < 2:
            raise ValueError("ContinuousSet '%s' must have at least two values"
                             " indicating the range over which a differential "
                             "equation is to be discretized" % self.name)
        self._fe = sorted(self)
        timer.report()
Example #8
0
    def construct(self, data=None):
        """
        Constructs this component, applying rule if it exists.
        """
        if __debug__ and logger.isEnabledFor(logging.DEBUG):
            logger.debug("Constructing suffix %s", self.name)

        if self._constructed is True:
            return

        timer = ConstructionTimer(self)
        self._constructed = True

        if self._rule is not None:
            self.update_values(self._rule(self._parent()))
        timer.report()
Example #9
0
 def construct(self, data=None):
     if __debug__ and logger.isEnabledFor(logging.DEBUG):  #pragma:nocover
         logger.debug( "Constructing Connector, name=%s, from data=%s"
                       % (self.name, data) )
     if self._constructed:
         return
     timer = ConstructionTimer(self)
     self._constructed=True
     #
     # Construct _ConnectorData objects for all index values
     #
     if self.is_indexed():
         self._initialize_members(self._index)
     else:
         self._data[None] = self
         self._initialize_members([None])
     timer.report()
Example #10
0
 def construct(self, data=None):
     """ Apply the rule to construct values in this set """
     if __debug__ and logger.isEnabledFor(logging.DEBUG):   #pragma:nocover
         logger.debug("Constructing Action, name="+self.name)
     #
     if self._constructed:                                  #pragma:nocover
         return
     timer = ConstructionTimer(self)
     self._constructed=True
     #
     if not self.is_indexed():
         # Scalar component
         self._rule(self._parent())
     else:
         # Indexed component
         for index in self._index:
             apply_indexed_rule(self, self._rule, self._parent(), index)
     timer.report()
Example #11
0
 def construct(self, data=None):
     """
     Construct the expression(s) for this complementarity condition.
     """
     generate_debug_messages = __debug__ and logger.isEnabledFor(logging.DEBUG)
     if generate_debug_messages:         #pragma:nocover
         logger.debug("Constructing complementarity list %s", self.name)
     if self._constructed:               #pragma:nocover
         return
     timer = ConstructionTimer(self)
     _self_rule = self._rule
     self._constructed=True
     if _self_rule is None:
         return
     #
     _generator = None
     _self_parent = self._parent()
     if inspect.isgeneratorfunction(_self_rule):
         _generator = _self_rule(_self_parent)
     elif inspect.isgenerator(_self_rule):
         _generator = _self_rule
     if _generator is None:
         while True:
             val = self._nconditions + 1
             if generate_debug_messages:     #pragma:nocover
                 logger.debug("   Constructing complementarity index "+str(val))
             expr = apply_indexed_rule( self, _self_rule, _self_parent, val )
             if expr is None:
                 raise ValueError( "Complementarity rule returned None "
                                   "instead of ComplementarityList.End" )
             if (expr.__class__ is tuple and expr == ComplementarityList.End):
                 return
             self.add(expr)
     else:
         for expr in _generator:
             if expr is None:
                 raise ValueError( "Complementarity generator returned None "
                                   "instead of ComplementarityList.End" )
             if (expr.__class__ is tuple and expr == ComplementarityList.End):
                 return
             self.add(expr)
     timer.report()
Example #12
0
    def construct(self, data=None):
        if __debug__ and logger.isEnabledFor(logging.DEBUG):
            logger.debug("Constructing disjunction %s"
                         % (self.name))
        if self._constructed:
            return
        timer = ConstructionTimer(self)
        self._constructed=True

        _self_parent = self.parent_block()
        if not self.is_indexed():
            if self._init_rule is not None:
                expr = self._init_rule(_self_parent)
            elif self._init_expr is not None:
                expr = self._init_expr
            else:
                timer.report()
                return

            if expr is None:
                raise ValueError( _rule_returned_none_error % (self.name,) )
            if expr is Disjunction.Skip:
                timer.report()
                return
            self._data[None] = self
            self._setitem_when_not_present( None, expr )
        elif self._init_expr is not None:
            raise IndexError(
                "Disjunction '%s': Cannot initialize multiple indices "
                "of a disjunction with a single disjunction list" %
                (self.name,) )
        elif self._init_rule is not None:
            _init_rule = self._init_rule
            for ndx in self._index:
                try:
                    expr = apply_indexed_rule(self,
                                             _init_rule,
                                             _self_parent,
                                             ndx)
                except Exception:
                    err = sys.exc_info()[1]
                    logger.error(
                        "Rule failed when generating expression for "
                        "disjunction %s with index %s:\n%s: %s"
                        % (self.name,
                           str(ndx),
                           type(err).__name__,
                           err))
                    raise
                if expr is None:
                    _name = "%s[%s]" % (self.name, str(idx))
                    raise ValueError( _rule_returned_none_error % (_name,) )
                if expr is Disjunction.Skip:
                    continue
                self._setitem_when_not_present(ndx, expr)
        timer.report()
Example #13
0
File: check.py Project: Pyomo/pyomo
 def construct(self, data=None):
     """ Apply the rule to construct values in this set """
     if __debug__ and logger.isEnabledFor(logging.DEBUG):   #pragma:nocover
             logger.debug("Constructing Check, name="+self.name)
     #
     if self._constructed:                                  #pragma:nocover
         return
     timer = ConstructionTimer(self)
     self._constructed=True
     #
     if not self.is_indexed():
         # Scalar component
         res = self._rule(self._parent())
         if not res:
             raise ValueError("BuildCheck %r identified error" % self.name)
     else:
         # Indexed component
         for index in self._index:
             res = apply_indexed_rule(self, self._rule, self._parent(), index)
             if not res:
                 raise ValueError("BuildCheck %r identified error with index %r" % (self.name, str(index)))
     timer.report()
Example #14
0
File: var.py Project: Pyomo/pyomo
    def construct(self, data=None):
        """Construct this component."""
        if __debug__ and logger.isEnabledFor(logging.DEBUG):   #pragma:nocover
            try:
                name = str(self.name)
            except:
                # Some Var components don't have a name yet, so just use
                # the type
                name = type(self)
            if logger.isEnabledFor(logging.DEBUG):
                logger.debug(
                    "Constructing Variable, name=%s, from data=%s"
                    % (name, str(data)))

        if self._constructed:
            return
        timer = ConstructionTimer(self)
        self._constructed=True

        #
        # Construct _VarData objects for all index values
        #
        if not self.is_indexed():
            self._data[None] = self
            self._initialize_members((None,))
        elif self._dense:
            # This loop is optimized for speed with pypy.
            # Calling dict.update((...) for ...) is roughly
            # 30% slower
            self_weakref = weakref_ref(self)
            for ndx in self._index:
                cdata = self._ComponentDataClass(
                    domain=self._domain_init_value, component=None)
                cdata._component = self_weakref
                self._data[ndx] = cdata
                #self._initialize_members((ndx,))
            self._initialize_members(self._index)
        timer.report()
Example #15
0
    def construct(self, data=None):
        """
        Construct the expression(s) for this constraint.
        """
        if __debug__ and logger.isEnabledFor(logging.DEBUG):
            logger.debug("Constructing constraint %s"
                         % (self.name))
        if self._constructed:
            return
        timer = ConstructionTimer(self)
        self._constructed=True

        _init_expr = self._init_expr
        _init_rule = self.rule
        #
        # We no longer need these
        #
        self._init_expr = None
        # Utilities like DAE assume this stays around
        #self.rule = None

        if (_init_rule is None) and \
           (_init_expr is None):
            # No construction role or expression specified.
            return

        _self_parent = self._parent()
        if not self.is_indexed():
            #
            # Scalar component
            #
            if _init_rule is None:
                tmp = _init_expr
            else:
                try:
                    tmp = _init_rule(_self_parent)
                except Exception:
                    err = sys.exc_info()[1]
                    logger.error(
                        "Rule failed when generating expression for "
                        "constraint %s:\n%s: %s"
                        % (self.name,
                           type(err).__name__,
                           err))
                    raise
            self._setitem_when_not_present(None, tmp)

        else:
            if _init_expr is not None:
                raise IndexError(
                    "Constraint '%s': Cannot initialize multiple indices "
                    "of a constraint with a single expression" %
                    (self.name,) )

            for ndx in self._index:
                try:
                    tmp = apply_indexed_rule(self,
                                             _init_rule,
                                             _self_parent,
                                             ndx)
                except Exception:
                    err = sys.exc_info()[1]
                    logger.error(
                        "Rule failed when generating expression for "
                        "constraint %s with index %s:\n%s: %s"
                        % (self.name,
                           str(ndx),
                           type(err).__name__,
                           err))
                    raise
                self._setitem_when_not_present(ndx, tmp)
        timer.report()
Example #16
0
    def construct(self, data=None):
        """
        Construct the expression(s) for this objective.
        """
        if is_debug_set(logger):
            logger.debug("Constructing objective %s" % (self.name))
        if self._constructed:
            return
        timer = ConstructionTimer(self)
        self._constructed = True

        _init_expr = self._init_expr
        _init_sense = self._init_sense
        _init_rule = self.rule
        #
        # We no longer need these
        #
        self._init_expr = None
        self._init_sense = None
        # Utilities like DAE assume this stays around
        #self.rule = None

        if (_init_rule is None) and \
           (_init_expr is None):
            # No construction rule or expression specified.
            return

        _self_parent = self._parent()
        if not self.is_indexed():
            #
            # Scalar component
            #
            if _init_rule is None:
                tmp = _init_expr
            else:
                try:
                    tmp = _init_rule(_self_parent)
                except Exception:
                    err = sys.exc_info()[1]
                    logger.error("Rule failed when generating expression for "
                                 "objective %s:\n%s: %s" %
                                 (self.name, type(err).__name__, err))
                    raise
            if self._setitem_when_not_present(None, tmp) is not None:
                self.set_sense(_init_sense)

        else:
            if _init_expr is not None:
                raise IndexError("Cannot initialize multiple indices of an "
                                 "objective with a single expression")
            for ndx in self._index:
                try:
                    tmp = apply_indexed_rule(self, _init_rule, _self_parent,
                                             ndx)
                except Exception:
                    err = sys.exc_info()[1]
                    logger.error(
                        "Rule failed when generating expression for"
                        " objective %s with index %s:\n%s: %s" %
                        (self.name, str(ndx), type(err).__name__, err))
                    raise
                ans = self._setitem_when_not_present(ndx, tmp)
                if ans is not None:
                    ans.set_sense(_init_sense)
        timer.report()
Example #17
0
File: sos.py Project: yynst2/pyomo
    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 = is_debug_set(logger)
        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(), 'isordered',
                                   lambda *x: 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, 'isordered') and sosSet.isordered():
                            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()
Example #18
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()
Example #19
0
 def test_raw_construction_timer(self):
     a = ConstructionTimer(None)
     self.assertIn("ConstructionTimer object for NoneType (unknown); ",
                   str(a))
Example #20
0
File: param.py Project: Pyomo/pyomo
    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()
Example #21
0
    def construct(self, data=None):
        """
        Construct the expression(s) for this logical constraint.
        """
        if __debug__ and logger.isEnabledFor(logging.DEBUG):
            logger.debug("Constructing logical constraint %s" % self.name)
        if self._constructed:
            return
        timer = ConstructionTimer(self)
        self._constructed = True

        _init_expr = self._init_expr
        _init_rule = self.rule
        #
        # We no longer need these
        #
        self._init_expr = None
        # Utilities like DAE assume this stays around
        # self.rule = None

        if (_init_rule is None) and \
                (_init_expr is None):
            # No construction role or expression specified.
            return

        _self_parent = self._parent()
        if not self.is_indexed():
            #
            # Scalar component
            #
            if _init_rule is None:
                tmp = _init_expr
            else:
                try:
                    tmp = _init_rule(_self_parent)
                except Exception:
                    err = sys.exc_info()[1]
                    logger.error("Rule failed when generating expression for "
                                 "logical constraint %s:\n%s: %s" %
                                 (self.name, type(err).__name__, err))
                    raise
            self._setitem_when_not_present(None, tmp)

        else:
            if _init_expr is not None:
                raise IndexError(
                    "LogicalConstraint '%s': Cannot initialize multiple indices "
                    "of a logical constraint with a single expression" %
                    (self.name, ))

            for ndx in self._index:
                try:
                    tmp = apply_indexed_rule(self, _init_rule, _self_parent,
                                             ndx)
                except Exception:
                    err = sys.exc_info()[1]
                    logger.error(
                        "Rule failed when generating expression for "
                        "logical constraint %s with index %s:\n%s: %s" %
                        (self.name, str(ndx), type(err).__name__, err))
                    raise
                self._setitem_when_not_present(ndx, tmp)
        timer.report()
Example #22
0
File: sos.py Project: Pyomo/pyomo
    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()
Example #23
0
    def construct(self, data=None):
        """
        Construct the expression(s) for this objective.
        """
        if self._constructed:
            return
        self._constructed = True

        timer = ConstructionTimer(self)
        if is_debug_set(logger):
            logger.debug("Constructing objective %s" % (self.name))

        rule = self.rule
        try:
            # We do not (currently) accept data for constructing Objectives
            index = None
            assert data is None

            if rule is None:
                # If there is no rule, then we are immediately done.
                return

            if rule.constant() and self.is_indexed():
                raise IndexError(
                    "Objective '%s': Cannot initialize multiple indices "
                    "of an objective with a single expression" %
                    (self.name,) )

            block = self.parent_block()
            if rule.contains_indices():
                # The index is coming in externally; we need to validate it
                for index in rule.indices():
                    ans = self.__setitem__(index, rule(block, index))
                    if ans is not None:
                        self[index].set_sense(self._init_sense(block, index))
            elif not self.index_set().isfinite():
                # If the index is not finite, then we cannot iterate
                # over it.  Since the rule doesn't provide explicit
                # indices, then there is nothing we can do (the
                # assumption is that the user will trigger specific
                # indices to be created at a later time).
                pass
            else:
                # Bypass the index validation and create the member directly
                for index in self.index_set():
                    ans = self._setitem_when_not_present(
                        index, rule(block, index))
                    if ans is not None:
                        ans.set_sense(self._init_sense(block, index))
        except Exception:
            err = sys.exc_info()[1]
            logger.error(
                "Rule failed when generating expression for "
                "Objective %s with index %s:\n%s: %s"
                % (self.name,
                   str(index),
                   type(err).__name__,
                   err))
            raise
        finally:
            timer.report()
Example #24
0
    def construct(self, data=None):
        """
        Construct the _VarData objects for this variable
        """
        if self._constructed:
            return
        self._constructed = True

        timer = ConstructionTimer(self)
        if is_debug_set(logger):
            logger.debug("Constructing Variable %s" % (self.name, ))

        # Note: define 'index' to avoid 'variable referenced before
        # assignment' in the error message generated in the 'except:'
        # block below.
        index = None
        try:
            # We do not (currently) accept data for constructing Variables
            assert data is None

            if not self.index_set().isfinite() and self._dense:
                # Note: if the index is not finite, then we cannot
                # iterate over it.  This used to be fatal; now we
                # just warn
                logger.warning(
                    "Var '%s' indexed by a non-finite set, but declared "
                    "with 'dense=True'.  Reverting to 'dense=False' as "
                    "it is not possible to make this variable dense.  "
                    "This warning can be suppressed by specifying "
                    "'dense=False'" % (self.name, ))
                self._dense = False

            if (self._rule_init is not None
                    and self._rule_init.contains_indices()):
                # Historically we have allowed Vars to be initialized by
                # a sparse map (i.e., a dict containing only some of the
                # keys).  We will wrap the incoming initializer to map
                # KeyErrors to None
                self._rule_init = DefaultInitializer(self._rule_init, None,
                                                     KeyError)
                # The index is coming in externally; we need to validate it
                for index in self._rule_init.indices():
                    self[index]
                # If this is a dense object, we need to ensure that it
                # has been filled in.
                if self._dense:
                    for index in self.index_set():
                        if index not in self._data:
                            self._getitem_when_not_present(index)
            elif not self.is_indexed():
                # As there is only a single VarData to populate, just do
                # so and bypass all special-case testing below
                self._getitem_when_not_present(None)
            elif self._dense:
                # Special case: initialize every VarData.  For the
                # initializers that are constant, we can avoid
                # re-calling (and re-validating) the inputs in certain
                # cases.  To support this, we will create the first
                # _VarData and then use it as a template to initialize
                # (constant portions of) every VarData so as to not
                # repeat all the domain/bounds validation.
                try:
                    ref = self._getitem_when_not_present(
                        next(iter(self.index_set())))
                except StopIteration:
                    # Empty index!
                    return
                call_domain_rule = not self._rule_domain.constant()
                call_bounds_rule = self._rule_bounds is not None and (
                    not self._rule_bounds.constant())
                call_init_rule = self._rule_init is not None and (
                    not self._rule_init.constant()
                    # If either the domain or bounds change, then we
                    # need to re-verify the initial value, even if it is
                    # constant:
                    or call_domain_rule or call_bounds_rule)
                # Initialize all the component datas with the common data
                for index in self.index_set():
                    self._data[index] = self._ComponentDataClass.copy(ref)
                    # NOTE: This is a special case where a key, value pair is
                    # added to the _data dictionary without calling
                    # _getitem_when_not_present, which is why we need to set the
                    # index here.
                    self._data[index]._index = index
                # Now go back and initialize any index-specific data
                block = self.parent_block()
                if call_domain_rule:
                    for index, obj in self._data.items():
                        # We can directly set the attribute (not the
                        # property) because the SetInitializer ensures
                        # that the value is a proper Set.
                        obj._domain = self._rule_domain(block, index)
                if call_bounds_rule:
                    for index, obj in self._data.items():
                        obj.lower, obj.upper = self._rule_bounds(block, index)
                if call_init_rule:
                    for index, obj in self._data.items():
                        obj.set_value(self._rule_init(block, index))
            else:
                # non-dense indexed var with generic
                # (non-index-containing) initializer: nothing to do
                pass

        except Exception:
            err = sys.exc_info()[1]
            logger.error("Rule failed when initializing variable for "
                         "Var %s with index %s:\n%s: %s" %
                         (self.name, str(index), type(err).__name__, err))
            raise
        finally:
            timer.report()