Exemple #1
0
 def test_dict(self):
     m = ConcreteModel()
     a = Initializer({1:5})
     self.assertIs(type(a), ItemInitializer)
     self.assertFalse(a.constant())
     self.assertFalse(a.verified)
     self.assertEqual(a(None, 1), 5)
Exemple #2
0
 def test_constant(self):
     m = ConcreteModel()
     a = Initializer(5)
     self.assertIs(type(a), ConstantInitializer)
     self.assertTrue(a.constant())
     self.assertFalse(a.verified)
     self.assertEqual(a(None, 1), 5)
Exemple #3
0
 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)
Exemple #4
0
 def __init__(self, *args, **kwds):
     # This will get called regardless of what class we are instantiating
     self._init_model = Initializer(kwds.pop('model', None))
     self._init_time = Initializer(kwds.pop('time', None),
                                   treat_sequences_as_mappings=False)
     self._init_inputs = Initializer(kwds.pop('inputs', None),
                                     treat_sequences_as_mappings=False)
     self._init_measurements = Initializer(
         kwds.pop('measurements', None), treat_sequences_as_mappings=False)
     Block.__init__(self, *args, **kwds)
Exemple #5
0
    def test_pickle(self):
        m = ConcreteModel()
        a = Initializer(5)
        a.verified = True
        b = pickle.loads(pickle.dumps(a))
        self.assertIsNot(a, b)
        self.assertEqual(a.val, b.val)
        self.assertEqual(a.verified, b.verified)

        a = Initializer({1:5})
        b = pickle.loads(pickle.dumps(a))
        self.assertIsNot(a, b)
        self.assertEqual(a._dict, b._dict)
        self.assertIsNot(a._dict, b._dict)
        self.assertEqual(a.verified, b.verified)

        a = Initializer(_init_scalar)
        b = pickle.loads(pickle.dumps(a))
        self.assertIsNot(a, b)
        self.assertIs(a._fcn, b._fcn)
        self.assertEqual(a.verified, b.verified)
        self.assertEqual(a(None, None), 1)
        self.assertEqual(b(None, None), 1)

        m.x = Var([1,2,3])
        a = Initializer(_init_indexed)
        b = pickle.loads(pickle.dumps(a))
        self.assertIsNot(a, b)
        self.assertIs(a._fcn, b._fcn)
        self.assertEqual(a.verified, b.verified)
        self.assertEqual(a(None, 1), 2)
        self.assertEqual(b(None, 2), 3)
Exemple #6
0
    def __init__(self, *args, **kwargs):
        kwargs.setdefault('ctype', Complementarity)
        kwargs.setdefault('dense', False)
        _init = tuple(_arg for _arg in (kwargs.pop('initialize', None),
                                        kwargs.pop('rule', None),
                                        kwargs.pop('expr', None))
                      if _arg is not None)
        if len(_init) > 1:
            raise ValueError(
                "Duplicate initialization: Complementarity() only accepts "
                "one of 'initialize=', 'rule=', and 'expr='")
        elif _init:
            _init = _init[0]
        else:
            _init = None

        self._init_rule = Initializer(_init,
                                      treat_sequences_as_mappings=False,
                                      allow_generators=True)

        if self._init_rule is not None:
            kwargs['rule'] = Complementarity._complementarity_rule
        Block.__init__(self, *args, **kwargs)

        # HACK to make the "counted call" syntax work.  We wait until
        # after the base class is set up so that is_indexed() is
        # reliable.
        if self._init_rule is not None \
           and self._init_rule.__class__ is IndexedCallInitializer:
            self._init_rule = CountedCallInitializer(self, self._init_rule)
Exemple #7
0
    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)
Exemple #8
0
    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])
