Esempio n. 1
0
                    if arg.__class__ is _ProductExpression:
                        _substitute_vars(arg._numerator, var)
                        _substitute_vars(arg._denominator, var)
                    else:
                        _substitute_vars(arg._args, var)
                elif isinstance(arg, _ConnectorValue):
                    v = arg.vars[var]
                    if v.is_expression():
                        v = v.clone()
                    args[idx] = _substitute_var(v, var) 
                elif isinstance(arg, VarList):
                    args[idx] = arg.add()

        for var in ref.vars.iterkeys():
            if var in skip:
                continue
            if constraint.body.is_expression():
                c = _substitute_var(constraint.body.clone(), var)
            else:
                c = _substitute_var(constraint.body, var)
            if constraint.equality:
                cList.append( ( c, constraint.upper ) )
            else:
                cList.append( ( constraint.lower, c, constraint.upper ) )

transform = ConnectorExpander()


register_component(Connector, "A bundle of variables that can be manipilated together.")

Esempio n. 2
0

class AbstractModel(Model):
    """
    An abstract optimization model that defers construction of
    components.
    """
    def __init__(self, *args, **kwds):
        Model.__init__(self, *args, **kwds)


#
# Create a Model and record all the default attributes, methods, etc.
# These will be assumes to be the set of illegal component names.
#
# Note that creating a Model will result in a warning, so we will
# (arbitrarily) choose a ConcreteModel as the definitive list of
# reserved names.
#
Model._Block_reserved_words = set(dir(ConcreteModel()))

register_component(
    Model, 'Model objects can be used as a component of other models.')
register_component(
    ConcreteModel,
    'A concrete optimization model that does not defer construction of components.'
)
register_component(
    AbstractModel,
    'An abstract optimization model that defers construction of components.')
Esempio n. 3
0
        _init = _LinearMatrixConstraintData
        self._data = tuple(
            _init(i, component=self) for i in xrange(len(self._range_types)))

    #
    # Override some IndexedComponent methods
    #

    def __getitem__(self, key):
        return self._data[key]

    def __len__(self):
        return self._data.__len__()

    def __iter__(self):
        return iter(i for i in xrange(len(self)))

    #
    # Remove methods that allow modifying this constraint
    #

    def add(self, index, expr):
        raise NotImplementedError

    def __delitem__(self):
        raise NotImplementedError


register_component(MatrixConstraint,
                   "A set of constraint expressions in Ax=b form.")
Esempio n. 4
0
                """Evaluating the numeric value of parameter '%s' before the Param has been
            constructed (there is currently no value to return).""" %
                self.cname(True))

    def set_value(self, value):
        if self._constructed and not self._mutable:
            raise TypeError(
                """Attempting to set the value of the immutable parameter %s after the
parameter has been constructed.  If you intend to change the value of
this parameter dynamically, please declare the parameter as mutable
[i.e., Param(mutable=True)]""" % (self.cname(True), ))
        self[None] = value

    def is_constant(self):
        """
        Returns False because this is not a constant in an expression.
        """
        return self._constructed and not self._mutable


class IndexedParam(Param):
    def __call__(self, exception=True):
        """Compute the value of the parameter"""
        if exception:
            msg = 'Cannot compute the value of an array of parameters'
            raise TypeError(msg)


register_component(Param,
                   "Parameter data that is used to define a model instance.")
Esempio n. 5
0
class SubModel(SimpleBlock):

    def __init__(self, *args, **kwargs):
        """Constructor"""
        #
        # Collect kwargs for SubModel
        #
        _rule = kwargs.pop('rule', None )
        _fixed = kwargs.pop('fixed', None )
        _var = kwargs.pop('var', None )     # Not documented
        #
        # Initialize the SimpleBlock
        #
        kwargs.setdefault('ctype', SubModel)
        SimpleBlock.__init__(self, *args, **kwargs)
        #
        # Initialize from kwargs
        #
        self._rule = _rule
        if isinstance(_fixed, Component):
            self._fixed = [_fixed]
        else:
            self._fixed = _fixed
        if isinstance(_var, Component):
            self._var = [_var]
        else:
            self._var = _var

