Beispiel #1
0
    def _test_disc_first(self, tname):

        ofile = join(currdir, tname + '.' + self.sim_mod + '.out')
        bfile = join(currdir, tname + '.' + self.sim_mod + '.txt')
        setup_redirect(ofile)

        # create model
        exmod = import_file(join(exdir, tname + '.py'))
        m = exmod.create_model()

        # Discretize model
        discretizer = TransformationFactory('dae.collocation')
        discretizer.apply_to(m, nfe=10, ncp=5)

        # Simulate model
        sim = Simulator(m, package=self.sim_mod)

        if hasattr(m, 'var_input'):
            tsim, profiles = sim.simulate(numpoints=100,
                                          varying_inputs=m.var_input)
        else:
            tsim, profiles = sim.simulate(numpoints=100)

        # Initialize model
        sim.initialize_model()

        self._print(m, profiles)

        reset_redirect()
        if not os.path.exists(bfile):
            os.rename(ofile, bfile)

        # os.system('diff ' + ofile + ' ' + bfile)
        self.assertFileEqualsBaseline(ofile, bfile, tolerance=0.01)
Beispiel #2
0
    def test_disc_invalid_options(self):
        m = self.m.clone()

        with self.assertRaises(TypeError):
            TransformationFactory('dae.collocation').apply_to(m, wrt=m.s)

        with self.assertRaises(ValueError):
            TransformationFactory('dae.collocation').apply_to(m, nfe=-1)

        with self.assertRaises(ValueError):
            TransformationFactory('dae.collocation').apply_to(m, ncp=0)

        with self.assertRaises(ValueError):
            TransformationFactory('dae.collocation').apply_to(m, scheme='foo')

        with self.assertRaises(ValueError):
            TransformationFactory('dae.collocation').apply_to(m, foo=True)

        TransformationFactory('dae.collocation').apply_to(m, wrt=m.t)
        with self.assertRaises(ValueError):
            TransformationFactory('dae.collocation').apply_to(m, wrt=m.t)

        m = self.m.clone()
        disc = TransformationFactory('dae.collocation')
        disc.apply_to(m)
        with self.assertRaises(ValueError):
            disc.apply_to(m)
Beispiel #3
0
 def run_bilevel(self, *args, **kwds):
     module = import_file(args[0])
     instance = module.pyomo_create_model(None, None)
     xfrm = TransformationFactory('bilevel.linear_mpec')
     xfrm.apply_to(instance, deterministic=True)
     instance.pprint(filename=join(currdir, self.problem +
                                   '_linear_mpec.out'))
Beispiel #4
0
    def test_disc_multi_index(self):
        m = self.m.clone()
        m.v2 = Var(m.t, m.s)
        m.dv2 = DerivativeVar(m.v2)

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

        self.assertTrue(hasattr(m, 'dv1_disc_eq'))
        self.assertTrue(hasattr(m, 'dv2_disc_eq'))
        self.assertTrue(len(m.dv2_disc_eq) == 45)
        self.assertTrue(len(m.v2) == 48)

        expected_tau_points = [0.0, 0.1550510257216822,
                               0.64494897427831788,
                               1.0]
        expected_disc_points = [0, 0.310102, 1.289898, 2.0, 2.310102,
                                3.289898,
                                4.0, 4.310102, 5.289898, 6.0, 6.310102,
                                7.289898, 8.0, 8.310102, 9.289898, 10]
        disc_info = m.t.get_discretization_info()

        self.assertTrue(disc_info['scheme'] == 'LAGRANGE-RADAU')

        for idx, val in enumerate(disc_info['tau_points']):
            self.assertAlmostEqual(val, expected_tau_points[idx])

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

        self.assertTrue(
            hasattr(m, '_pyomo_dae_reclassified_derivativevars'))
        self.assertTrue(m.dv1 in m._pyomo_dae_reclassified_derivativevars)
        self.assertTrue(m.dv2 in m._pyomo_dae_reclassified_derivativevars)
Beispiel #5
0
    def test_disc_invalid_options(self):
        m = self.m.clone()

        with self.assertRaises(TypeError):
            TransformationFactory('dae.finite_difference').apply_to(m, wrt=m.s)

        with self.assertRaises(ValueError):
            TransformationFactory('dae.finite_difference').apply_to(m, nfe=-1)

        with self.assertRaises(ValueError):
            TransformationFactory('dae.finite_difference').apply_to(m,
                                                                    scheme='foo')

        with self.assertRaises(ValueError):
            TransformationFactory('dae.finite_difference').apply_to(m,
                                                                    foo=True)

        TransformationFactory('dae.finite_difference').apply_to(m, wrt=m.t)
        with self.assertRaises(ValueError):
            TransformationFactory('dae.finite_difference').apply_to(m, wrt=m.t)

        m = self.m.clone()
        disc = TransformationFactory('dae.finite_difference')
        disc.apply_to(m)
        with self.assertRaises(ValueError):
            disc.apply_to(m)
Beispiel #6
0
    def test_disc_single_index_central(self):
        m = self.m.clone()
        disc = TransformationFactory('dae.finite_difference')
        disc.apply_to(m, nfe=5, scheme='CENTRAL')

        self.assertTrue(hasattr(m, 'dv1_disc_eq'))
        self.assertEqual(len(m.dv1_disc_eq), 4)
        self.assertEqual(len(m.v1), 6)

        expected_disc_points = [0, 2.0, 4.0, 6.0, 8.0, 10]
        disc_info = m.t.get_discretization_info()

        self.assertEqual(disc_info['scheme'], 'CENTRAL Difference')

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

        output = \
"""\
dv1_disc_eq : Size=4, Index=t, Active=True
    Key : Lower : Body                                : Upper : Active
    2.0 :   0.0 :   dv1[2.0] - 0.25*(v1[4.0] - v1[0]) :   0.0 :   True
    4.0 :   0.0 : dv1[4.0] - 0.25*(v1[6.0] - v1[2.0]) :   0.0 :   True
    6.0 :   0.0 : dv1[6.0] - 0.25*(v1[8.0] - v1[4.0]) :   0.0 :   True
    8.0 :   0.0 :  dv1[8.0] - 0.25*(v1[10] - v1[6.0]) :   0.0 :   True
"""
        out = StringIO()
        m.dv1_disc_eq.pprint(ostream=out)
        self.assertEqual(output, out.getvalue())
Beispiel #7
0
    def test_disc_single_index_backward(self):
        m = self.m.clone()
        disc = TransformationFactory('dae.finite_difference')
        disc.apply_to(m, nfe=5)

        self.assertTrue(hasattr(m, 'dv1_disc_eq'))
        self.assertEqual(len(m.dv1_disc_eq), 5)
        self.assertEqual(len(m.v1), 6)

        expected_disc_points = [0, 2.0, 4.0, 6.0, 8.0, 10]
        disc_info = m.t.get_discretization_info()

        self.assertEqual(disc_info['scheme'], 'BACKWARD Difference')

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

        self.assertTrue(hasattr(m, '_pyomo_dae_reclassified_derivativevars'))
        self.assertIn(m.dv1, m._pyomo_dae_reclassified_derivativevars)

        output = \
"""\
dv1_disc_eq : Size=5, Index=t, Active=True
    Key : Lower : Body                               : Upper : Active
    2.0 :   0.0 :   dv1[2.0] - 0.5*(v1[2.0] - v1[0]) :   0.0 :   True
    4.0 :   0.0 : dv1[4.0] - 0.5*(v1[4.0] - v1[2.0]) :   0.0 :   True
    6.0 :   0.0 : dv1[6.0] - 0.5*(v1[6.0] - v1[4.0]) :   0.0 :   True
    8.0 :   0.0 : dv1[8.0] - 0.5*(v1[8.0] - v1[6.0]) :   0.0 :   True
     10 :   0.0 :   dv1[10] - 0.5*(v1[10] - v1[8.0]) :   0.0 :   True
"""
        out = StringIO()
        m.dv1_disc_eq.pprint(ostream=out)
        self.assertEqual(output, out.getvalue())