Exemple #9
0
    def test_generators(self):
        m = ConcreteModel()
        with self.assertRaisesRegexp(ValueError, "Generators are not allowed"):
            a = Initializer(iter([0, 3]))

        a = Initializer(iter([0, 3]), allow_generators=True)
        self.assertIs(type(a), ConstantInitializer)
        self.assertTrue(a.constant())
        self.assertFalse(a.verified)
        self.assertEqual(list(a(None, 1)), [0, 3])

        def x_init():
            yield 0
            yield 3

        with self.assertRaisesRegexp(ValueError, "Generators are not allowed"):
            a = Initializer(x_init())

        a = Initializer(x_init(), allow_generators=True)
        self.assertIs(type(a), ConstantInitializer)
        self.assertTrue(a.constant())
        self.assertFalse(a.verified)
        self.assertEqual(list(a(None, 1)), [0, 3])
Exemple #10
0
 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)
Exemple #11
0
    def __init__(self, **kwargs):
        """Constructor"""
        if 'expr' in kwargs:
            raise ValueError(
                "ConstraintList does not accept the 'expr' keyword")
        _rule = kwargs.pop('rule', None)

        args = (Set(dimen=1), )
        super(ConstraintList, self).__init__(*args, **kwargs)

        self.rule = Initializer(_rule,
                                treat_sequences_as_mappings=False,
                                allow_generators=True)
        # HACK to make the "counted call" syntax work.  We wait until
        # after the base class is set up so that is_indexed() is
        # reliable.
        if self.rule is not None and type(self.rule) is IndexedCallInitializer:
            self.rule = CountedCallInitializer(self, self.rule)
Exemple #12
0
 def __init__(self, *args, **kwds):
     kwds.setdefault('ctype', ExternalGreyBoxBlock)
     self._init_model = Initializer(kwds.pop('external_model', None))
     Block.__init__(self, *args, **kwds)
Exemple #13
0
    def test_generator_method(self):
        class Init(object):
            def a_init(self, m):
                yield 0
                yield 3

            def x_init(self, m, i):
                yield i
                yield i+1

            def y_init(self, m, i, j):
                yield j
                yield i+1
        init = Init()

        m = ConcreteModel()
        with self.assertRaisesRegex(
                ValueError, "Generator functions are not allowed"):
            a = Initializer(init.a_init)

        a = Initializer(init.a_init, allow_generators=True)
        self.assertIs(type(a), ScalarCallInitializer)
        self.assertFalse(a.constant())
        self.assertFalse(a.verified)
        self.assertEqual(list(a(None, 1)), [0,3])

        m.x = Var([1,2,3])
        a = Initializer(init.x_init, allow_generators=True)
        self.assertIs(type(a), IndexedCallInitializer)
        self.assertFalse(a.constant())
        self.assertFalse(a.verified)
        self.assertEqual(list(a(None, 1)), [1,2])

        m.y = Var([1,2,3], [4,5,6])
        a = Initializer(init.y_init, allow_generators=True)
        self.assertIs(type(a), IndexedCallInitializer)
        self.assertFalse(a.constant())
        self.assertFalse(a.verified)
        self.assertEqual(list(a(None, (1, 4))), [4,2])
Exemple #14
0
    def test_generator_fcn(self):
        m = ConcreteModel()
        def a_init(m):
            yield 0
            yield 3
        with self.assertRaisesRegex(
                ValueError, "Generator functions are not allowed"):
            a = Initializer(a_init)

        a = Initializer(a_init, allow_generators=True)
        self.assertIs(type(a), ScalarCallInitializer)
        self.assertFalse(a.constant())
        self.assertFalse(a.verified)
        self.assertEqual(list(a(None, 1)), [0,3])

        m.x = Var([1,2,3])
        def x_init(m, i):
            yield i
            yield i+1
        a = Initializer(x_init, allow_generators=True)
        self.assertIs(type(a), IndexedCallInitializer)
        self.assertFalse(a.constant())
        self.assertFalse(a.verified)
        self.assertEqual(list(a(None, 1)), [1,2])

        m.y = Var([1,2,3], [4,5,6])
        def y_init(m, i, j):
            yield j
            yield i+1
        a = Initializer(y_init, allow_generators=True)
        self.assertIs(type(a), IndexedCallInitializer)
        self.assertFalse(a.constant())
        self.assertFalse(a.verified)
        self.assertEqual(list(a(None, (1, 4))), [4,2])