register_component(SubModel, "A submodel in a bilevel program")
Esempio n. 6
0
        Check to see if all the ContinuousSets this derivative is taken with
        respect to have been discretized.
        """
        for i in self._wrt:
            if 'scheme' not in i.get_discretization_info():
                return False
        return True

    def get_state_var(self):
        return self._sVar

    def get_derivative_expression(self):
        """
        Returns the current discretization expression for this derivative or creates
        an access function to its StateVar the first time this method is called.
        The expression gets built up as the discretization transformations are 
        sequentially applied to each ContinuousSet in the model.
        """
        try:
            return self._expr
        except:
            self._expr = create_access_function(self._sVar)
            return self._expr

    def set_derivative_expression(self, expr):
        self._expr = expr


register_component(DerivativeVar,
                   "Derivative of a State variable in a DAE model.")
Esempio n. 7
0
        Test if the specified element in this set.
        """
        try:
            x = element - self._start_val
            if x % self._step_val != 0:
                #
                # If we are doing floating-point arithmetic, there is a
                # chance that we are seeing roundoff error...
                #
                if math.fabs((x + 1e-7) % self._step_val) > 2e-7:
                    return False
            if element < self._bounds[0] or element > self._bounds[1]:
                return False
        except:
            #
            # This exception is triggered when type(element) is not int or float.
            #
            return False
        #
        # Now see if the element if filtered or invalid.
        #
        if self.filter is not None and not self.filter(element):
            return False
        if self.validate is not None and not self.validate(self, element):
            return False
        return True


register_component(RangeSet, "A sequence of numeric values.  RangeSet(start,end,step) is a sequence starting a value 'start', and increasing in values by 'step' until a value greater than or equal to 'end' is reached.")

Esempio n. 8
0
        IndexedComponent.__init__(self, *args, **kwd)
        #
        if not type(self._rule) is types.FunctionType:
            raise ValueError("BuildCheck  must have an 'rule' option specified whose value is a function")

    def _pprint(self):
        return ([], None, None, None)

    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
        self._constructed=True
        #
        if None in self._index:
            # 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)))

register_component(BuildCheck, "A component that performs tests during model construction.  The action rule is applied to every index value.")
Esempio n. 9
0
        logger.warning(
            "DEPRECATION WARNING: Suffix.extractValues() is replaced "
            " with the dict-interface method Suffix.items().")
        # As implemented by MutableMapping
        return list(self.items())

    #
    # Override a few methods to make sure the ActiveComponent versions are
    # called. We can't just switch the inheritance order due to
    # complications with __setstate__
    #

    def pprint(self, *args, **kwds):
        return ActiveComponent.pprint(self, *args, **kwds)

    def __str__(self):
        return ActiveComponent.__str__(self)

    #
    # Override NotImplementedError messages on ComponentMap base class
    #

    def __eq__(self, other):
        raise NotImplementedError("Suffix components are not comparable")

    def __ne__(self, other):
        raise NotImplementedError("Suffix components are not comparable")


register_component(Suffix, "Declare a container for extraneous model data")
Esempio n. 10
0
            return False

        setlist = []
        if self.dim() == 1:
            setlist =[self.index_set(),]
        else:
            setlist = self._implicit_subsets

        for i in setlist:
            if i.type() is ContinuousSet:
                if 'scheme' not in i.get_discretization_info():
                    return False
        return True
    #
    # Leaving this method for backward compatibility reasons
    # Note: It allows adding members outside of self._index.
    #       This has always been the case. Not sure there is
    #       any reason to maintain a reference to a separate
    #       index set if we allow this.
    #
    def add(self, index, expr):
        """Add an expression with a given index."""
        if (type(expr) is tuple) and \
           (expr == Expression.Skip):
            return None
        cdata = _GeneralExpressionData(expr, component=self)
        self._data[index] = cdata
        return cdata

register_component(Integral, "Integral Expression in a DAE model.")
Esempio n. 11
0
                                     "instead of ObjectiveList.End")
                if (expr.__class__ is tuple) and \
                   (expr == ObjectiveList.End):
                    return
                self.add(expr, sense=_init_sense)

        else:

            for expr in _generator:
                if expr is None:
                    raise ValueError("Objective generator returned None "
                                     "instead of ObjectiveList.End")
                if (expr.__class__ is tuple) and \
                   (expr == ObjectiveList.End):
                    return
                self.add(expr, sense=_init_sense)

    def add(self, expr, sense=minimize):
        """Add an objective to the list."""
        cdata = self._check_skip_add(self._nobjectives + 1, expr)
        self._nobjectives += 1
        self._index.add(self._nobjectives)
        if cdata is not None:
            cdata.set_sense(sense)
            self._data[self._nobjectives] = cdata
        return cdata