Beispiel #8
0
    def test_disc_multidimen_index(self):
        m = self.m.clone()
        m.s2 = Set(initialize=[('A', 'B'), ('C', 'D'), ('E', 'F')])
        m.v2 = Var(m.t, m.s2)
        m.dv2 = DerivativeVar(m.v2)
        m.v3 = Var(m.s2, m.t)
        m.dv3 = DerivativeVar(m.v3)

        disc = TransformationFactory('dae.finite_difference')
        disc.apply_to(m, nfe=5)

        self.assertTrue(hasattr(m, 'dv1_disc_eq'))
        self.assertTrue(hasattr(m, 'dv2_disc_eq'))
        self.assertTrue(hasattr(m, 'dv3_disc_eq'))
        self.assertEqual(len(m.dv2_disc_eq), 15)
        self.assertEqual(len(m.v2), 18)
        self.assertEqual(len(m.dv3_disc_eq), 15)
        self.assertEqual(len(m.v3), 18)

        expected_disc_points = [0, 2.0, 4.0, 6.0, 8.0, 10]
        disc_info = m.t.get_discretization_info()

        self.assertEqual(disc_info['scheme'], 'BACKWARD Difference')

        for idx, val in enumerate(list(m.t)):
            self.assertAlmostEqual(val, expected_disc_points[idx])
Beispiel #9
0
 def test_var_bound_propagate_revert(self):
     """Test to make sure bound propagation revert works."""
     m = ConcreteModel()
     m.v1 = Var(initialize=1, bounds=(1, 3))
     m.v2 = Var(initialize=2, bounds=(0, 8))
     m.v3 = Var(initialize=3, bounds=(2, 4))
     m.v4 = Var(initialize=4, bounds=(0, 5))
     m.c1 = Constraint(expr=m.v1 == m.v2)
     m.c2 = Constraint(expr=m.v2 == m.v3)
     m.c3 = Constraint(expr=m.v3 == m.v4)
     xfrm = TransformationFactory('contrib.propagate_eq_var_bounds')
     xfrm.apply_to(m, tmp=True)
     self.assertEquals(value(m.v1.lb), 2)
     self.assertEquals(value(m.v1.lb), value(m.v2.lb))
     self.assertEquals(value(m.v1.lb), value(m.v3.lb))
     self.assertEquals(value(m.v1.lb), value(m.v4.lb))
     self.assertEquals(value(m.v1.ub), 3)
     self.assertEquals(value(m.v1.ub), value(m.v2.ub))
     self.assertEquals(value(m.v1.ub), value(m.v3.ub))
     self.assertEquals(value(m.v1.ub), value(m.v4.ub))
     xfrm.revert(m)
     self.assertEquals(value(m.v1.lb), 1)
     self.assertEquals(value(m.v2.lb), 0)
     self.assertEquals(value(m.v3.lb), 2)
     self.assertEquals(value(m.v4.lb), 0)
     self.assertEquals(value(m.v1.ub), 3)
     self.assertEquals(value(m.v2.ub), 8)
     self.assertEquals(value(m.v3.ub), 4)
     self.assertEquals(value(m.v4.ub), 5)
Beispiel #10
0
    def _test(self, tname):

        ofile = join(currdir, tname + '.' + self.sim_mod + '.out')
        bfile = join(currdir, tname + '.' + self.sim_mod + '.txt')
        setup_redirect(ofile)

        # create model
        exmod = import_file(join(exdir, tname + '.py'))
        m = exmod.create_model()

        # Simulate model
        sim = Simulator(m, package=self.sim_mod)

        if hasattr(m, 'var_input'):
            tsim, profiles = sim.simulate(numpoints=100,
                                          varying_inputs=m.var_input)
        else:
            tsim, profiles = sim.simulate(numpoints=100)

        # Discretize model
        discretizer = TransformationFactory('dae.collocation')
        discretizer.apply_to(m, nfe=10, ncp=5)

        # Initialize model
        sim.initialize_model()

        self._print(m, profiles)

        reset_redirect()
        if not os.path.exists(bfile):
            os.rename(ofile, bfile)

        # os.system('diff ' + ofile + ' ' + bfile)
        self.assertFileEqualsBaseline(ofile, bfile, tolerance=0.01)
Beispiel #11
0
    def test_disc_single_index_backward(self):
        m = self.m.clone()
        disc = TransformationFactory('dae.finite_difference')
        disc.apply_to(m, nfe=5)
         
        self.assertTrue(hasattr(m, 'dv1_disc_eq'))
        self.assertTrue(len(m.dv1_disc_eq) == 5)
        self.assertTrue(len(m.v1) == 6)

        expected_disc_points = [0, 2.0, 4.0, 6.0, 8.0, 10]
        disc_info = m.t.get_discretization_info()

        self.assertTrue(disc_info['scheme'] == 'BACKWARD Difference')

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

        self.assertTrue(hasattr(m, '_pyomo_dae_reclassified_derivativevars'))
        self.assertTrue(m.dv1 in m._pyomo_dae_reclassified_derivativevars)

        output = \
"""\
dv1_disc_eq : Size=5, Index=t, Active=True
    Key : Lower : Body                               : Upper : Active
    2.0 :   0.0 :   dv1[2.0] - 0.5*(v1[2.0] - v1[0]) :   0.0 :   True
    4.0 :   0.0 : dv1[4.0] - 0.5*(v1[4.0] - v1[2.0]) :   0.0 :   True
    6.0 :   0.0 : dv1[6.0] - 0.5*(v1[6.0] - v1[4.0]) :   0.0 :   True
    8.0 :   0.0 : dv1[8.0] - 0.5*(v1[8.0] - v1[6.0]) :   0.0 :   True
     10 :   0.0 :   dv1[10] - 0.5*(v1[10] - v1[8.0]) :   0.0 :   True
"""
        out = StringIO()
        m.dv1_disc_eq.pprint(ostream=out)
        self.assertEqual(output, out.getvalue())
Beispiel #12
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)
Beispiel #13
0
    def test_disc_second_order_legendre(self):
        m = self.m.clone()
        m.dv1dt2 = DerivativeVar(m.v1, wrt=(m.t, m.t))
        disc = TransformationFactory('dae.collocation')
        disc.apply_to(m, nfe=2, ncp=2, scheme='LAGRANGE-LEGENDRE')
         
        self.assertTrue(hasattr(m, 'dv1dt2_disc_eq'))
        self.assertTrue(hasattr(m, 'v1_t_cont_eq'))
        self.assertTrue(len(m.dv1dt2_disc_eq) == 4)
        self.assertTrue(len(m.v1_t_cont_eq) == 2)
        self.assertTrue(len(m.v1) == 7)

        self.assertTrue(hasattr(m, '_pyomo_dae_reclassified_derivativevars'))
        self.assertTrue(m.dv1 in m._pyomo_dae_reclassified_derivativevars)
        self.assertTrue(m.dv1dt2 in m._pyomo_dae_reclassified_derivativevars)

        repn_baseline = {id(m.dv1dt2[1.056624]): 1,
                         id(m.v1[0]): -0.48,
                         id(m.v1[1.056624]): 0.65569,
                         id(m.v1[3.943376]): -0.17569}

        repn = generate_standard_repn(m.dv1dt2_disc_eq[1.056624].body)
        repn_gen = repn_to_rounded_dict(repn, 5)
        self.assertEqual(repn_baseline, repn_gen)

        repn_baseline = {id(m.dv1dt2[6.056624]): 1,
                         id(m.v1[5.0]): -0.48,
                         id(m.v1[6.056624]): 0.65569,
                         id(m.v1[8.943376]): -0.17569}

        repn = generate_standard_repn(m.dv1dt2_disc_eq[6.056624].body)
        repn_gen = repn_to_rounded_dict(repn, 5)
        self.assertEqual(repn_baseline, repn_gen)
