Ejemplo n.º 1
0
    def test_generate_finite_elements(self):
        m = ConcreteModel()
        m.t = ContinuousSet(bounds=(0, 10))
        m.t2 = ContinuousSet(bounds=(0, 10))
        m.t3 = ContinuousSet(bounds=(0, 1))

        oldt = sorted(m.t)
        generate_finite_elements(m.t, 1)
        self.assertTrue(oldt == sorted(m.t))
        self.assertFalse(m.t.get_changed())
        generate_finite_elements(m.t, 2)
        self.assertFalse(oldt == sorted(m.t))
        self.assertTrue(m.t.get_changed())
        self.assertTrue([0, 5.0, 10] == sorted(m.t))
        generate_finite_elements(m.t, 3)
        self.assertTrue([0, 2.5, 5.0, 10] == sorted(m.t))
        generate_finite_elements(m.t, 5)
        self.assertTrue([0, 1.25, 2.5, 5.0, 7.5, 10] == sorted(m.t))

        generate_finite_elements(m.t2, 10)
        self.assertTrue(len(m.t2) == 11)
        self.assertTrue([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] == sorted(m.t2))

        generate_finite_elements(m.t3, 7)
        self.assertTrue(len(m.t3) == 8)
        t = sorted(m.t3)
        print(t[1])
        self.assertTrue(t[1] == 0.142857)
Ejemplo n.º 2
0
    def test_generate_collocation_points(self):
        m = ConcreteModel()
        m.t = ContinuousSet(initialize=[0, 1])
        m.t2 = ContinuousSet(initialize=[0, 2, 4, 6])

        tau1 = [1]
        oldt = sorted(m.t)
        generate_colloc_points(m.t, tau1)
        self.assertTrue(oldt == sorted(m.t))
        self.assertFalse(m.t.get_changed())

        tau1 = [0.5]
        oldt = sorted(m.t)
        generate_colloc_points(m.t, tau1)
        self.assertFalse(oldt == sorted(m.t))
        self.assertTrue(m.t.get_changed())
        self.assertTrue([0, 0.5, 1] == sorted(m.t))

        tau2 = [0.2, 0.3, 0.7, 0.8, 1]
        generate_colloc_points(m.t, tau2)
        self.assertTrue(len(m.t) == 11)
        self.assertTrue(
            [0, 0.1, 0.15, 0.35, 0.4, 0.5, 0.6, 0.65, 0.85, 0.9, 1] == sorted(
                m.t))

        generate_colloc_points(m.t2, tau2)
        self.assertTrue(len(m.t2) == 16)
        self.assertTrue(m.t2.get_changed())
        t = sorted(m.t2)
        self.assertTrue(t[1] == 0.4)
        self.assertTrue(t[13] == 5.4)
Ejemplo n.º 3
0
    def test_bad_kwds(self):
        model = ConcreteModel()
        try:
            model.t = ContinuousSet(bounds=(0, 1), filter=True)
            self.fail("Expected TypeError")
        except TypeError:
            pass

        # try:
        #     model.t = ContinuousSet(bounds=(0,1),within=NonNegativeReals)
        #     self.fail("Expected TypeError")
        # except TypeError:
        #     pass

        try:
            model.t = ContinuousSet(bounds=(0, 1), dimen=2)
            self.fail("Expected TypeError")
        except TypeError:
            pass

        try:
            model.t = ContinuousSet(bounds=(0, 1), virtual=True)
            self.fail("Expected TypeError")
        except TypeError:
            pass

        try:
            model.t = ContinuousSet(bounds=(0, 1), validate=True)
            self.fail("Expected TypeError")
        except TypeError:
            pass
Ejemplo n.º 4
0
    def test_get_index_information(self):
        m = ConcreteModel()
        m.t = ContinuousSet(bounds=(0, 10))
        m.x = ContinuousSet(bounds=(0, 10))
        m.s = Set(initialize=['a', 'b', 'c'])
        m.v = Var(m.t, m.x, m.s, initialize=1)
        m.v2 = Var(m.t, m.s, initialize=1)

        disc = TransformationFactory('dae.collocation')
        disc.apply_to(m, wrt=m.t, nfe=5, ncp=2, scheme='LAGRANGE-RADAU')
        disc.apply_to(m, wrt=m.x, nfe=5, ncp=2, scheme='LAGRANGE-RADAU')

        info = get_index_information(m.v, m.t)
        nts = info['non_ds']
        index_getter = info['index function']

        self.assertEqual(len(nts), 33)
        self.assertTrue(m.x in nts.set_tuple)
        self.assertTrue(m.s in nts.set_tuple)
        self.assertEqual(index_getter((8.0, 'a'), 1, 0), (2.0, 8.0, 'a'))

        info = get_index_information(m.v2, m.t)
        nts = info['non_ds']
        index_getter = info['index function']

        self.assertEqual(len(nts), 3)
        self.assertTrue(m.s is nts)
        self.assertEqual(index_getter('a', 1, 0), (2.0, 'a'))