register_component(Objective, "Expressions that are minimized or maximized.")
register_component(ObjectiveList, "A list of objective expressions.")
Esempio n. 12
0
    def is_fully_discretized(self):
        """
        Check to see if all the ContinuousSets this derivative is taken with
        respect to have been discretized.
        """
        for i in self._wrt:
            if 'scheme' not in i.get_discretization_info():
                return False
        return True

    def get_state_var(self):
        return self._sVar

    def get_derivative_expression(self):
        """
        Returns the current discretization expression for this derivative or creates
        an access function to its StateVar the first time this method is called.
        The expression gets built up as the discretization transformations are 
        sequentially applied to each ContinuousSet in the model.
        """
        try:
            return self._expr
        except:
            self._expr = create_access_function(self._sVar)
            return self._expr

    def set_derivative_expression(self,expr):
        self._expr = expr

register_component(DerivativeVar, "Derivative of a State variable in a DAE model.")
Esempio n. 13
0
        """
        logger.warning("DEPRECATION WARNING: Suffix.extractValues() is replaced "
                       " with the dict-interface method Suffix.items().")
        # As implemented by MutableMapping
        return list(self.items())

    #
    # Override a few methods to make sure the ActiveComponent versions are
    # called. We can't just switch the inheritance order due to
    # complications with __setstate__
    #

    def pprint(self, *args, **kwds):
        return ActiveComponent.pprint(self, *args, **kwds)

    def __str__(self):
        return ActiveComponent.__str__(self)

    #
    # Override NotImplementedError messages on ComponentMap base class
    #

    def __eq__(self, other):
        raise NotImplementedError("Suffix components are not comparable")

    def __ne__(self, other):
        raise NotImplementedError("Suffix components are not comparable")


register_component(Suffix, "Declare a container for extraneous model data")
Esempio n. 14
0
        if exception:
            raise ValueError( """Evaluating the numeric value of parameter '%s' before the Param has been
            constructed (there is currently no value to return).""" % self.name )

    def set_value(self, value):
        if self._constructed and not self._mutable:
            raise TypeError(
"""Attempting to set the value of the immutable parameter %s after the
parameter has been constructed.  If you intend to change the value of
this parameter dynamically, please declare the parameter as mutable
[i.e., Param(mutable=True)]""" % (self.name,))
        self[None] = value

    def is_constant(self):
        """
        Returns False because this is not a constant in an expression.
        """
        return self._constructed and not self._mutable


class IndexedParam(Param):

    def __call__(self, exception=True):
        """Compute the value of the parameter"""
        if exception:
            msg = 'Cannot compute the value of an array of parameters'
            raise TypeError(msg)

register_component(Param, "Parameter data that is used to define a model instance.")

Esempio n. 15
0
        _init = _LinearMatrixConstraintData
        self._data = tuple(_init(i, component=self)
                           for i in xrange(len(self._range_types)))

    #
    # Override some IndexedComponent methods
    #

    def __getitem__(self, key):
        return self._data[key]

    def __len__(self):
        return self._data.__len__()

    def __iter__(self):
        return iter(i for i in xrange(len(self)))

    #
    # Remove methods that allow modifying this constraint
    #

    def add(self, index, expr):
        raise NotImplementedError

    def __delitem__(self):
        raise NotImplementedError

register_component(MatrixConstraint,
                   "A set of constraint expressions in Ax=b form.")
Esempio n. 16
0
            if not val is None:
                ostream.write("\t"+str(val)+'\n')
            ostream.write("\t\tType="+str(self._data[val].level)+'\n')
            ostream.write("\t\tWeight : Variable\n")
            for var, weight in self._data[val].get_items():
                ostream.write("\t\t"+str(weight)+' : '+var.cname(True)+'\n')


# Since this class derives from Component and Component.__getstate__
# just packs up the entire __dict__ into the state dict, there s
# nothing special that we need to do here.  We will just defer to the
# super() get/set state.  Since all of our get/set state methods
# rely on super() to traverse the MRO, this will automatically pick
# up both the Component and Data base classes.

class SimpleSOSConstraint(SOSConstraint, _SOSConstraintData):

    def __init__(self, *args, **kwd):
        _SOSConstraintData.__init__(self, self)
        SOSConstraint.__init__(self, *args, **kwd)


class IndexedSOSConstraint(SOSConstraint):

    def __init__(self, *args, **kwds):
        super(IndexedSOSConstraint,self).__init__(*args, **kwds)


register_component(SOSConstraint, "SOS constraint expressions.")

Esempio n. 17
0
    def _pprint(self):
        return ([
            ("Size", len(self)),
            ("Index", self._index if self.is_indexed() else None),
            ("Active", self.active),
        ], None, None, None)

    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
        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)


register_component(
    BuildAction,
    "A component that performs arbitrary actions during model construction.  The action rule is applied to every index value."
)
Esempio n. 18
0
                        "ConstraintList '%s': rule returned None "
                        "instead of ConstraintList.End" % (self.name,) )
                if (expr.__class__ is tuple) and \
                   (expr == ConstraintList.End):
                    return
                self.add(expr)

        else:

            for expr in _generator:
                if expr is None:
                    raise ValueError(
                        "ConstraintList '%s': generator returned None "
                        "instead of ConstraintList.End" % (self.name,) )
                if (expr.__class__ is tuple) and \
                   (expr == ConstraintList.End):
                    return
                self.add(expr)

    def add(self, expr):
        """Add a constraint with an implicit index."""
        cdata = self._check_skip_add(self._nconstraints + 1, expr)
        self._nconstraints += 1
        self._index.add(self._nconstraints)
        if cdata is not None:
            self._data[self._nconstraints] = cdata
        return cdata

register_component(Constraint, "General constraint expressions.")
register_component(ConstraintList, "A list of constraint expressions.")
Esempio n. 19
0
                   (expr == ObjectiveList.End):
                    return
                self.add(expr, sense=_init_sense)

        else:

            for expr in _generator:
                if expr is None:
                    raise ValueError(
                        "Objective generator returned None "
                        "instead of ObjectiveList.End")
                if (expr.__class__ is tuple) and \
                   (expr == ObjectiveList.End):
                    return
                self.add(expr, sense=_init_sense)

    def add(self, expr, sense=minimize):
        """Add an objective to the list."""
        cdata = self._check_skip_add(self._nobjectives + 1, expr)
        self._nobjectives += 1
        self._index.add(self._nobjectives)
        if cdata is not None:
            cdata.set_sense(sense)
            self._data[self._nobjectives] = cdata
        return cdata

register_component(Objective,
                   "Expressions that are minimized or maximized.")
register_component(ObjectiveList,
                   "A list of objective expressions.")
Esempio n. 20
0
        Returns
        -------
        :py:class:`Var<pyomo.environ.Var>`
        """
        return self._sVar

    def get_derivative_expression(self):
        """
        Returns the current discretization expression for this derivative or
        creates an access function to its :py:class:`Var` the first time
        this method is called. The expression gets built up as the
        discretization transformations are sequentially applied to each
        :py:class:`ContinuousSet` in the model.
        """
        try:
            return self._expr
        except:
            self._expr = create_access_function(self._sVar)
            return self._expr

    def set_derivative_expression(self, expr):
        """ Sets``_expr``, an expression representing the discretization
        equations linking the :class:`DerivativeVar` to its state
        :class:`Var`
        """
        self._expr = expr