Beispiel #14
0
    def test_disc_second_order_legendre(self):
        m = self.m.clone()
        m.dv1dt2 = DerivativeVar(m.v1, wrt=(m.t, m.t))
        disc = TransformationFactory('dae.collocation')
        disc.apply_to(m, nfe=2, ncp=2, scheme='LAGRANGE-LEGENDRE')
         
        self.assertTrue(hasattr(m, 'dv1dt2_disc_eq'))
        self.assertTrue(hasattr(m, 'v1_t_cont_eq'))
        self.assertTrue(len(m.dv1dt2_disc_eq) == 4)
        self.assertTrue(len(m.v1_t_cont_eq) == 2)
        self.assertTrue(len(m.v1) == 7)

        self.assertTrue(hasattr(m, '_pyomo_dae_reclassified_derivativevars'))
        self.assertTrue(m.dv1 in m._pyomo_dae_reclassified_derivativevars)
        self.assertTrue(m.dv1dt2 in m._pyomo_dae_reclassified_derivativevars)

        repn_baseline = {id(m.dv1dt2[1.056624]): 1,
                         id(m.v1[0]): -0.48,
                         id(m.v1[1.056624]): 0.65569,
                         id(m.v1[3.943376]): -0.17569}

        repn = generate_standard_repn(m.dv1dt2_disc_eq[1.056624].body)
        repn_gen = repn_to_rounded_dict(repn, 5)
        self.assertEqual(repn_baseline, repn_gen)

        repn_baseline = {id(m.dv1dt2[6.056624]): 1,
                         id(m.v1[5.0]): -0.48,
                         id(m.v1[6.056624]): 0.65569,
                         id(m.v1[8.943376]): -0.17569}

        repn = generate_standard_repn(m.dv1dt2_disc_eq[6.056624].body)
        repn_gen = repn_to_rounded_dict(repn, 5)
        self.assertEqual(repn_baseline, repn_gen)
Beispiel #15
0
    def test_disc_second_order_radau(self):
        m = self.m.clone()
        m.dv1dt2 = DerivativeVar(m.v1, wrt=(m.t, m.t))
        disc = TransformationFactory('dae.collocation')
        disc.apply_to(m, nfe=2, ncp=2)
         
        self.assertTrue(hasattr(m, 'dv1dt2_disc_eq'))
        self.assertTrue(len(m.dv1dt2_disc_eq) == 4)
        self.assertTrue(len(m.v1) == 5)

        self.assertTrue(hasattr(m, '_pyomo_dae_reclassified_derivativevars'))
        self.assertTrue(m.dv1 in m._pyomo_dae_reclassified_derivativevars)
        self.assertTrue(m.dv1dt2 in m._pyomo_dae_reclassified_derivativevars)

        repn_baseline = {id(m.dv1dt2[5.0]): 1,
                         id(m.v1[0]): -0.24,
                         id(m.v1[1.666667]): 0.36,
                         id(m.v1[5.0]): -0.12}

        repn = generate_standard_repn(m.dv1dt2_disc_eq[5.0].body)
        repn_gen = repn_to_rounded_dict(repn, 5)
        self.assertEqual(repn_baseline, repn_gen)

        repn_baseline = {id(m.dv1dt2[10]): 1,
                         id(m.v1[5.0]): -0.24,
                         id(m.v1[6.666667]): 0.36,
                         id(m.v1[10]): -0.12}

        repn = generate_standard_repn(m.dv1dt2_disc_eq[10.0].body)
        repn_gen = repn_to_rounded_dict(repn, 5)
        self.assertEqual(repn_baseline, repn_gen)
Beispiel #16
0
    def test_disc_multi_index(self):
        m = self.m.clone()
        m.v2 = Var(m.t, m.s)
        m.dv2 = DerivativeVar(m.v2)

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

        self.assertTrue(hasattr(m, 'dv1_disc_eq'))
        self.assertTrue(hasattr(m, 'dv2_disc_eq'))
        self.assertTrue(len(m.dv2_disc_eq) == 45)
        self.assertTrue(len(m.v2) == 48)

        expected_tau_points = [0.0, 0.1550510257216822,
                               0.64494897427831788,
                               1.0]
        expected_disc_points = [0, 0.310102, 1.289898, 2.0, 2.310102,
                                3.289898,
                                4.0, 4.310102, 5.289898, 6.0, 6.310102,
                                7.289898, 8.0, 8.310102, 9.289898, 10]
        disc_info = m.t.get_discretization_info()

        self.assertTrue(disc_info['scheme'] == 'LAGRANGE-RADAU')

        for idx, val in enumerate(disc_info['tau_points']):
            self.assertAlmostEqual(val, expected_tau_points[idx])

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

        self.assertTrue(
            hasattr(m, '_pyomo_dae_reclassified_derivativevars'))
        self.assertTrue(m.dv1 in m._pyomo_dae_reclassified_derivativevars)
        self.assertTrue(m.dv2 in m._pyomo_dae_reclassified_derivativevars)
Beispiel #17
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)
 def test_var_bound_propagate_revert(self):
     """Test to make sure bound propagation revert works."""
     m = ConcreteModel()
     m.v1 = Var(initialize=1, bounds=(1, 3))
     m.v2 = Var(initialize=2, bounds=(0, 8))
     m.v3 = Var(initialize=3, bounds=(2, 4))
     m.v4 = Var(initialize=4, bounds=(0, 5))
     m.c1 = Constraint(expr=m.v1 == m.v2)
     m.c2 = Constraint(expr=m.v2 == m.v3)
     m.c3 = Constraint(expr=m.v3 == m.v4)
     xfrm = TransformationFactory('contrib.propagate_eq_var_bounds')
     xfrm.apply_to(m, tmp=True)
     self.assertEquals(value(m.v1.lb), 2)
     self.assertEquals(value(m.v1.lb), value(m.v2.lb))
     self.assertEquals(value(m.v1.lb), value(m.v3.lb))
     self.assertEquals(value(m.v1.lb), value(m.v4.lb))
     self.assertEquals(value(m.v1.ub), 3)
     self.assertEquals(value(m.v1.ub), value(m.v2.ub))
     self.assertEquals(value(m.v1.ub), value(m.v3.ub))
     self.assertEquals(value(m.v1.ub), value(m.v4.ub))
     xfrm.revert(m)
     self.assertEquals(value(m.v1.lb), 1)
     self.assertEquals(value(m.v2.lb), 0)
     self.assertEquals(value(m.v3.lb), 2)
     self.assertEquals(value(m.v4.lb), 0)
     self.assertEquals(value(m.v1.ub), 3)
     self.assertEquals(value(m.v2.ub), 8)
     self.assertEquals(value(m.v3.ub), 4)
     self.assertEquals(value(m.v4.ub), 5)