Ejemplo n.º 5
0
    def test_reclassification(self):
        m = ConcreteModel()
        m.t = ContinuousSet(bounds=(0, 1))
        m.x = ContinuousSet(bounds=(5, 10))
        m.s = Set(initialize=[1, 2, 3])
        m.v = Var(m.t)
        m.v2 = Var(m.s, m.t)
        m.v3 = Var(m.x, m.t)

        m.dv = DerivativeVar(m.v)
        m.dv2 = DerivativeVar(m.v2, wrt=(m.t, m.t))
        m.dv3 = DerivativeVar(m.v3, wrt=m.x)

        TransformationFactory('dae.finite_difference').apply_to(m, wrt=m.t)

        self.assertTrue(m.dv.ctype is Var)
        self.assertTrue(m.dv2.ctype is Var)
        self.assertTrue(m.dv.is_fully_discretized())
        self.assertTrue(m.dv2.is_fully_discretized())
        self.assertTrue(m.dv3.ctype is DerivativeVar)
        self.assertFalse(m.dv3.is_fully_discretized())

        TransformationFactory('dae.collocation').apply_to(m, wrt=m.x)
        self.assertTrue(m.dv3.ctype is Var)
        self.assertTrue(m.dv3.is_fully_discretized())
Ejemplo n.º 6
0
    def test_update_contset_indexed_component_expressions_multiple(self):
        m = ConcreteModel()
        m.t = ContinuousSet(bounds=(0, 10))
        m.t2 = ContinuousSet(initialize=[1, 2, 3])
        m.s1 = Set(initialize=[1, 2, 3])
        m.s2 = Set(initialize=[(1, 1), (2, 2)])

        def _init(m, i, j):
            return j + i

        m.p1 = Param(m.s1, m.t, default=_init)
        m.v1 = Var(m.s1, m.t, initialize=5)
        m.v2 = Var(m.s2, m.t, initialize=2)
        m.v3 = Var(m.t2, m.s2, initialize=1)

        def _con1(m, si, ti):
            return m.v1[si, ti] * m.p1[si, ti]

        m.con1 = Expression(m.s1, m.t, rule=_con1)

        def _con2(m, i, j, ti):
            return m.v2[i, j, ti] + m.p1[1, ti]

        m.con2 = Expression(m.s2, m.t, rule=_con2)

        def _con3(m, i, ti, ti2, j, k):
            return m.v1[i, ti] - m.v3[ti2, j, k] * m.p1[i, ti]

        m.con3 = Expression(m.s1, m.t, m.t2, m.s2, rule=_con3)

        expansion_map = ComponentMap()

        generate_finite_elements(m.t, 5)
        update_contset_indexed_component(m.p1, expansion_map)
        update_contset_indexed_component(m.v1, expansion_map)
        update_contset_indexed_component(m.v2, expansion_map)
        update_contset_indexed_component(m.v3, expansion_map)
        update_contset_indexed_component(m.con1, expansion_map)
        update_contset_indexed_component(m.con2, expansion_map)
        update_contset_indexed_component(m.con3, expansion_map)

        self.assertTrue(len(m.con1) == 18)
        self.assertTrue(len(m.con2) == 12)
        self.assertTrue(len(m.con3) == 108)

        self.assertEqual(m.con1[1, 4](), 25)
        self.assertEqual(m.con1[2, 6](), 40)
        self.assertEqual(m.con1[3, 8](), 55)

        self.assertEqual(m.con2[1, 1, 2](), 5)
        self.assertEqual(m.con2[2, 2, 4](), 7)
        self.assertEqual(m.con2[1, 1, 8](), 11)

        self.assertEqual(m.con3[1, 2, 1, 1, 1](), 2)
        self.assertEqual(m.con3[1, 4, 1, 2, 2](), 0)
        self.assertEqual(m.con3[2, 6, 3, 1, 1](), -3)
        self.assertEqual(m.con3[3, 8, 2, 2, 2](), -6)
