コード例 #1
0
ファイル: test_util.py プロジェクト: adowling2/pyomo
    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])
コード例 #2
0
ファイル: test_util.py プロジェクト: adowling2/pyomo
    def test_method(self):
        class Init(object):
            def a_init(self, m):
                return 0

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

            def x2_init(self, m):
                return 0

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

        init = Init()

        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)
コード例 #3
0
ファイル: test_util.py プロジェクト: Utkarsh-Detha/pyomo
    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)
コード例 #4
0
ファイル: test_util.py プロジェクト: matzech/pyomo
    def test_sequence(self):
        m = ConcreteModel()
        a = Initializer([0,5])
        self.assertIs(type(a), ItemInitializer)
        self.assertFalse(a.constant())
        self.assertFalse(a.verified)
        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.assertEqual(a(None, 1), [0,5])
コード例 #5
0
ファイル: test_util.py プロジェクト: matzech/pyomo
 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)
コード例 #6
0
ファイル: test_util.py プロジェクト: matzech/pyomo
 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)
コード例 #7
0
ファイル: test_util.py プロジェクト: adowling2/pyomo
 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)
コード例 #8
0
ファイル: test_util.py プロジェクト: adowling2/pyomo
 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)
コード例 #9
0
ファイル: test_util.py プロジェクト: Utkarsh-Detha/pyomo
    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.assertRaisesRegexp(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])
コード例 #10
0
ファイル: test_util.py プロジェクト: Utkarsh-Detha/pyomo
    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])
コード例 #11
0
ファイル: constraint.py プロジェクト: zypher22/pyomo
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),
            ])