Beispiel #19
0
    def test_disc_second_order_radau(self):
        m = self.m.clone()
        m.dv1dt2 = DerivativeVar(m.v1, wrt=(m.t, m.t))
        disc = TransformationFactory('dae.collocation')
        disc.apply_to(m, nfe=2, ncp=2)
         
        self.assertTrue(hasattr(m, 'dv1dt2_disc_eq'))
        self.assertTrue(len(m.dv1dt2_disc_eq) == 4)
        self.assertTrue(len(m.v1) == 5)

        self.assertTrue(hasattr(m, '_pyomo_dae_reclassified_derivativevars'))
        self.assertTrue(m.dv1 in m._pyomo_dae_reclassified_derivativevars)
        self.assertTrue(m.dv1dt2 in m._pyomo_dae_reclassified_derivativevars)

        repn_baseline = {id(m.dv1dt2[5.0]): 1,
                         id(m.v1[0]): -0.24,
                         id(m.v1[1.666667]): 0.36,
                         id(m.v1[5.0]): -0.12}

        repn = generate_standard_repn(m.dv1dt2_disc_eq[5.0].body)
        repn_gen = repn_to_rounded_dict(repn, 5)
        self.assertEqual(repn_baseline, repn_gen)

        repn_baseline = {id(m.dv1dt2[10]): 1,
                         id(m.v1[5.0]): -0.24,
                         id(m.v1[6.666667]): 0.36,
                         id(m.v1[10]): -0.12}

        repn = generate_standard_repn(m.dv1dt2_disc_eq[10.0].body)
        repn_gen = repn_to_rounded_dict(repn, 5)
        self.assertEqual(repn_baseline, repn_gen)
Beispiel #20
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'))
Beispiel #21
0
    def _test_disc_first(self, tname):

        bfile = join(currdir, tname + '.' + self.sim_mod + '.json')

        # create model
        exmod = import_file(join(exdir, tname + '.py'))
        m = exmod.create_model()

        # Discretize model
        discretizer = TransformationFactory('dae.collocation')
        discretizer.apply_to(m, nfe=10, ncp=5)

        # Simulate model
        sim = Simulator(m, package=self.sim_mod)

        if hasattr(m, 'var_input'):
            tsim, profiles = sim.simulate(numpoints=100,
                                          varying_inputs=m.var_input)
        else:
            tsim, profiles = sim.simulate(numpoints=100)

        # Initialize model
        sim.initialize_model()

        results = self._store_results(m, profiles)

        # Used to regenerate baseline files
        if not os.path.exists(bfile):
            with open(bfile, 'w') as f1:
                json.dump(results, f1)

        # Compare results to baseline
        with open(bfile, 'r') as f2:
            baseline = json.load(f2)
            self.assertStructuredAlmostEqual(results, baseline, abstol=1e-2)
Beispiel #22
0
    def test_disc_multidimen_index(self):
        m = self.m.clone()
        m.s2 = Set(initialize=[('A', 'B'), ('C', 'D'), ('E', 'F')])
        m.v2 = Var(m.t, m.s2)
        m.dv2 = DerivativeVar(m.v2)
        m.v3 = Var(m.s2, m.t)
        m.dv3 = DerivativeVar(m.v3)

        disc = TransformationFactory('dae.finite_difference')
        disc.apply_to(m, nfe=5)

        self.assertTrue(hasattr(m, 'dv1_disc_eq'))
        self.assertTrue(hasattr(m, 'dv2_disc_eq'))
        self.assertTrue(hasattr(m, 'dv3_disc_eq'))
        self.assertTrue(len(m.dv2_disc_eq) == 15)
        self.assertTrue(len(m.v2) == 18)
        self.assertTrue(len(m.dv3_disc_eq) == 15)
        self.assertTrue(len(m.v3) == 18)

        expected_disc_points = [0, 2.0, 4.0, 6.0, 8.0, 10]
        disc_info = m.t.get_discretization_info()

        self.assertTrue(disc_info['scheme'] == 'BACKWARD Difference')

        for idx, val in enumerate(list(m.t)):
            self.assertAlmostEqual(val, expected_disc_points[idx])
Beispiel #23
0
 def test_var_bound_propagate_crossover(self):
     """Test for error message when variable bound crosses over."""
     m = ConcreteModel()
     m.v1 = Var(initialize=1, bounds=(1, 3))
     m.v2 = Var(initialize=5, bounds=(4, 8))
     m.c1 = Constraint(expr=m.v1 == m.v2)
     xfrm = TransformationFactory('contrib.propagate_eq_var_bounds')
     with self.assertRaises(ValueError):
         xfrm.apply_to(m)
 def test_var_bound_propagate_crossover(self):
     """Test for error message when variable bound crosses over."""
     m = ConcreteModel()
     m.v1 = Var(initialize=1, bounds=(1, 3))
     m.v2 = Var(initialize=5, bounds=(4, 8))
     m.c1 = Constraint(expr=m.v1 == m.v2)
     xfrm = TransformationFactory('contrib.propagate_eq_var_bounds')
     with self.assertRaises(ValueError):
         xfrm.apply_to(m)
Beispiel #25
0
    def test_disc_single_index_legendre(self):
        m = self.m.clone()
        disc = TransformationFactory('dae.collocation')
        disc.apply_to(m, nfe=5, ncp=3, scheme='LAGRANGE-LEGENDRE')

        self.assertTrue(hasattr(m, 'dv1_disc_eq'))
        self.assertTrue(hasattr(m, 'v1_t_cont_eq'))
        self.assertTrue(len(m.dv1_disc_eq) == 15)
        self.assertTrue(len(m.v1_t_cont_eq) == 5)
        self.assertTrue(len(m.v1) == 21)

        expected_tau_points = [
            0.0, 0.11270166537925834, 0.49999999999999989, 0.88729833462074226
        ]
        expected_disc_points = [
            0, 0.225403, 1.0, 1.774597, 2.0, 2.225403, 3.0, 3.774597, 4.0,
            4.225403, 5.0, 5.774597, 6.0, 6.225403, 7.0, 7.774597, 8.0,
            8.225403, 9.0, 9.774597, 10
        ]
        disc_info = m.t.get_discretization_info()

        self.assertTrue(disc_info['scheme'] == 'LAGRANGE-LEGENDRE')

        for idx, val in enumerate(disc_info['tau_points']):
            self.assertAlmostEqual(val, expected_tau_points[idx])

        for idx, val in enumerate(list(m.t)):
            self.assertAlmostEqual(val, expected_disc_points[idx])
            self.assertTrue(type(val) in [float, int])

        self.assertTrue(hasattr(m, '_pyomo_dae_reclassified_derivativevars'))
        self.assertTrue(m.dv1 in m._pyomo_dae_reclassified_derivativevars)

        repn_baseline = {
            id(m.dv1[3.0]): 1,
            id(m.v1[2.0]): -1.5,
            id(m.v1[2.225403]): 2.86374,
            id(m.v1[3.0]): -1.0,
            id(m.v1[3.774597]): -0.36374
        }

        repn = generate_standard_repn(m.dv1_disc_eq[3.0].body)
        repn_gen = repn_to_rounded_dict(repn, 5)
        self.assertEqual(repn_baseline, repn_gen)

        repn_baseline = {
            id(m.dv1[5.0]): 1,
            id(m.v1[4.0]): -1.5,
            id(m.v1[4.225403]): 2.86374,
            id(m.v1[5.0]): -1.0,
            id(m.v1[5.774597]): -0.36374
        }

        repn = generate_standard_repn(m.dv1_disc_eq[5.0].body)
        repn_gen = repn_to_rounded_dict(repn, 5)
        self.assertEqual(repn_baseline, repn_gen)
Beispiel #26
0
    def test_discretize_twice(self):
        m = self.m.clone()

        disc1 = TransformationFactory('dae.finite_difference')
        disc1.apply_to(m, nfe=5)

        disc2 = TransformationFactory('dae.finite_difference')

        with self.assertRaises(DAE_Error):
            disc2.apply_to(m, nfe=5)
