def test_constant(self): m = ConcreteModel() a = Initializer(5) self.assertIs(type(a), ConstantInitializer) self.assertTrue(a.constant()) self.assertFalse(a.verified) self.assertFalse(a.contains_indices()) with self.assertRaisesRegex( RuntimeError, "Initializer ConstantInitializer does " "not contain embedded indices"): a.indices() self.assertEqual(a(None, 1), 5)
def test_dict(self): m = ConcreteModel() a = Initializer({1:5}) self.assertIs(type(a), ItemInitializer) self.assertFalse(a.constant()) self.assertFalse(a.verified) self.assertTrue(a.contains_indices()) self.assertEqual(list(a.indices()), [1]) self.assertEqual(a(None, 1), 5)
def test_sequence(self): m = ConcreteModel() a = Initializer([0,5]) self.assertIs(type(a), ItemInitializer) self.assertFalse(a.constant()) self.assertFalse(a.verified) self.assertTrue(a.contains_indices()) self.assertEqual(list(a.indices()), [0,1]) self.assertEqual(a(None, 1), 5) a = Initializer([0,5], treat_sequences_as_mappings=False) self.assertIs(type(a), ConstantInitializer) self.assertTrue(a.constant()) self.assertFalse(a.verified) self.assertFalse(a.contains_indices()) self.assertEqual(a(None, 1), [0,5])
class Constraint(ActiveIndexedComponent): """ This modeling component defines a constraint expression using a rule function. Constructor arguments: expr A Pyomo expression for this constraint rule A function that is used to construct constraint expressions doc A text string describing this component name A name for this component Public class attributes: doc A text string describing this component name A name for this component active A boolean that is true if this component will be used to construct a model instance rule The rule used to initialize the constraint(s) Private class attributes: _constructed A boolean that is true if this component has been constructed _data A dictionary from the index set to component data objects _index The set of valid indices _implicit_subsets A tuple of set objects that represents the index set _model A weakref to the model that owns this component _parent A weakref to the parent block that owns this component _type The class type for the derived subclass """ _ComponentDataClass = _GeneralConstraintData class Infeasible(object): pass Feasible = ActiveIndexedComponent.Skip NoConstraint = ActiveIndexedComponent.Skip Violated = Infeasible Satisfied = Feasible def __new__(cls, *args, **kwds): if cls != Constraint: return super(Constraint, cls).__new__(cls) if not args or (args[0] is UnindexedComponent_set and len(args) == 1): return super(Constraint, cls).__new__(AbstractSimpleConstraint) else: return super(Constraint, cls).__new__(IndexedConstraint) def __init__(self, *args, **kwargs): _init = tuple(_arg for _arg in (kwargs.pop('rule', None), kwargs.pop('expr', None)) if _arg is not None) if len(_init) == 1: _init = _init[0] elif not _init: _init = None else: raise ValueError("Duplicate initialization: Constraint() only " "accepts one of 'rule=' and 'expr='") kwargs.setdefault('ctype', Constraint) ActiveIndexedComponent.__init__(self, *args, **kwargs) self.rule = Initializer(_init, treat_sequences_as_mappings=False) def construct(self, data=None): """ Construct the expression(s) for this constraint. """ if self._constructed: return self._constructed = True timer = ConstructionTimer(self) if __debug__ and logger.isEnabledFor(logging.DEBUG): 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() def _getitem_when_not_present(self, idx): if self.rule is None: raise KeyError(idx) con = self._setitem_when_not_present( idx, self.rule(self.parent_block(), idx)) if con is None: raise KeyError(idx) return con def _pprint(self): """ Return data that will be printed for this component. """ return ([ ("Size", len(self)), ("Index", self._index if self.is_indexed() else None), ("Active", self.active), ], iteritems(self), ("Lower", "Body", "Upper", "Active"), lambda k, v: [ "-Inf" if v.lower is None else v.lower, v.body, "+Inf" if v.upper is None else v.upper, v.active, ]) def display(self, prefix="", ostream=None): """ Print component state information This duplicates logic in Component.pprint() """ if not self.active: return if ostream is None: ostream = sys.stdout tab = " " ostream.write(prefix + self.local_name + " : ") ostream.write("Size=" + str(len(self))) ostream.write("\n") tabular_writer( ostream, prefix + tab, ((k, v) for k, v in iteritems(self._data) if v.active), ("Lower", "Body", "Upper"), lambda k, v: [ value(v.lower), v.body(), value(v.upper), ])