register_component(DerivativeVar,
                   "Derivative of a Var in a DAE model.")
Esempio n. 21
0
            raise ValueError("Unknown model transformation '%s'" % name)
        return xfrm.apply_to(self, **kwds)


class ConcreteModel(Model):
    """
    A concrete optimization model that does not defer construction of
    components.
    """

    def __init__(self, *args, **kwds):
        kwds['concrete'] = True
        Model.__init__(self, *args, **kwds)


class AbstractModel(Model):
    """
    An abstract optimization model that defers construction of
    components.
    """

    def __init__(self, *args, **kwds):
        Model.__init__(self, *args, **kwds)



register_component(Model, 'Model objects can be used as a component of other models.')
register_component(ConcreteModel, 'A concrete optimization model that does not defer construction of components.')
register_component(AbstractModel, 'An abstract optimization model that defers construction of components.')

Esempio n. 22
0
            ostream.write("\n")
        for val in self._data:
            if not val is None:
                ostream.write("\t" + str(val) + '\n')
            ostream.write("\t\tType=" + str(self._data[val].level) + '\n')
            ostream.write("\t\tWeight : Variable\n")
            for var, weight in self._data[val].get_items():
                ostream.write("\t\t" + str(weight) + ' : ' + var.name + '\n')


# Since this class derives from Component and Component.__getstate__
# just packs up the entire __dict__ into the state dict, there s
# nothing special that we need to do here.  We will just defer to the
# super() get/set state.  Since all of our get/set state methods
# rely on super() to traverse the MRO, this will automatically pick
# up both the Component and Data base classes.