Beispiel #27
0
    def test_discretize_twice(self):
        m = self.m.clone()

        disc1 = TransformationFactory('dae.collocation')
        disc1.apply_to(m, nfe=5, ncp=3)

        disc2 = TransformationFactory('dae.collocation')

        with self.assertRaises(DAE_Error):
            disc2.apply_to(m, nfe=5, ncp=3)
Beispiel #28
0
    def test_discretize_twice(self):
        m = self.m.clone()

        disc1 = TransformationFactory('dae.collocation')
        disc1.apply_to(m, nfe=5, ncp=3)

        disc2 = TransformationFactory('dae.collocation')

        with self.assertRaises(DAE_Error):
            disc2.apply_to(m, nfe=5, ncp=3)
Beispiel #29
0
    def test_discretize_twice(self):
        m = self.m.clone()

        disc1 = TransformationFactory('dae.finite_difference')
        disc1.apply_to(m, nfe=5)

        disc2 = TransformationFactory('dae.finite_difference')

        with self.assertRaises(DAE_Error):
            disc2.apply_to(m, nfe=5)
Beispiel #30
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
Beispiel #31
0
 def test_var_bound_propagate_crossover(self):
     """Test for error message when variable bound crosses over."""
     m = ConcreteModel()
     m.v1 = Var(initialize=1, bounds=(1, 3))
     m.v2 = Var(initialize=5, bounds=(4, 8))
     m.c1 = Constraint(expr=m.v1 == m.v2)
     xfrm = TransformationFactory('contrib.propagate_eq_var_bounds')
     with self.assertRaisesRegex(InfeasibleConstraintException,
                                 "Variable v2 has a lower bound 4 > the "
                                 "upper bound 3 of variable v1, but they "
                                 "are linked by equality constraints"):
         xfrm.apply_to(m)
Beispiel #32
0
    def test_disc_single_index_radau(self):
        m = self.m.clone()
        disc = TransformationFactory('dae.collocation')
        disc.apply_to(m, nfe=5, ncp=3)

        self.assertTrue(hasattr(m, 'dv1_disc_eq'))
        self.assertTrue(len(m.dv1_disc_eq) == 15)
        self.assertTrue(len(m.v1) == 16)

        expected_tau_points = [
            0.0, 0.1550510257216822, 0.64494897427831788, 1.0
        ]
        expected_disc_points = [
            0, 0.310102, 1.289898, 2.0, 2.310102, 3.289898, 4.0, 4.310102,
            5.289898, 6.0, 6.310102, 7.289898, 8.0, 8.310102, 9.289898, 10
        ]
        disc_info = m.t.get_discretization_info()

        self.assertTrue(disc_info['scheme'] == 'LAGRANGE-RADAU')

        for idx, val in enumerate(disc_info['tau_points']):
            self.assertAlmostEqual(val, expected_tau_points[idx])

        for idx, val in enumerate(list(m.t)):
            self.assertAlmostEqual(val, expected_disc_points[idx])
            self.assertTrue(type(val) in [float, int])

        self.assertTrue(hasattr(m, '_pyomo_dae_reclassified_derivativevars'))
        self.assertTrue(m._pyomo_dae_reclassified_derivativevars[0] is m.dv1)

        repn_baseline = {
            id(m.dv1[2.0]): 1.0,
            id(m.v1[0]): 1.5,
            id(m.v1[0.310102]): -2.76599,
            id(m.v1[1.289898]): 3.76599,
            id(m.v1[2.0]): -2.5
        }

        repn = generate_standard_repn(m.dv1_disc_eq[2.0].body)
        repn_gen = repn_to_rounded_dict(repn, 5)
        self.assertEqual(repn_baseline, repn_gen)

        repn_baseline = {
            id(m.dv1[4.0]): 1.0,
            id(m.v1[2.0]): 1.5,
            id(m.v1[2.310102]): -2.76599,
            id(m.v1[3.289898]): 3.76599,
            id(m.v1[4.0]): -2.5
        }

        repn = generate_standard_repn(m.dv1_disc_eq[4.0].body)
        repn_gen = repn_to_rounded_dict(repn, 5)
        self.assertEqual(repn_baseline, repn_gen)
def test_initialize_dyn(build_turbine_dyn):
    """Initialize a turbine model"""
    m = build_turbine_dyn
    hin = iapws95.htpx(T=880, P=2.4233e7)
    discretizer = TransformationFactory('dae.finite_difference')
    discretizer.apply_to(m, nfe=4, wrt=m.fs.time, scheme='BACKWARD')

    # fix inlet
    m.fs.turb.inlet.enth_mol.fix(hin)
    m.fs.turb.inlet.flow_mol.fix(26000 / 4.0)
    m.fs.turb.inlet.pressure.fix(2.4233e7)
    m.fs.turb.initialize()
Beispiel #34
0
def initialize_model(m, nfe):
    u_profile = {0: -0.06}

    m.u_input = Suffix(direction=Suffix.LOCAL)
    m.u_input[m.u] = u_profile

    sim = Simulator(m, package='scipy')
    tsim, profiles = sim.simulate(numpoints=100, varying_inputs=m.u_input)

    discretizer = TransformationFactory('dae.collocation')
    discretizer.apply_to(m, nfe=nfe, ncp=1, scheme='LAGRANGE-RADAU')

    sim.initialize_model()
Beispiel #35
0
 def test_relax_integrality_only_active_blocks(self):
     self.model.x = Var(domain=NonNegativeIntegers)
     self.model.b = Block()
     self.model.b.x = Var(domain=Binary)
     self.model.b.y = Var(domain=Integers, bounds=(-3,2))
     instance = self.model.create_instance()
     instance.b.deactivate()
     relax_integrality = TransformationFactory('core.relax_integer_vars')
     relax_integrality.apply_to(instance, transform_deactivated_blocks=False)
     self.assertIs(instance.b.x.domain, Binary)
     self.assertIs(instance.b.y.domain, Integers)
     self.assertIs(instance.x.domain, Reals)
     self.assertEqual(instance.x.lb, 0)
     self.assertIsNone(instance.x.ub)
Beispiel #36
0
    def test_disc_single_index_legendre(self):
        m = self.m.clone()
        disc = TransformationFactory('dae.collocation')
        disc.apply_to(m, nfe=5, ncp=3, scheme='LAGRANGE-LEGENDRE')
         
        self.assertTrue(hasattr(m, 'dv1_disc_eq'))
        self.assertTrue(hasattr(m, 'v1_t_cont_eq'))
        self.assertTrue(len(m.dv1_disc_eq) == 15)
        self.assertTrue(len(m.v1_t_cont_eq) == 5)
        self.assertTrue(len(m.v1) == 21)

        expected_tau_points = [0.0, 0.11270166537925834, 0.49999999999999989,
                               0.88729833462074226]
        expected_disc_points = [0, 0.225403, 1.0, 1.774597, 2.0, 2.225403,
                                3.0, 3.774597, 4.0, 4.225403, 5.0, 5.774597,
                                6.0, 6.225403, 7.0, 7.774597, 8.0,
                                8.225403, 9.0, 9.774597, 10]
        disc_info = m.t.get_discretization_info()

        self.assertTrue(disc_info['scheme'] == 'LAGRANGE-LEGENDRE')

        for idx, val in enumerate(disc_info['tau_points']):
            self.assertAlmostEqual(val, expected_tau_points[idx])

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

        self.assertTrue(hasattr(m, '_pyomo_dae_reclassified_derivativevars'))
        self.assertTrue(m.dv1 in m._pyomo_dae_reclassified_derivativevars)

        repn_baseline = {id(m.dv1[3.0]): 1,
                         id(m.v1[2.0]): -1.5,
                         id(m.v1[2.225403]): 2.86374,
                         id(m.v1[3.0]): -1.0,
                         id(m.v1[3.774597]): -0.36374}

        repn = generate_standard_repn(m.dv1_disc_eq[3.0].body)
        repn_gen = repn_to_rounded_dict(repn, 5)
        self.assertEqual(repn_baseline, repn_gen)

        repn_baseline = {id(m.dv1[5.0]): 1,
                         id(m.v1[4.0]): -1.5,
                         id(m.v1[4.225403]): 2.86374,
                         id(m.v1[5.0]): -1.0,
                         id(m.v1[5.774597]): -0.36374}

        repn = generate_standard_repn(m.dv1_disc_eq[5.0].body)
        repn_gen = repn_to_rounded_dict(repn, 5)
        self.assertEqual(repn_baseline, repn_gen)