Ejemplo n.º 7
0
    def test_reclassification_collocation(self):
        m = ConcreteModel()
        m.t = ContinuousSet(bounds=(0, 1))
        m.x = ContinuousSet(bounds=(5, 10))
        m.s = Set(initialize=[1, 2, 3])
        m.v = Var(m.t)
        m.v2 = Var(m.s, m.t)
        m.v3 = Var(m.t, m.x)

        def _int1(m, t):
            return m.v[t]

        m.int1 = Integral(m.t, rule=_int1)

        def _int2(m, s, t):
            return m.v2[s, t]

        m.int2 = Integral(m.s, m.t, wrt=m.t, rule=_int2)

        def _int3(m, t, x):
            return m.v3[t, x]

        m.int3 = Integral(m.t, m.x, wrt=m.t, rule=_int3)

        def _int4(m, x):
            return m.int3[x]

        m.int4 = Integral(m.x, wrt=m.x, rule=_int4)

        self.assertFalse(m.int1.is_fully_discretized())
        self.assertFalse(m.int2.is_fully_discretized())
        self.assertFalse(m.int3.is_fully_discretized())
        self.assertFalse(m.int4.is_fully_discretized())

        TransformationFactory('dae.collocation').apply_to(m, wrt=m.t)

        self.assertTrue(m.int1.is_fully_discretized())
        self.assertTrue(m.int2.is_fully_discretized())
        self.assertFalse(m.int3.is_fully_discretized())
        self.assertFalse(m.int4.is_fully_discretized())

        self.assertTrue(m.int1.ctype is Integral)
        self.assertTrue(m.int2.ctype is Integral)
        self.assertTrue(m.int3.ctype is Integral)
        self.assertTrue(m.int4.ctype is Integral)

        TransformationFactory('dae.collocation').apply_to(m, wrt=m.x)

        self.assertTrue(m.int3.is_fully_discretized())
        self.assertTrue(m.int4.is_fully_discretized())

        self.assertTrue(m.int1.ctype is Expression)
        self.assertTrue(m.int2.ctype is Expression)
        self.assertTrue(m.int3.ctype is Expression)
        self.assertTrue(m.int4.ctype is Expression)
Ejemplo n.º 8
0
def make_model():
    m = ConcreteModel()
    m.time = ContinuousSet(bounds=(0, 10))
    m.space = ContinuousSet(bounds=(0, 5))
    m.set1 = Set(initialize=['a', 'b', 'c'])
    m.set2 = Set(initialize=['d', 'e', 'f'])
    m.fs = Block()

    m.fs.v0 = Var(m.space, initialize=1)

    @m.fs.Block()
    def b1(b):
        b.v = Var(m.time, m.space, initialize=1)
        b.dv = DerivativeVar(b.v, wrt=m.time, initialize=0)

        b.con = Constraint(m.time,
                           m.space,
                           rule=lambda b, t, x: b.dv[t, x] == 7 - b.v[t, x])
        # Inconsistent

        @b.Block(m.time)
        def b2(b, t):
            b.v = Var(initialize=2)

    @m.fs.Block(m.time, m.space)
    def b2(b, t, x):
        b.v = Var(m.set1, initialize=2)

        @b.Block(m.set1)
        def b3(b, c):
            b.v = Var(m.set2, initialize=3)

            @b.Constraint(m.set2)
            def con(b, s):
                return (5 * b.v[s] == m.fs.b2[m.time.first(),
                                              m.space.first()].v[c])
                # inconsistent

    @m.fs.Constraint(m.time)
    def con1(fs, t):
        return fs.b1.v[t, m.space.last()] == 5

    # Will be inconsistent

    @m.fs.Constraint(m.space)
    def con2(fs, x):
        return fs.b1.v[m.time.first(), x] == fs.v0[x]

    # will be consistent

    disc = TransformationFactory('dae.collocation')
    disc.apply_to(m, wrt=m.time, nfe=5, ncp=2, scheme='LAGRANGE-RADAU')
    disc.apply_to(m, wrt=m.space, nfe=5, ncp=2, scheme='LAGRANGE-RADAU')

    return m
Ejemplo n.º 9
0
    def test_disc_second_order_1cp(self):
        m = ConcreteModel()
        m.t = ContinuousSet(bounds=(0,1))
        m.t2 = ContinuousSet(bounds=(0,10))
        m.v = Var(m.t, m.t2)
        m.dv = DerivativeVar(m.v, wrt=(m.t, m.t2))
        TransformationFactory('dae.collocation').apply_to(m, nfe=2, ncp=1)

        self.assertTrue(hasattr(m, 'dv_disc_eq'))
        self.assertTrue(len(m.dv_disc_eq) == 4)
        self.assertTrue(len(m.v) == 9)                        