class SimpleSOSConstraint(SOSConstraint, _SOSConstraintData):
    def __init__(self, *args, **kwd):
        _SOSConstraintData.__init__(self, self)
        SOSConstraint.__init__(self, *args, **kwd)


class IndexedSOSConstraint(SOSConstraint):
    def __init__(self, *args, **kwds):
        super(IndexedSOSConstraint, self).__init__(*args, **kwds)


register_component(SOSConstraint, "SOS constraint expressions.")
Esempio n. 23
0
    #
    # Since this class derives from Component and Component.__getstate__
    # just packs up the entire __dict__ into the state dict, we do not
    # need to define the __getstate__ or __setstate__ methods.
    # We just defer to the super() get/set state.  Since all of our
    # get/set state methods rely on super() to traverse the MRO, this
    # will automatically pick up both the Component and Data base classes.
    #


class IndexedConnector(Connector):
    """An array of connectors"""
    pass


register_component(
    Connector, "A bundle of variables that can be manipilated together.")


class ConnectorExpander(Plugin):
    implements(IPyomoScriptModifyInstance)

    def apply(self, **kwds):
        instance = kwds.pop('instance')
        xform = TransformationFactory('core.expand_connectors')
        xform.apply_to(instance, **kwds)
        return instance

transform = ConnectorExpander()
Esempio n. 24
0
            setlist = [
                self.index_set(),
            ]
        else:
            setlist = self._implicit_subsets

        for i in setlist:
            if i.type() is ContinuousSet:
                if 'scheme' not in i.get_discretization_info():
                    return False
        return True

    #
    # Leaving this method for backward compatibility reasons
    # Note: It allows adding members outside of self._index.
    #       This has always been the case. Not sure there is
    #       any reason to maintain a reference to a separate
    #       index set if we allow this.
    #
    def add(self, index, expr):
        """Add an expression with a given index."""
        if (type(expr) is tuple) and \
           (expr == Expression.Skip):
            return None
        cdata = _GeneralExpressionData(expr, component=self)
        self._data[index] = cdata
        return cdata


register_component(Integral, "Integral Expression in a DAE model.")
Esempio n. 25
0
    free=unfix

class VarList(IndexedVar):
    """
    Variable-length indexed variable objects used to construct Pyomo models.
    """

    def __init__(self, **kwds):
        kwds['dense'] = False
        args = (Set(),)
        self._nvars = 0
        IndexedVar.__init__(self, *args, **kwds)

    def construct(self, data=None):
        """Construct this component."""
        if __debug__ and logger.isEnabledFor(logging.DEBUG):
            logger.debug("Constructing variable list %s",self.cname(True))
        IndexedVar.construct(self, data)

    def add(self):
        """Add a variable to this list."""
        self._nvars += 1
        self._index.add(self._nvars)
        vardata = self._data[self._nvars] = _GeneralVarData(Reals, component=self)
        self._initialize_members([self._nvars])
        return vardata

register_component(Var, "Decision variables.")
register_component(VarList, "List of decision variables.")

Esempio n. 26
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 Check, name=" + self.name)
        #
        if self._constructed:  #pragma:nocover
            return
        self._constructed = True
        #
        if None in self._index:
            # 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)))


register_component(
    BuildCheck,
    "A component that performs tests during model construction.  The action rule is applied to every index value."
)
Esempio n. 27
0
        try:
            x = element - self._start_val
            if x % self._step_val != 0:
                #
                # If we are doing floating-point arithmetic, there is a
                # chance that we are seeing roundoff error...
                #
                if math.fabs((x + 1e-7) % self._step_val) > 2e-7:
                    return False
            if element < self._bounds[0] or element > self._bounds[1]:
                return False
        except:
            #
            # This exception is triggered when type(element) is not int or float.
            #
            return False
        #
        # Now see if the element if filtered or invalid.
        #
        if self.filter is not None and not self.filter(element):
            return False
        if self.validate is not None and not self.validate(self, element):
            return False
        return True