Beispiel #37
0
    def test_strip_bounds_maps_exist(self):
        """Tests if component maps for reversion already exist."""
        m = ConcreteModel()
        m.v0 = Var(bounds=(2, 4))
        m.v1 = Var(domain=NonNegativeReals)
        m.v2 = Var(domain=PositiveReals)
        m.v3 = Var(bounds=(-1, 1))
        m.v4 = Var(domain=Binary)
        m.v5 = Var(domain=Integers, bounds=(15, 16))

        xfrm = TransformationFactory('contrib.strip_var_bounds')
        xfrm.apply_to(m, reversible=True)
        # At this point, component maps for reversion already exist.
        with self.assertRaises(RuntimeError):
            xfrm.apply_to(m, reversible=True)
Beispiel #38
0
    def test_fixed_var_revert(self):
        """Test for reversion of fixed variables."""
        m = ConcreteModel()
        m.v1 = Var(initialize=1)
        m.v2 = Var(initialize=2)
        m.v1.setub(2)
        m.v1.setlb(2)

        xfrm = TransformationFactory('contrib.detect_fixed_vars')
        xfrm.apply_to(m, tmp=True)
        self.assertTrue(m.v1.fixed)
        self.assertFalse(m.v2.fixed)
        xfrm.revert(m)
        self.assertFalse(m.v1.fixed)
        self.assertEqual(value(m.v1), 1)
Beispiel #39
0
    def test_fixed_var_revert(self):
        """Test for reversion of fixed variables."""
        m = ConcreteModel()
        m.v1 = Var(initialize=1)
        m.v2 = Var(initialize=2)
        m.v1.setub(2)
        m.v1.setlb(2)

        xfrm = TransformationFactory('contrib.detect_fixed_vars')
        xfrm.apply_to(m, tmp=True)
        self.assertTrue(m.v1.fixed)
        self.assertFalse(m.v2.fixed)
        xfrm.revert(m)
        self.assertFalse(m.v1.fixed)
        self.assertEqual(value(m.v1), 1)
Beispiel #40
0
def initialize_model(m, n_sim, n_nfe, n_ncp):
    vp_profile = {0: 0.75}
    vt_profile = {0: 0.75}

    m.u_input = Suffix(direction=Suffix.LOCAL)
    m.u_input[m.vp] = vp_profile
    m.u_input[m.vt] = vt_profile

    sim = Simulator(m, package='scipy')
    tsim, profiles = sim.simulate(numpoints=n_sim, varying_inputs=m.u_input)

    discretizer = TransformationFactory('dae.collocation')
    discretizer.apply_to(m, nfe=n_nfe, ncp=n_ncp, scheme='LAGRANGE-RADAU')

    sim.initialize_model()
Beispiel #41
0
    def test_disc_single_index_radau(self):
        m = self.m.clone()
        disc = TransformationFactory('dae.collocation')
        disc.apply_to(m, nfe=5, ncp=3)
         
        self.assertTrue(hasattr(m, 'dv1_disc_eq'))
        self.assertTrue(len(m.dv1_disc_eq) == 15)
        self.assertTrue(len(m.v1) == 16)

        expected_tau_points = [0.0, 0.1550510257216822,
                               0.64494897427831788, 1.0]
        expected_disc_points = [0, 0.310102, 1.289898, 2.0, 2.310102,
                                3.289898, 4.0, 4.310102, 5.289898, 6.0,
                                6.310102, 7.289898, 8.0, 8.310102, 9.289898,
                                10]
        disc_info = m.t.get_discretization_info()

        self.assertTrue(disc_info['scheme'] == 'LAGRANGE-RADAU')

        for idx, val in enumerate(disc_info['tau_points']):
            self.assertAlmostEqual(val, expected_tau_points[idx])

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

        self.assertTrue(hasattr(m, '_pyomo_dae_reclassified_derivativevars'))
        self.assertTrue(m._pyomo_dae_reclassified_derivativevars[0] is m.dv1)

        repn_baseline = {id(m.dv1[2.0]): 1.0,
                         id(m.v1[0]): 1.5,
                         id(m.v1[0.310102]): -2.76599,
                         id(m.v1[1.289898]): 3.76599,
                         id(m.v1[2.0]): -2.5}

        repn = generate_standard_repn(m.dv1_disc_eq[2.0].body)
        repn_gen = repn_to_rounded_dict(repn, 5)
        self.assertEqual(repn_baseline, repn_gen)

        repn_baseline = {id(m.dv1[4.0]): 1.0,
                         id(m.v1[2.0]): 1.5,
                         id(m.v1[2.310102]): -2.76599,
                         id(m.v1[3.289898]): 3.76599,
                         id(m.v1[4.0]): -2.5}

        repn = generate_standard_repn(m.dv1_disc_eq[4.0].body)
        repn_gen = repn_to_rounded_dict(repn, 5)
        self.assertEqual(repn_baseline, repn_gen)
Beispiel #42
0
    def test_lookup_legendre_collocation_points(self):
        # Save initial flag value
        colloc_numpy_avail = pyomo.dae.plugins.colloc.numpy_available

        # Numpy flag must be False to test lookup
        pyomo.dae.plugins.colloc.numpy_available = False

        m = self.m.clone()
        disc = TransformationFactory('dae.collocation')
        disc.apply_to(m, nfe=5, ncp=3, scheme='LAGRANGE-LEGENDRE')

        self.assertTrue(hasattr(m, 'dv1_disc_eq'))
        self.assertTrue(len(m.dv1_disc_eq) == 15)
        self.assertTrue(len(m.v1) == 21)

        expected_tau_points = [
            0.0, 0.11270166537925834, 0.49999999999999989, 0.88729833462074226
        ]
        expected_disc_points = [
            0, 0.225403, 1.0, 1.774597, 2.0, 2.225403, 3.0, 3.774597, 4.0,
            4.225403, 5.0, 5.774597, 6.0, 6.225403, 7.0, 7.774597, 8.0,
            8.225403, 9.0, 9.774597, 10
        ]

        disc_info = m.t.get_discretization_info()

        self.assertTrue(disc_info['scheme'] == 'LAGRANGE-LEGENDRE')

        for idx, val in enumerate(disc_info['tau_points']):
            self.assertAlmostEqual(val, expected_tau_points[idx])

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

        m = self.m.clone()
        try:
            disc = TransformationFactory('dae.collocation')
            disc.apply_to(m, ncp=15, scheme='LAGRANGE-LEGENDRE')
            self.fail('Expected ValueError')
        except ValueError:
            pass

        # Restore initial flag value
        pyomo.dae.plugins.colloc.numpy_available = colloc_numpy_avail