Ejemplo n.º 10
0
    def test_invalid(self):
        m = ConcreteModel()
        m.t = ContinuousSet(bounds=(0, 1))
        m.x = ContinuousSet(bounds=(5, 10))
        m.s = Set(initialize=[1, 2, 3])
        m.v = Var(m.t)
        m.v2 = Var(m.s, m.t)
        m.v3 = Var(m.x, m.t)
        m.y = Var()

        # Not passing a Var as the first positional argument
        with self.assertRaises(DAE_Error):
            m.ds = DerivativeVar(m.s)

        # Specifying both option aliases
        with self.assertRaises(TypeError):
            m.dv = DerivativeVar(m.v, wrt=m.t, withrespectto=m.t)

        # Passing in Var not indexed by a ContinuousSet
        with self.assertRaises(DAE_Error):
            m.dy = DerivativeVar(m.y)

        # Not specifying 'wrt' when Var indexed by multiple ContinuousSets
        with self.assertRaises(DAE_Error):
            m.dv3 = DerivativeVar(m.v3)

        # 'wrt' is not a ContinuousSet
        with self.assertRaises(DAE_Error):
            m.dv2 = DerivativeVar(m.v2, wrt=m.s)

        with self.assertRaises(DAE_Error):
            m.dv2 = DerivativeVar(m.v2, wrt=(m.t, m.s))

        # Specified ContinuousSet does not index the Var
        with self.assertRaises(DAE_Error):
            m.dv = DerivativeVar(m.v, wrt=m.x)

        with self.assertRaises(DAE_Error):
            m.dv2 = DerivativeVar(m.v2, wrt=[m.t, m.x])

        # Declaring the same derivative twice
        m.dvdt = DerivativeVar(m.v)
        with self.assertRaises(DAE_Error):
            m.dvdt2 = DerivativeVar(m.v)

        m.dv2dt = DerivativeVar(m.v2, wrt=m.t)
        with self.assertRaises(DAE_Error):
            m.dv2dt2 = DerivativeVar(m.v2, wrt=m.t)

        m.dv3 = DerivativeVar(m.v3, wrt=(m.x, m.x))
        with self.assertRaises(DAE_Error):
            m.dv4 = DerivativeVar(m.v3, wrt=(m.x, m.x))
Ejemplo n.º 11
0
    def test_bad_kwds(self):
        model = ConcreteModel()
        with self.assertRaises(TypeError):
            model.t = ContinuousSet(bounds=(0, 1), filter=True)

        with self.assertRaises(TypeError):
            model.t = ContinuousSet(bounds=(0, 1), dimen=2)

        with self.assertRaises(TypeError):
            model.t = ContinuousSet(bounds=(0, 1), virtual=True)

        with self.assertRaises(TypeError):
            model.t = ContinuousSet(bounds=(0, 1), validate=True)
Ejemplo n.º 12
0
    def test_update_contset_indexed_component_vars_multiple(self):
        m = ConcreteModel()
        m.t = ContinuousSet(bounds=(0, 10))
        m.t2 = ContinuousSet(initialize=[1, 2, 3])
        m.s = Set(initialize=[1, 2, 3])
        m.s2 = Set(initialize=[(1, 1), (2, 2)])
        m.v1 = Var(m.s, m.t, initialize=3)
        m.v2 = Var(m.s,
                   m.t,
                   m.t2,
                   bounds=(4, 10),
                   initialize={
                       (1, 0, 1): 22,
                       (2, 10, 2): 22
                   })

        def _init(m, i, j, k):
            return i

        m.v3 = Var(m.t, m.s2, bounds=(-5, 5), initialize=_init)
        m.v4 = Var(m.s, m.t2, initialize=7, dense=True)
        m.v5 = Var(m.s2)

        expansion_map = ComponentMap()

        generate_finite_elements(m.t, 5)
        update_contset_indexed_component(m.v1, expansion_map)
        update_contset_indexed_component(m.v2, expansion_map)
        update_contset_indexed_component(m.v3, expansion_map)
        update_contset_indexed_component(m.v4, expansion_map)
        update_contset_indexed_component(m.v5, expansion_map)

        self.assertTrue(len(m.v1) == 18)
        self.assertTrue(len(m.v2) == 54)
        self.assertTrue(len(m.v3) == 12)
        self.assertTrue(len(m.v4) == 9)

        self.assertTrue(value(m.v1[1, 4]) == 3)
        self.assertTrue(m.v1[2, 2].ub is None)
        self.assertTrue(m.v1[3, 8].lb is None)

        self.assertTrue(value(m.v2[1, 0, 1]) == 22)
        self.assertTrue(m.v2[1, 2, 1].value is None)
        self.assertTrue(m.v2[2, 4, 3].lb == 4)
        self.assertTrue(m.v2[3, 8, 1].ub == 10)

        self.assertTrue(value(m.v3[2, 2, 2]) == 2)
        self.assertTrue(m.v3[4, 1, 1].lb == -5)
        self.assertTrue(m.v3[8, 2, 2].ub == 5)
        self.assertTrue(value(m.v3[6, 1, 1]) == 6)
