Example #1
0
    def construct(self, data=None):
        """Construct this component."""
        if is_debug_set(logger):   #pragma:nocover
            try:
                name = str(self.name)
            except:
                name = type(self)
            logger.debug(
                "Constructing Variable, name=%s, from data=%s"
                % (name, str(data)))

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

        #
        # Construct _BooleanVarData 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(component=None)
                cdata._component = self_weakref
                self._data[ndx] = cdata
            self._initialize_members(self._index)
        timer.report()
Example #2
0
 def construct(self, data=None):
     """ Apply the rule to construct values in this set """
     if is_debug_set(logger):  #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 #3
0
    def construct(self, data=None):
        """
        Initialize this component.
        """
        if self._constructed:
            return
        timer = ConstructionTimer(self)

        nom = self._nominal

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

        else:
            self_weakref = weakref_ref(self)
            for ndx in self._index:
                if ndx not in self._data:
                    self._data[ndx] = _UncParamData(self)
                self._data[ndx]._nominal = nom[ndx]
                self._data[ndx]._value = nom[ndx]
                self._component = self_weakref
                if self._bounds_init_value is not None:
                    lb, ub = self._bounds_init_value
                    self._data[ndx]._lb = lb
                    self._data[ndx]._ub = ub

        self._constructed = True
        timer.report()
Example #4
0
    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 #5
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

        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 #6
0
    def construct(self, data=None):
        """
        Construct the expression(s) for this constraint.
        """
        if self._constructed:
            return
        self._constructed=True

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

        try:
            # We do not (currently) accept data for constructing Constraints
            assert data is None

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

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

            index = None
            block = self.parent_block()
            if self.rule.contains_indices():
                # The index is coming in externally; we need to validate it
                for index in self.rule.indices():
                    self[index] = self.rule(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():
                    self._setitem_when_not_present(
                        index, self.rule(block, index)
                    )
        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(index),
                   type(err).__name__,
                   err))
            raise
        finally:
            timer.report()
Example #7
0
    def construct(self, data=None):
        if is_debug_set(logger):
            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(ndx))
                    raise ValueError( _rule_returned_none_error % (_name,) )
                if expr is Disjunction.Skip:
                    continue
                self._setitem_when_not_present(ndx, expr)
        timer.report()
Example #8
0
    def construct(self, data=None):
        """Initialize the Arc"""
        if is_debug_set(logger):
            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 #9
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 #10
0
 def construct(self, data=None):
     if is_debug_set(logger):  #pragma:nocover
         try:
             name = str(self.name)
         except:
             name = type(self)
         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 #11
0
    def construct(self, data=None):
        """ Apply the rule to construct values in this set """

        if is_debug_set(logger):
            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 #12
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 #13
0
 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 #14
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 #15
0
    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])
        timer.report()
Example #16
0
    def construct(self, data=None):
        """
        Constructs this component, applying rule if it exists.
        """
        if is_debug_set(logger):
            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 #17