Beispiel #43
0
    def test_deactivate_trivial_constraints_revert(self):
        """Test for reversion of trivial constraint deactivation."""
        m = ConcreteModel()
        m.v1 = Var(initialize=1)
        m.v2 = Var(initialize=2)
        m.v3 = Var(initialize=3)
        m.c = Constraint(expr=m.v1 <= m.v2)
        m.c2 = Constraint(expr=m.v2 >= m.v3)
        m.c3 = Constraint(expr=m.v1 <= 5)
        m.v1.fix()

        xfrm = TransformationFactory('contrib.deactivate_trivial_constraints')
        xfrm.apply_to(m, tmp=True)
        self.assertTrue(m.c.active)
        self.assertTrue(m.c2.active)
        self.assertFalse(m.c3.active)

        xfrm.revert(m)
        self.assertTrue(m.c3.active)
Beispiel #44
0
    def test_disc_second_order_central(self):
        m = self.m.clone()
        m.dv1dt2 = DerivativeVar(m.v1, wrt=(m.t, m.t))
        disc = TransformationFactory('dae.finite_difference')
        disc.apply_to(m, nfe=2, scheme='CENTRAL')

        self.assertTrue(hasattr(m, 'dv1dt2_disc_eq'))
        self.assertEqual(len(m.dv1dt2_disc_eq), 1)
        self.assertEqual(len(m.v1), 3)

        output = \
"""\
dv1dt2_disc_eq : Size=1, Index=t, Active=True
    Key : Lower : Body                                            : Upper : Active
    5.0 :   0.0 : dv1dt2[5.0] - 0.04*(v1[10] - 2*v1[5.0] + v1[0]) :   0.0 :   True
"""
        out = StringIO()
        m.dv1dt2_disc_eq.pprint(ostream=out)
        self.assertEqual(output, out.getvalue())
Beispiel #45
0
    def test_disc_second_order_central(self):
        m = self.m.clone()
        m.dv1dt2 = DerivativeVar(m.v1, wrt=(m.t, m.t))
        disc = TransformationFactory('dae.finite_difference')
        disc.apply_to(m, nfe=2, scheme='CENTRAL')

        self.assertTrue(hasattr(m, 'dv1dt2_disc_eq'))
        self.assertTrue(len(m.dv1dt2_disc_eq) == 1)
        self.assertTrue(len(m.v1) == 3)

        output = \
"""\
dv1dt2_disc_eq : Size=1, Index=t, Active=True
    Key : Lower : Body                                            : Upper : Active
    5.0 :   0.0 : dv1dt2[5.0] - 0.04*(v1[10] - 2*v1[5.0] + v1[0]) :   0.0 :   True
"""
        out = StringIO()
        m.dv1dt2_disc_eq.pprint(ostream=out)
        self.assertEqual(output, out.getvalue())
Beispiel #46
0
    def test_lookup_radau_collocation_points(self):
        # Save initial flag value
        colloc_numpy_avail = pyomo.dae.plugins.colloc.numpy_available

        # Numpy flag must be False to test lookup
        pyomo.dae.plugins.colloc.numpy_available = False

        m = self.m.clone()
        disc = TransformationFactory('dae.collocation')
        disc.apply_to(m, nfe=5, ncp=3)

        self.assertTrue(hasattr(m, 'dv1_disc_eq'))
        self.assertTrue(len(m.dv1_disc_eq) == 15)
        self.assertTrue(len(m.v1) == 16)

        expected_tau_points = [
            0.0, 0.1550510257216822, 0.64494897427831788, 1.0
        ]
        expected_disc_points = [
            0, 0.310102, 1.289898, 2.0, 2.310102, 3.289898, 4.0, 4.310102,
            5.289898, 6.0, 6.310102, 7.289898, 8.0, 8.310102, 9.289898, 10
        ]
        disc_info = m.t.get_discretization_info()

        self.assertTrue(disc_info['scheme'] == 'LAGRANGE-RADAU')

        for idx, val in enumerate(disc_info['tau_points']):
            self.assertAlmostEqual(val, expected_tau_points[idx])

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

        m = self.m.clone()
        try:
            disc = TransformationFactory('dae.collocation')
            disc.apply_to(m, ncp=15, scheme='LAGRANGE-RADAU')
            self.fail('Expected ValueError')
        except ValueError:
            pass

        # Restore initial flag value
        pyomo.dae.plugins.colloc.numpy_available = colloc_numpy_avail
    def test_deactivate_trivial_constraints_revert(self):
        """Test for reversion of trivial constraint deactivation."""
        m = ConcreteModel()
        m.v1 = Var(initialize=1)
        m.v2 = Var(initialize=2)
        m.v3 = Var(initialize=3)
        m.c = Constraint(expr=m.v1 <= m.v2)
        m.c2 = Constraint(expr=m.v2 >= m.v3)
        m.c3 = Constraint(expr=m.v1 <= 5)
        m.v1.fix()

        xfrm = TransformationFactory(
            'contrib.deactivate_trivial_constraints')
        xfrm.apply_to(m, tmp=True)
        self.assertTrue(m.c.active)
        self.assertTrue(m.c2.active)
        self.assertFalse(m.c3.active)

        xfrm.revert(m)
        self.assertTrue(m.c3.active)
Beispiel #48
0
    def test_reduce_colloc_multi_index(self):
        m = self.m.clone()
        m.u = Var(m.t, m.s)

        m2 = m.clone()
        m3 = m.clone()

        disc = TransformationFactory('dae.collocation')
        disc.apply_to(m, nfe=5, ncp=3)
        disc.reduce_collocation_points(m, contset=m.t, var=m.u, ncp=1)

        self.assertTrue(hasattr(m, 'u_interpolation_constraints'))
        self.assertEqual(len(m.u_interpolation_constraints), 30)

        disc2 = TransformationFactory('dae.collocation')
        disc2.apply_to(m2, wrt=m2.t, nfe=5, ncp=3)
        disc2.reduce_collocation_points(m2, contset=m2.t, var=m2.u, ncp=3)

        self.assertFalse(hasattr(m2, 'u_interpolation_constraints'))

        disc3 = TransformationFactory('dae.collocation')
        disc3.apply_to(m3, wrt=m3.t, nfe=5, ncp=3)
        disc3.reduce_collocation_points(m3, contset=m3.t, var=m3.u, ncp=2)

        self.assertTrue(hasattr(m3, 'u_interpolation_constraints'))
        self.assertEqual(len(m3.u_interpolation_constraints), 15)
Beispiel #49
0
 def test_var_fix_revert(self):
     """Test to make sure that variable fixing reversion works."""
     m = ConcreteModel()
     m.v1 = Var(initialize=1)
     m.v2 = Var(initialize=2)
     m.v3 = Var(initialize=3)
     m.v4 = Var(initialize=4)
     m.c1 = Constraint(expr=m.v1 == m.v2)
     m.c2 = Constraint(expr=m.v2 == m.v3)
     m.c3 = Constraint(expr=m.v3 == m.v4)
     m.v2.fix()
     fvp = TransformationFactory('contrib.propagate_fixed_vars')
     fvp.apply_to(m, tmp=True)
     self.assertTrue(m.v1.fixed)
     self.assertTrue(m.v2.fixed)
     self.assertTrue(m.v3.fixed)
     self.assertTrue(m.v4.fixed)
     fvp.revert(m)
     self.assertFalse(m.v1.fixed)
     self.assertTrue(m.v2.fixed)
     self.assertFalse(m.v3.fixed)
     self.assertFalse(m.v4.fixed)