Exemple #15
0
    def test_staticmethod(self):
        class Init(object):
            @staticmethod
            def a_init(m):
                return 0

            @staticmethod
            def x_init(m, i):
                return i+1

            @staticmethod
            def x2_init(m):
                return 0

            @staticmethod
            def y_init(m, i, j):
                return j*(i+1)

        m = ConcreteModel()
        a = Initializer(Init.a_init)
        self.assertIs(type(a), ScalarCallInitializer)
        self.assertFalse(a.constant())
        self.assertFalse(a.verified)
        self.assertFalse(a.contains_indices())
        self.assertEqual(a(None, 1), 0)

        m.x = Var([1,2,3])
        a = Initializer(Init.x_init)
        self.assertIs(type(a), IndexedCallInitializer)
        self.assertFalse(a.constant())
        self.assertFalse(a.verified)
        self.assertFalse(a.contains_indices())
        self.assertEqual(a(None, 1), 2)

        a = Initializer(Init.x2_init)
        self.assertIs(type(a), ScalarCallInitializer)
        self.assertFalse(a.constant())
        self.assertFalse(a.verified)
        self.assertFalse(a.contains_indices())
        self.assertEqual(a(None, 1), 0)

        m.y = Var([1,2,3], [4,5,6])
        a = Initializer(Init.y_init)
        self.assertIs(type(a), IndexedCallInitializer)
        self.assertFalse(a.constant())
        self.assertFalse(a.verified)
        self.assertFalse(a.contains_indices())
        self.assertEqual(a(None, (1, 4)), 8)

        b = CountedCallInitializer(m.x, a)
        self.assertIs(type(b), CountedCallInitializer)
        self.assertFalse(b.constant())
        self.assertFalse(b.verified)
        self.assertFalse(a.contains_indices())
        self.assertFalse(b._scalar)
        self.assertIs(a._fcn, b._fcn)
        c = b(None, 1)
        self.assertIs(type(c), CountedCallGenerator)
        self.assertEqual(next(c), 2)
        self.assertEqual(next(c), 3)
        self.assertEqual(next(c), 4)
Exemple #16
0
    def test_function(self):
        m = ConcreteModel()
        def a_init(m):
            return 0
        a = Initializer(a_init)
        self.assertIs(type(a), ScalarCallInitializer)
        self.assertFalse(a.constant())
        self.assertFalse(a.verified)
        self.assertFalse(a.contains_indices())
        self.assertEqual(a(None, 1), 0)

        m.x = Var([1,2,3])
        def x_init(m, i):
            return i+1
        a = Initializer(x_init)
        self.assertIs(type(a), IndexedCallInitializer)
        self.assertFalse(a.constant())
        self.assertFalse(a.verified)
        self.assertFalse(a.contains_indices())
        self.assertEqual(a(None, 1), 2)

        def x2_init(m):
            return 0
        a = Initializer(x2_init)
        self.assertIs(type(a), ScalarCallInitializer)
        self.assertFalse(a.constant())
        self.assertFalse(a.verified)
        self.assertFalse(a.contains_indices())
        self.assertEqual(a(None, 1), 0)

        m.y = Var([1,2,3], [4,5,6])
        def y_init(m, i, j):
            return j*(i+1)
        a = Initializer(y_init)
        self.assertIs(type(a), IndexedCallInitializer)
        self.assertFalse(a.constant())
        self.assertFalse(a.verified)
        self.assertFalse(a.contains_indices())
        self.assertEqual(a(None, (1, 4)), 8)

        b = CountedCallInitializer(m.x, a)
        self.assertIs(type(b), CountedCallInitializer)
        self.assertFalse(b.constant())
        self.assertFalse(b.verified)
        self.assertFalse(a.contains_indices())
        self.assertFalse(b._scalar)
        self.assertIs(a._fcn, b._fcn)
        c = b(None, 1)
        self.assertIs(type(c), CountedCallGenerator)
        self.assertEqual(next(c), 2)
        self.assertEqual(next(c), 3)
        self.assertEqual(next(c), 4)
Exemple #17
0
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),
            ])