Ejemplo n.º 13
0
    def test_init(self):
        model = ConcreteModel()
        model.t = ContinuousSet(bounds=(0, 1))

        model = ConcreteModel()
        model.t = ContinuousSet(initialize=[1, 2, 3])

        model = ConcreteModel()
        model.t = ContinuousSet(bounds=(0, 5), initialize=[1, 3, 5])

        # Expected ValueError because a ContinuousSet component
        # must contain at least two values upon construction
        with self.assertRaises(ValueError):
            model.t = ContinuousSet()
Ejemplo n.º 14
0
    def test_update_block_derived2(self):
        class Foo(Block):
            pass

        m = ConcreteModel()
        m.t = ContinuousSet(bounds=(0, 10))
        m.s = Set(initialize=[1, 2, 3])

        def _block_rule(b, t, s):
            m = b.model()

            def _init(m, j):
                return j * 2

            b.p1 = Param(m.t, default=_init)
            b.v1 = Var(m.t, initialize=5)

        m.foo = Foo(m.t, m.s, rule=_block_rule)

        generate_finite_elements(m.t, 5)
        expand_components(m)

        self.assertEqual(len(m.foo), 18)
        self.assertEqual(len(m.foo[0, 1].p1), 6)
        self.assertEqual(len(m.foo[2, 2].v1), 6)
        self.assertEqual(m.foo[0, 3].p1[6], 12)
Ejemplo n.º 15
0
    def test_update_block_derived_override_construct_nofcn2(self):
        class Foo(Block):
            def construct(self, data=None):
                Block.construct(self, data)

        m = ConcreteModel()
        m.t = ContinuousSet(bounds=(0, 10))
        m.s = Set(initialize=[1, 2, 3])

        def _block_rule(b, t, s):
            m = b.model()

            def _init(m, j):
                return j * 2

            b.p1 = Param(m.t, default=_init)
            b.v1 = Var(m.t, initialize=5)

        m.foo = Foo(m.t, m.s, rule=_block_rule)

        generate_finite_elements(m.t, 5)

        OUTPUT = StringIO()
        with LoggingIntercept(OUTPUT, 'pyomo.dae'):
            expand_components(m)
        self.assertIn('transformation to the Block-derived component',
                      OUTPUT.getvalue())
        self.assertEqual(len(m.foo), 18)
        self.assertEqual(len(m.foo[0, 1].p1), 6)
        self.assertEqual(len(m.foo[2, 2].v1), 6)
        self.assertEqual(m.foo[0, 3].p1[6], 12)
Ejemplo n.º 16
0
    def test_update_contset_indexed_component_piecewise_multiple(self):
        x = [0.0, 1.5, 3.0, 5.0]
        y = [1.1, -1.1, 2.0, 1.1]

        model = ConcreteModel()
        model.t = ContinuousSet(bounds=(0, 10))
        model.s = Set(initialize=['A', 'B', 'C'])

        model.x = Var(model.s, model.t, bounds=(min(x), max(x)))
        model.y = Var(model.s, model.t)

        model.fx = Piecewise(model.s,
                             model.t,
                             model.y,
                             model.x,
                             pw_pts=x,
                             pw_constr_type='EQ',
                             f_rule=y)

        self.assertEqual(len(model.fx), 6)

        expansion_map = ComponentMap()

        generate_finite_elements(model.t, 5)
        update_contset_indexed_component(model.fx, expansion_map)

        self.assertEqual(len(model.fx), 18)
        self.assertEqual(len(model.fx['A', 2].SOS2_constraint), 3)
Ejemplo n.º 17
0
    def test_instanciate(self):
        from lms2 import AbsLModel
        from lms2 import ScalablePowerSource

        import pandas as pd
        from pyomo.dae import ContinuousSet
        from pyomo.environ import TransformationFactory

        m = AbsLModel()
        m.time = ContinuousSet()
        m.u = ScalablePowerSource(curtailable=False)

        df = pd.Series({0: 0, 1: 1, 2: 2, 3: 1, 4: 0})
        data_u = {
            'time': {None: [0, 4]},
            'profile_index': {None: df.index},
            'profile_value': df.to_dict()}

        data = \
            {None:
                {
                    'time': {None: [0, 4]},
                    'u': data_u
                }
            }
        inst = m.create_instance(data)
        TransformationFactory('dae.finite_difference').apply_to(inst, nfe=4)

        self.assertFalse(hasattr(inst.u, 'p_curt'))
        self.assertTrue(hasattr(inst.u, 'p'))
        self.assertTrue(hasattr(inst.u, 'p_scaled'))
        self.assertTrue(hasattr(inst.u, 'scale_fact'))