Beispiel #50
0
    def test_lookup_radau_collocation_points(self):
        # Save initial flag value
        colloc_numpy_avail = pyomo.dae.plugins.colloc.numpy_available

        # Numpy flag must be False to test lookup
        pyomo.dae.plugins.colloc.numpy_available = False

        m = self.m.clone()
        disc = TransformationFactory('dae.collocation')
        disc.apply_to(m, nfe=5, ncp=3)

        self.assertTrue(hasattr(m, 'dv1_disc_eq'))
        self.assertTrue(len(m.dv1_disc_eq) == 15)
        self.assertTrue(len(m.v1) == 16)

        expected_tau_points = [0.0, 0.1550510257216822,
                               0.64494897427831788,
                               1.0]
        expected_disc_points = [0, 0.310102, 1.289898, 2.0, 2.310102,
                                3.289898,
                                4.0, 4.310102, 5.289898, 6.0, 6.310102,
                                7.289898, 8.0, 8.310102, 9.289898, 10]
        disc_info = m.t.get_discretization_info()

        self.assertTrue(disc_info['scheme'] == 'LAGRANGE-RADAU')

        for idx, val in enumerate(disc_info['tau_points']):
            self.assertAlmostEqual(val, expected_tau_points[idx])

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

        m = self.m.clone()
        with self.assertRaises(ValueError):
            disc = TransformationFactory('dae.collocation')
            disc.apply_to(m, ncp=15, scheme='LAGRANGE-RADAU')

        # Restore initial flag value
        pyomo.dae.plugins.colloc.numpy_available = colloc_numpy_avail
Beispiel #51
0
    def test_lookup_legendre_collocation_points(self):
        # Save initial flag value
        colloc_numpy_avail = pyomo.dae.plugins.colloc.numpy_available

        # Numpy flag must be False to test lookup
        pyomo.dae.plugins.colloc.numpy_available = False

        m = self.m.clone()
        disc = TransformationFactory('dae.collocation')
        disc.apply_to(m, nfe=5, ncp=3, scheme='LAGRANGE-LEGENDRE')

        self.assertTrue(hasattr(m, 'dv1_disc_eq'))
        self.assertTrue(len(m.dv1_disc_eq) == 15)
        self.assertTrue(len(m.v1) == 21)

        expected_tau_points = [0.0, 0.11270166537925834, 0.49999999999999989,
                               0.88729833462074226]
        expected_disc_points = [0, 0.225403, 1.0, 1.774597, 2.0, 2.225403,
                                3.0, 3.774597, 4.0, 4.225403, 5.0, 5.774597,
                                6.0, 6.225403, 7.0, 7.774597, 8.0, 8.225403,
                                9.0, 9.774597, 10]

        disc_info = m.t.get_discretization_info()

        self.assertTrue(disc_info['scheme'] == 'LAGRANGE-LEGENDRE')

        for idx, val in enumerate(disc_info['tau_points']):
            self.assertAlmostEqual(val, expected_tau_points[idx])

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

        m = self.m.clone()
        with self.assertRaises(ValueError):
            disc = TransformationFactory('dae.collocation')
            disc.apply_to(m, ncp=15, scheme='LAGRANGE-LEGENDRE')

        # Restore initial flag value
        pyomo.dae.plugins.colloc.numpy_available = colloc_numpy_avail
Beispiel #52
0
    def test_disc_second_order_backward(self):
        m = self.m.clone()
        m.dv1dt2 = DerivativeVar(m.v1, wrt=(m.t, m.t))
        disc = TransformationFactory('dae.finite_difference')
        disc.apply_to(m, nfe=2)
         
        self.assertTrue(hasattr(m, 'dv1dt2_disc_eq'))
        self.assertTrue(len(m.dv1dt2_disc_eq) == 1)
        self.assertTrue(len(m.v1) == 3)

        self.assertTrue(hasattr(m, '_pyomo_dae_reclassified_derivativevars'))
        self.assertTrue(m.dv1 in m._pyomo_dae_reclassified_derivativevars)
        self.assertTrue(m.dv1dt2 in m._pyomo_dae_reclassified_derivativevars)

        output = \
"""\
dv1dt2_disc_eq : Size=1, Index=t, Active=True
    Key : Lower : Body                                           : Upper : Active
     10 :   0.0 : dv1dt2[10] - 0.04*(v1[10] - 2*v1[5.0] + v1[0]) :   0.0 :   True
"""
        out = StringIO()
        m.dv1dt2_disc_eq.pprint(ostream=out)
        self.assertEqual(output, out.getvalue())
Beispiel #53
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.finite_difference')
        disc.apply_to(m, nfe=2)

        self.assertTrue(hasattr(m, 'dv2dt_disc_eq'))
        self.assertTrue(hasattr(m, 'dv2dt2_disc_eq'))
        self.assertTrue(len(m.dv2dt_disc_eq) == 6)
        self.assertTrue(len(m.dv2dt2_disc_eq) == 6)
        self.assertTrue(len(m.v2) == 9)

        expected_t_disc_points = [0, 5.0, 10]
        expected_t2_disc_points = [0, 2.5, 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])
Beispiel #54
0
    def test_reduce_colloc_invalid(self):
        m = self.m.clone()
        m.u = Var(m.t)
        m2 = m.clone()

        disc = TransformationFactory('dae.collocation')
        disc2 = TransformationFactory('dae.collocation')
        disc.apply_to(m, nfe=5, ncp=3)

        # No ContinuousSet specified
        with self.assertRaises(TypeError):
            disc.reduce_collocation_points(m, contset=None)

        # Component passed in is not a ContinuousSet
        with self.assertRaises(TypeError):
            disc.reduce_collocation_points(m, contset=m.s)

        # Call reduce_collocation_points method before applying discretization
        with self.assertRaises(RuntimeError):
            disc2.reduce_collocation_points(m2, contset=m2.t)

        # Call reduce_collocation_points on a ContinuousSet that hasn't been
        #  discretized
        m2.tt = ContinuousSet(bounds=(0, 1))
        disc2.apply_to(m2, wrt=m2.t)
        with self.assertRaises(ValueError):
            disc2.reduce_collocation_points(m2, contset=m2.tt)

        # No Var specified
        with self.assertRaises(TypeError):
            disc.reduce_collocation_points(m, contset=m.t, var=None)

        # Component passed in is not a Var
        with self.assertRaises(TypeError):
            disc.reduce_collocation_points(m, contset=m.t, var=m.s)

        # New ncp not specified
        with self.assertRaises(TypeError):
            disc.reduce_collocation_points(m, contset=m.t, var=m.v1, ncp=None)

        # Negative ncp specified
        with self.assertRaises(ValueError):
            disc.reduce_collocation_points(m, contset=m.t, var=m.v1, ncp=-3)

        # Too large ncp specified
        with self.assertRaises(ValueError):
            disc.reduce_collocation_points(m, contset=m.t, var=m.v1, ncp=10)

        # Passing Vars not indexed by the ContinuousSet
        m.v2 = Var()
        m.v3 = Var(m.s)
        m.v4 = Var(m.s, m.s)

        with self.assertRaises(IndexError):
            disc.reduce_collocation_points(m, contset=m.t, var=m.v2, ncp=1)

        with self.assertRaises(IndexError):
            disc.reduce_collocation_points(m, contset=m.t, var=m.v3, ncp=1)

        with self.assertRaises(IndexError):
            disc.reduce_collocation_points(m, contset=m.t, var=m.v4, ncp=1)

        # Calling reduce_collocation_points more than once
        disc.reduce_collocation_points(m, contset=m.t, var=m.u, ncp=1)
        with self.assertRaises(RuntimeError):
            disc.reduce_collocation_points(m, contset=m.t, var=m.u, ncp=1)