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.")
#tmp.append(self.disj) tmp = tuple(tmp) disjuncts = self.disj._disjunction_rule(*tmp) elif type(self.disj._disjunctive_set) in (tuple, list): # explicit disjunction over a user-specified list of disjuncts disjuncts = self.disj._disjunctive_set elif isinstance(self.disj._disjunctive_set, Disjunct): # pick one of all disjuncts if len(self.disj._disjunctive_set._data): disjuncts = self.disj._data.values() else: disjuncts = (self.disj._disjunctive_set) else: msg = 'Bad expression passed to Disjunction' raise TypeError(msg) for d in disjuncts: if not isinstance(d, _DisjunctData): msg = 'Non-disjunct (type="%s") found in ' \ 'disjunctive set for disjunction %s' % \ (type(d), self.disj.name) raise ValueError(msg) self.disj._disjuncts[normalize_index(idx)] = disjuncts # sum(disjuncts) == 1 return (sum(d.indicator_var for d in disjuncts), 1.0) register_component(Disjunct, "Disjunctive blocks.") register_component(Disjunction, "Disjunction expressions.")
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.")
while True: val = len(self._index) + 1 if generate_debug_messages: logger.debug(" Constructing objective index " + str(val)) expr = apply_indexed_rule(self, _init_rule, _self_parent, val) if (expr.__class__ is tuple) and \ (expr == ObjectiveList.End): return self.add(expr, sense=_init_sense) else: for expr in _generator: 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.""" next_idx = len(self._index) + 1 self._index.add(next_idx) ans = self.__setitem__(next_idx, expr) if ans is not None: ans.set_sense(sense) return ans register_component(Objective, "Expressions that are minimized or maximized.") register_component(ObjectiveList, "A list of objective expressions.")
# # 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()
""" # 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): """Not implemented.""" raise NotImplementedError("Suffix components are not comparable") def __ne__(self, other): """Not implemented.""" raise NotImplementedError("Suffix components are not comparable") register_component(Suffix, "Declare a container for extraneous model data")
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." )
if __debug__ and logger.isEnabledFor(logging.DEBUG): logger.debug("Constructing variable list %s", self.name) # We need to ensure that the indices needed for initialization are # added to the underlying implicit set. We *could* verify that the # indices in the initialization dict are all sequential integers, # OR we can just add the correct number of sequential integers and # then let _validate_index complain when we set the value. if self._value_init_value.__class__ is dict: for i in xrange(len(self._value_init_value)): self._index.add(i + 1) super(VarList, self).construct(data) # Note that the current Var initializer silently ignores # initialization data that is not in the underlying index set. To # ensure that at least here all initialization data is added to the # VarList (so we get potential domain errors), we will re-set # everything. if self._value_init_value.__class__ is dict: for k, v in iteritems(self._value_init_value): self[k] = v def add(self): """Add a variable to this list.""" next_idx = len(self._index) + 1 self._index.add(next_idx) return self[next_idx] register_component(Var, "Decision variables.") register_component(VarList, "List of decision variables.")
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.")
""" if not self._constructed: raise ValueError("Setting the value of arc '%s' before " "the Arc has been constructed (there " "is currently no object to set)." % self.name) if len(self._data) == 0: self._data[None] = self try: super(SimpleArc, self).set_value(vals) except: # don't allow model walker to find poorly constructed arcs del self._data[None] raise def pprint(self, ostream=None, verbose=False, prefix=""): Arc.pprint(self, ostream=ostream, verbose=verbose, prefix=prefix) class IndexedArc(Arc): def __init__(self, *args, **kwds): self._expanded_block = None super(IndexedArc, self).__init__(*args, **kwds) @property def expanded_block(self): # indexed block that contains all the blocks for this arc return self._expanded_block register_component(Arc, "Component used for connecting two Ports.")
def set_value(self, value, index=_NoArgument): if index is _NoArgument: index = None if self._constructed and not self._mutable: _raise_modifying_immutable_error(self, index) if not self._data: self._data[index] = self super(SimpleParam, self).set_value(value, index) def is_constant(self): """Determine if this SimpleParam is constant (and can be eliminated) Returns False if either unconstructed or mutable, as it must be kept in expressions (as it either doesn't have a value yet or the value can change later. """ return self._constructed and not self._mutable class IndexedParam(Param): def __call__(self, exception=True): """Compute the value of the parameter""" if exception: raise TypeError( 'Cannot compute the value of an indexed Param (%s)' % (self.name, )) register_component(Param, "Parameter data that is used to define a model instance.")
""" 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() register_component( BuildCheck, "A component that performs tests during model construction. The action rule is applied to every index value." )
else: return port1.vars[name] == port2.vars[name] con = Constraint(index_set, rule=rule) eblock.add_component(cname, con) @staticmethod def _create_evar(member, name, eblock, index_set): # Name is same, conflicts are prevented by a check in Port.add. # The new var will mirror the original var and have same index set. # We only need one evar per arc, so check if it already exists # before making a new one. evar = eblock.component(name) if evar is None: evar = replicate_var(member, name, eblock, index_set) return evar class SimplePort(Port, _PortData): def __init__(self, *args, **kwd): _PortData.__init__(self, component=self) Port.__init__(self, *args, **kwd) class IndexedPort(Port): pass register_component( Port, "A bundle of variables that can be connected to other ports.")
_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() register_component(Complementarity, "Complementarity conditions.") register_component(ComplementarityList, "A list of complementarity conditions.")
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() register_component(ContinuousSet, "A bounded continuous numerical range optionally containing" " discrete points of interest.")
val) if expr is None: raise ValueError( "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.""" next_idx = len(self._index) + 1 self._index.add(next_idx) return self.__setitem__(next_idx, expr) register_component(Constraint, "General constraint expressions.") register_component(ConstraintList, "A list of constraint expressions.")
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.')
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.")
_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.")
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 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() register_component( BuildAction, "A component that performs arbitrary actions during model construction. The action rule is applied to every index value." )
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")