Ejemplo n.º 18
0
    def test_bad_arg(self):
        m = ConcreteModel()
        m.t = ContinuousSet(bounds=(0, 1))

        m.a = Param(initialize=1, mutable=True)
        m.b = Param(initialize=2, mutable=True)
        m.c = Param(initialize=3, mutable=False)

        m.x = Var(m.t)

        list_one = [m.a, m.b]
        list_two = [m.a, m.b, m.c]
        list_three = [m.a, m.x]
        list_four = [m.a, m.c]

        # verify ValueError thrown when param and perturb list are different
        # lengths
        msg = ("Length of paramList argument does"
               " not equal length of perturbList")
        with self.assertRaisesRegex(ValueError, msg):
            Result = sensitivity_calculation('sipopt', m, list_one, list_two)

        # verify ValueError thrown when param list has an unmutable param
        msg = ("Parameters within paramList must be mutable")
        with self.assertRaisesRegex(ValueError, msg):
            Result = sensitivity_calculation('sipopt', m, list_four, list_one)

        # verify ValueError thrown when param list has an unfixed var.
        msg = ("Specified \"parameter\" variables must be fixed")
        with self.assertRaisesRegex(ValueError, msg) as context:
            Result = sensitivity_calculation('sipopt', m, list_three, list_one)
Ejemplo n.º 19
0
    def test_instanciate_prog(self):
        from lms2 import ProgrammableLoad, DebugSource
        from pyomo.environ import AbstractModel, TransformationFactory, Param, Var
        from pyomo.dae import ContinuousSet
        import pandas as pd

        m = AbstractModel()
        m.time = ContinuousSet(bounds=(0, 1))
        m.prog = ProgrammableLoad()

        UB = 1e6

        df = pd.Series({0: 0, 1: 1, 2: 2, 3: 1, 4: 0})

        data_prog = {
            'time': {None: [0, 10]},
            'w1': {None: 3},
            'w2': {None: 8},
            'window': {None: [2, 8]},
            'profile_index': {None: df.index},
            'profile_value': df.to_dict()}

        data = \
            {None:
                {
                    'time': {None: [0, 10]},
                    'prog': data_prog
                }
            }

        inst = m.create_instance(data)
        TransformationFactory('dae.finite_difference').apply_to(inst, nfe=10)

        inst.prog.compile()
Ejemplo n.º 20
0
    def test_disc_multi_index2(self):
        m = self.m.clone()
        m.t2 = ContinuousSet(bounds=(0, 5))
        m.v2 = Var(m.t, m.t2)
        m.dv2dt = DerivativeVar(m.v2, wrt=m.t)
        m.dv2dt2 = DerivativeVar(m.v2, wrt=m.t2)

        disc = TransformationFactory('dae.collocation')
        disc.apply_to(m, nfe=2, ncp=2)

        self.assertTrue(hasattr(m, 'dv2dt_disc_eq'))
        self.assertTrue(hasattr(m, 'dv2dt2_disc_eq'))
        self.assertTrue(len(m.dv2dt_disc_eq) == 20)
        self.assertTrue(len(m.dv2dt2_disc_eq) == 20)
        self.assertTrue(len(m.v2) == 25)

        expected_t_disc_points = [0, 1.666667, 5.0, 6.666667, 10]
        expected_t2_disc_points = [0, 0.833333, 2.5, 3.333333, 5]
        
        for idx, val in enumerate(list(m.t)):
            self.assertAlmostEqual(val, expected_t_disc_points[idx])

        for idx, val in enumerate(list(m.t2)):
            self.assertAlmostEqual(val, expected_t2_disc_points[idx])

        self.assertTrue(hasattr(m, '_pyomo_dae_reclassified_derivativevars'))
        self.assertTrue(m.dv1 in m._pyomo_dae_reclassified_derivativevars)
        self.assertTrue(m.dv2dt in m._pyomo_dae_reclassified_derivativevars)
        self.assertTrue(m.dv2dt2 in m._pyomo_dae_reclassified_derivativevars)
Ejemplo n.º 21
0
    def test_flat_model(self):
        m = ConcreteModel()
        m.T = ContinuousSet(bounds=(0, 1))
        m.x = Var()
        m.y = Var([1, 2])
        m.a = Var(m.T)
        m.b = Var(m.T, [1, 2])
        m.c = Var([3, 4], m.T)

        regular, time = flatten_dae_variables(m, m.T)
        regular_id = set(id(_) for _ in regular)
        self.assertEqual(len(regular), 3)
        self.assertIn(id(m.x), regular_id)
        self.assertIn(id(m.y[1]), regular_id)
        self.assertIn(id(m.y[2]), regular_id)
        # Output for debugging
        #for v in time:
        #    v.pprint()
        #    for _ in v.values():
        #        print"     -> ", _.name
        ref_data = {
            self._hashRef(Reference(m.a[:])),
            self._hashRef(Reference(m.b[:, 1])),
            self._hashRef(Reference(m.b[:, 2])),
            self._hashRef(Reference(m.c[3, :])),
            self._hashRef(Reference(m.c[4, :])),
        }
        self.assertEqual(len(time), len(ref_data))
        for ref in time:
            self.assertIn(self._hashRef(ref), ref_data)