register_component(
    RangeSet,
    "A sequence of numeric values.  RangeSet(start,end,step) is a sequence starting a value 'start', and increasing in values by 'step' until a value greater than or equal to 'end' is reached."
)
Esempio n. 28
0
class VarList(IndexedVar):
    """
    Variable-length indexed variable objects used to construct Pyomo models.
    """

    def __init__(self, **kwds):
        kwds['dense'] = False
        args = (Set(),)
        self._nvars = 0
        IndexedVar.__init__(self, *args, **kwds)

    def construct(self, data=None):
        """Construct this component."""
        if __debug__ and logger.isEnabledFor(logging.DEBUG):
            logger.debug("Constructing variable list %s", self.name)
        IndexedVar.construct(self, data)

    def add(self):
        """Add a variable to this list."""
        self._nvars += 1
        self._index.add(self._nvars)
        vardata = self._data[self._nvars] = \
            _GeneralVarData(domain=self._domain_init_value,
                            component=self)
        self._initialize_members([self._nvars])
        return vardata

register_component(Var, "Decision variables.")
register_component(VarList, "List of decision variables.")

Esempio n. 29
0
                                     (self.name, ))
                if (expr.__class__ is tuple) and \
                   (expr == ConstraintList.End):
                    return
                self.add(expr)

        else:

            for expr in _generator:
                if expr is None:
                    raise ValueError(
                        "ConstraintList '%s': generator returned None "
                        "instead of ConstraintList.End" % (self.name, ))
                if (expr.__class__ is tuple) and \
                   (expr == ConstraintList.End):
                    return
                self.add(expr)

    def add(self, expr):
        """Add a constraint with an implicit index."""
        cdata = self._check_skip_add(self._nconstraints + 1, expr)
        self._nconstraints += 1
        self._index.add(self._nconstraints)
        if cdata is not None:
            self._data[self._nconstraints] = cdata
        return cdata


register_component(Constraint, "General constraint expressions.")
register_component(ConstraintList, "A list of constraint expressions.")
Esempio n. 30
0
        if (type(expr) is tuple) and \
           (expr == Expression.Skip):
            raise ValueError(
                "Expression.Skip can not be assigned "
                "to an Expression that is not indexed: %s"
                % (self.name))
        self.set_value(expr)
        return self

class IndexedExpression(Expression):

    #
    # Leaving this method for backward compatibility reasons
    # Note: It allows adding members outside of self._index.
    #       This has always been the case. Not sure there is
    #       any reason to maintain a reference to a separate
    #       index set if we allow this.
    #
    def add(self, index, expr):
        """Add an expression with a given index."""
        if (type(expr) is tuple) and \
           (expr == Expression.Skip):
            return None
        cdata = _GeneralExpressionData(expr, component=self)
        self._data[index] = cdata
        return cdata

register_component(
    Expression,
    "Named expressions that can be used in other expressions.")
Esempio n. 31
0
        if (type(expr) is tuple) and \
           (expr == Expression.Skip):
            raise ValueError("Expression.Skip can not be assigned "
                             "to an Expression that is not indexed: %s" %
                             (self.name))
        self.set_value(expr)
        return self


class IndexedExpression(Expression):

    #
    # Leaving this method for backward compatibility reasons
    # Note: It allows adding members outside of self._index.
    #       This has always been the case. Not sure there is
    #       any reason to maintain a reference to a separate
    #       index set if we allow this.
    #
    def add(self, index, expr):
        """Add an expression with a given index."""
        if (type(expr) is tuple) and \
           (expr == Expression.Skip):
            return None
        cdata = _GeneralExpressionData(expr, component=self)
        self._data[index] = cdata
        return cdata


register_component(Expression,
                   "Named expressions that can be used in other expressions.")
Esempio n. 32
0
        #
        if not type(self._rule) is types.FunctionType:
            raise ValueError("BuildAction must have an 'rule' option specified whose value is a function")

    def _pprint(self):
        return ([("Size", len(self)),
                 ("Index", self._index \
                      if self._index != UnindexedComponent_set else None),
                 ("Active", self.active),]
                 , None, None, None)

    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
        self._constructed=True
        #
        if None in self._index:
            # Scalar component
            self._rule(self._parent())
        else:
            # Indexed component
            for index in self._index:
                apply_indexed_rule(self, self._rule, self._parent(), index)


register_component(BuildAction, "A component that performs arbitrary actions during model construction.  The action rule is applied to every index value.")