0
    def construct(self, data=None):
        """ Apply the rule to construct values in this set """
        if self._constructed:
            return
        self._constructed = True

        timer = ConstructionTimer(self)
        if is_debug_set(logger):
            logger.debug("Constructing Expression, name=%s, from data=%s" %
                         (self.name, str(data)))

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

            if rule is None:
                # Historically, Expression objects were dense (but None):
                rule = Initializer(lambda *args: None)
                # If there is no rule, then we are immediately done.
                #return

            block = self.parent_block()
            if rule.contains_indices():
                # The index is coming in externally; we need to validate it
                for index in rule.indices():
                    self[index] = rule(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():
                    self._setitem_when_not_present(index, rule(block, index))
        except Exception:
            err = sys.exc_info()[1]
            logger.error("Rule failed when generating expression for "
                         "Expression %s with index %s:\n%s: %s" %
                         (self.name, str(index), type(err).__name__, err))
            raise
        finally:
            timer.report()
Example #18
0
    def construct(self, data=None):
        """ Apply the rule to construct values in this set """
        if self._constructed:
            return
        self._constructed = True

        timer = ConstructionTimer(self)
        if is_debug_set(logger):
            logger.debug("Constructing Expression, name=%s, from data=%s" %
                         (self.name, str(data)))

        try:
            # We do not (currently) accept data for constructing Constraints
            assert data is None
            self._construct_from_rule_using_setitem()
        finally:
            timer.report()
Example #19
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 #20
0
 def construct(self, data=None):
     if is_debug_set(logger):  #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 #21
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 #22
0
    def construct(self, data=None):
        """
        Construct the ExternalGreyBoxBlockDatas
        """
        if self._constructed:
            return
        # Do not set the constructed flag - Block.construct() will do that

        timer = ConstructionTimer(self)
        if is_debug_set(logger):
            logger.debug("Constructing external grey box model %s" %
                         (self.name))

        super(ExternalGreyBoxBlock, self).construct(data)

        if self._init_model is not None:
            block = self.parent_block()
            for index, data in iteritems(self):
                data.set_external_model(self._init_model(block, index))
Example #23
0
    def construct(self, data=None):
        """
        Construct the expression(s) for this complementarity condition.
        """
        if is_debug_set(logger):
            logger.debug("Constructing complementarity list %s", self.name)
        if self._constructed:
            return
        timer = ConstructionTimer(self)
        self._constructed = True

        if self._init_rule is not None:
            _init = self._init_rule(self.parent_block(), ())
            for cc in iter(_init):
                if cc is ComplementarityList.End:
                    break
                if cc is Complementarity.Skip:
                    continue
                self.add(cc)

        timer.report()
Example #24
0
    def construct(self, values=None):
        """ Constructs a :py:class:`ContinuousSet` component

        """
        if self._constructed:
            return
        timer = ConstructionTimer(self)
        super(ContinuousSet, self).construct(values)

        for val in self:
            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")

        # 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.
        for bnd in self.domain.bounds():
            # Note: the base class constructor ensures that any declared
            # set members are already within the bounds.
            if bnd is not None and bnd not in self:
                self.add(bnd)

        if None in self.bounds():
            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 len(self) < 2:
            # (reachable if lb==ub)
            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 #25
0
    def construct(self, data=None):
        """
        Initialize this component.
        """
        if self._constructed:
            return
        timer = ConstructionTimer(self)

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

        else:
            self_weakref = weakref_ref(self)
            for ndx in self._index:
                if ndx not in self._data:
                    self._data[ndx] = _AdjustableVarData(self)
                self._component = self_weakref
            self._initialize_members(self._index)

        self._constructed = True
        timer.report()
Example #26
0
    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 #27
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:
            logger.debug("Constructing complementarity list %s", self.name)
        if self._constructed:
            return
        timer = ConstructionTimer(self)
        self._constructed = True

        if self._init_rule is not None:
            _init = self._init_rule(self.parent_block(), ())
            for cc in iter(_init):
                if cc is ComplementarityList.End:
                    break
                if cc is Complementarity.Skip:
                    continue
                self.add(cc)

        timer.report()
Example #28
0
    def construct(self, data=None):
        """Construct this component."""
        if is_debug_set(logger):  #pragma:nocover
            try:
                name = str(self.name)
            except:
                name = type(self)
            logger.debug("Constructing Variable, name=%s, from data=%s" %
                         (name, str(data)))

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

        #
        # Construct _BooleanVarData 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_set:
                cdata = self._ComponentDataClass(component=None)
                cdata._component = self_weakref
                self._data[ndx] = cdata
                # 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.
                cdata._index = ndx
            self._initialize_members(self._index_set)
        timer.report()
Example #29
0
    def construct(self, data=None):
        """
        Construct the expression(s) for this logical constraint.
        """
        if is_debug_set(logger):
            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 #30
0
 def test_raw_construction_timer(self):
     a = ConstructionTimer(None)
     self.assertIn(
         "ConstructionTimer object for NoneType (unknown); ",
         str(a))