Ejemplo n.º 22
0
    def test_abs(self):
        from lms2 import FlowSource
        from pyomo.environ import AbstractModel, TransformationFactory
        from pyomo.dae import ContinuousSet
        from pyomo.network import Port

        m = AbstractModel()
        m.time = ContinuousSet()
        m.u = FlowSource(flow_name='p')

        data_unit = dict(time={None: [0, 15]})

        data = \
            {None:
                {
                    'time': {None: [0, 15]},
                    'u': data_unit
                }
            }

        inst = m.create_instance(data)
        TransformationFactory('dae.finite_difference').apply_to(inst, nfe=1)

        self.assertTrue(hasattr(m.u, 'p'))
        self.assertTrue(hasattr(m.u, 'outlet'))
        self.assertIsInstance(m.u.outlet, Port)

        self.assertEqual(inst.u.time.data(), (0, 15))
        self.assertEqual(inst.time.data(), (0, 15))
Ejemplo n.º 23
0
    def test_discretized_params_single(self):
        m = ConcreteModel()
        m.t = ContinuousSet(bounds=(0, 10))
        m.s1 = Set(initialize=[1, 2, 3])
        m.s2 = Set(initialize=[(1, 1), (2, 2)])
        m.p1 = Param(m.t, initialize=1)
        m.p2 = Param(m.t, default=2)
        m.p3 = Param(m.t, initialize=1, default=2)

        def _rule1(m, i):
            return i**2

        def _rule2(m, i):
            return 2 * i

        m.p4 = Param(m.t, initialize={0: 5, 10: 5}, default=_rule1)
        m.p5 = Param(m.t, initialize=_rule1, default=_rule2)

        generate_finite_elements(m.t, 5)
        # Expected ValueError because no default value was specified
        with self.assertRaises(ValueError):
            for i in m.t:
                m.p1[i]

        for i in m.t:
            self.assertEqual(m.p2[i], 2)

            if i == 0 or i == 10:
                self.assertEqual(m.p3[i], 1)
                self.assertEqual(m.p4[i], 5)
                self.assertEqual(m.p5[i], i**2)
            else:
                self.assertEqual(m.p3[i], 2)
                self.assertEqual(m.p4[i], i**2)
                self.assertEqual(m.p5[i], 2 * i)
Ejemplo n.º 24
0
    def test_hierarchical_blocks(self):
        m = ConcreteModel()

        m.b = Block()
        m.b.t = ContinuousSet(bounds=(0, 10))

        m.b.c = Block()

        def _d_rule(d, t):
            m = d.model()
            d.x = Var()
            return d

        m.b.c.d = Block(m.b.t, rule=_d_rule)

        m.b.y = Var(m.b.t)

        def _con_rule(b, t):
            return b.y[t] <= b.c.d[t].x

        m.b.con = Constraint(m.b.t, rule=_con_rule)

        generate_finite_elements(m.b.t, 5)
        expand_components(m)

        self.assertEqual(len(m.b.c.d), 6)
        self.assertEqual(len(m.b.con), 6)
        self.assertEqual(len(m.b.y), 6)
Ejemplo n.º 25
0
    def test_mgv0(self):

        from lms2 import MainGridV0
        from pyomo.environ import AbstractModel, TransformationFactory, Param, Var
        from pyomo.dae import ContinuousSet
        from pyomo.network import Port

        m = AbstractModel()
        m.time = ContinuousSet(bounds=(0, 10))
        m.mg = MainGridV0()

        data_main_grid_v0 = {'time': {None: [0, 2]}, 'cost': {None: 0.15}}

        data = \
            {None:
                {
                    'time'  : {None: [0, 10]},
                    'mg'    : data_main_grid_v0
                }
            }

        inst = m.create_instance(data)
        TransformationFactory('dae.finite_difference').apply_to(inst, nfe=2)

        self.assertTrue(hasattr(m.mg, 'outlet'))
        self.assertIsInstance(m.mg.outlet, Port)
Ejemplo n.º 26
0
def create_model():
    m = ConcreteModel()

    m.a = Param(initialize=-0.2, mutable=True)
    m.H = Param(initialize=0.5, mutable=True)
    m.T = 15

    m.t = ContinuousSet(bounds=(0, m.T))

    m.x = Var(m.t)
    m.F = Var(m.t)
    m.u = Var(m.t, initialize=0, bounds=(-0.2, 0))

    m.dx = DerivativeVar(m.x, wrt=m.t)
    m.df0 = DerivativeVar(m.F, wrt=m.t)

    m.x[0].fix(5)
    m.F[0].fix(0)

    def _x(m, t):
        return m.dx[t] == m.a * m.x[t] + m.u[t]

    m.x_dot = Constraint(m.t, rule=_x)

    def _f0(m, t):
        return m.df0[t] == 0.25 * m.u[t]**2

    m.FDiffCon = Constraint(m.t, rule=_f0)

    def _Cost(m):
        return 0.5 * m.H * m.x[m.T]**2 + m.F[m.T]

    m.J = Objective(rule=_Cost)

    return m
Ejemplo n.º 27
0
    def test_update_block_derived_override_construct_withfcn2(self):
        class Foo(Block):
            updated = False

            def construct(self, data=None):
                Block.construct(self, data)

            def update_after_discretization(self):
                self.updated = True

        m = ConcreteModel()
        m.t = ContinuousSet(bounds=(0, 10))
        m.s = Set(initialize=[1, 2, 3])

        def _block_rule(b, t, s):
            m = b.model()

            def _init(m, j):
                return j * 2

            b.p1 = Param(m.t, default=_init)
            b.v1 = Var(m.t, initialize=5)

        m.foo = Foo(m.t, m.s, rule=_block_rule)

        generate_finite_elements(m.t, 5)
        expand_components(m)

        self.assertTrue(m.foo.updated)
        self.assertEqual(len(m.foo), 6)
        self.assertEqual(len(m.foo[0, 1].v1), 6)
Ejemplo n.º 28
0
    def test_update_contset_indexed_component_expressions_single(self):
        m = ConcreteModel()
        m.t = ContinuousSet(bounds=(0, 10))
        m.p = Param(m.t, default=3)
        m.v = Var(m.t, initialize=5)

        def _con1(m, i):
            return m.p[i] * m.v[i]

        m.con1 = Expression(m.t, rule=_con1)

        # Rules that iterate over a ContinuousSet implicitly are not updated
        # after the discretization
        def _con2(m):
            return sum(m.v[i] for i in m.t)

        m.con2 = Expression(rule=_con2)

        expansion_map = ComponentMap()

        generate_finite_elements(m.t, 5)
        update_contset_indexed_component(m.v, expansion_map)
        update_contset_indexed_component(m.p, expansion_map)
        update_contset_indexed_component(m.con1, expansion_map)
        update_contset_indexed_component(m.con2, expansion_map)

        self.assertTrue(len(m.con1) == 6)
        self.assertEqual(m.con1[2](), 15)
        self.assertEqual(m.con1[8](), 15)
        self.assertEqual(m.con2(), 10)
Ejemplo n.º 29
0
    def test_2level_model(self):
        m = ConcreteModel()
        m.T = ContinuousSet(bounds=(0,1))
        @m.Block([1,2],m.T)
        def B(b, i, t):
            @b.Block(list(range(2*i, 2*i+2)))
            def bb(bb, j):
                bb.y = Var([10,11])
            b.x = Var(list(range(2*i, 2*i+2)))

        regular, time = flatten_dae_variables(m, m.T)
        self.assertEqual(len(regular), 0)
        # Output for debugging
        #for v in time:
        #    v.pprint()
        #    for _ in v.values():
        #        print"     -> ", _.name
        ref_data = {
            self._hashRef(Reference(m.B[1,:].x[2])),
            self._hashRef(Reference(m.B[1,:].x[3])),
            self._hashRef(Reference(m.B[2,:].x[4])),
            self._hashRef(Reference(m.B[2,:].x[5])),
            self._hashRef(Reference(m.B[1,:].bb[2].y[10])),
            self._hashRef(Reference(m.B[1,:].bb[2].y[11])),
            self._hashRef(Reference(m.B[1,:].bb[3].y[10])),
            self._hashRef(Reference(m.B[1,:].bb[3].y[11])),
            self._hashRef(Reference(m.B[2,:].bb[4].y[10])),
            self._hashRef(Reference(m.B[2,:].bb[4].y[11])),
            self._hashRef(Reference(m.B[2,:].bb[5].y[10])),
            self._hashRef(Reference(m.B[2,:].bb[5].y[11])),
        }
        self.assertEqual(len(time), len(ref_data))
        for ref in time:
            self.assertIn(self._hashRef(ref), ref_data)
Ejemplo n.º 30
0
    def test_invalid_derivative(self):
        m = ConcreteModel()
        m.t = ContinuousSet(bounds=(0, 10))
        m.v = Var(m.t)
        m.dv = DerivativeVar(m.v, wrt=(m.t, m.t, m.t))

        with self.assertRaises(DAE_Error):
            TransformationFactory('dae.collocation').apply_to(m)