예제 #1
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)
예제 #2
0
파일: models.py 프로젝트: nadia-el/lms2
    def construct_objective_from_expression_list(self, wrt, *args):
        """
        Construct objective from list of expression to be integrated with respect to wrt.

        :param str name: name of the new integral expression (optional)
        :param wrt: Set for the integration of the expressions
        :param args: Expression of instantaneous objectives
        :return: Objective
        """
        from pyomo.environ import Expression
        from pyomo.dae import Integral
        for exp in args:
            assert isinstance(exp, Expression), ValueError(f'args should be a list of pyomo Expression,'
                                                           f' and actually received {exp, type(exp)}')

        self.new_int = Integral(wrt, wrt=wrt, rule=lambda model, index: sum([a[index] for a in args]))

        return Objective(expr=self.new_int)
예제 #3
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)

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

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

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

        # Integrals must be indexed by a ContinuousSet
        with self.assertRaises(ValueError):
            m.int = Integral(rule=_int)

        # Specifying multiple aliases of same option
        with self.assertRaises(TypeError):
            m.int = Integral(m.t, wrt=m.t, withrespectto=m.t, rule=_int)

        # No ContinuousSet specified
        with self.assertRaises(ValueError):
            m.int2 = Integral(m.x, m.t, rule=_int2)

        # 'wrt' is not a ContinuousSet
        with self.assertRaises(ValueError):
            m.int = Integral(m.s, m.t, wrt=m.s, rule=_int2)

        # 'wrt' is not in argument list
        with self.assertRaises(ValueError):
            m.int = Integral(m.t, wrt=m.x, rule=_int)

        # 'bounds' not supported
        with self.assertRaises(DAE_Error):
            m.int = Integral(m.t, wrt=m.t, rule=_int, bounds=(0, 0.5))

        # No rule specified
        with self.assertRaises(ValueError):
            m.int = Integral(m.t, wrt=m.t)
예제 #4
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)

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

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

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

        # Integrals must be indexed by a ContinuousSet
        with self.assertRaises(ValueError):
            m.int = Integral(rule=_int)

        # Specifying multiple aliases of same option
        with self.assertRaises(TypeError):
            m.int = Integral(m.t, wrt=m.t, withrespectto=m.t, rule=_int)

        # No ContinuousSet specified
        with self.assertRaises(ValueError):
            m.int2 = Integral(m.x, m.t, rule=_int2)

        # 'wrt' is not a ContinuousSet
        with self.assertRaises(ValueError):
            m.int = Integral(m.s, m.t, wrt=m.s, rule=_int2)

        # 'wrt' is not in argument list
        with self.assertRaises(ValueError):
            m.int = Integral(m.t, wrt=m.x, rule=_int)

        # 'bounds' not supported
        with self.assertRaises(DAE_Error):
            m.int = Integral(m.t, wrt=m.t, rule=_int, bounds=(0, 0.5))

        # No rule specified
        with self.assertRaises(ValueError):
            m.int = Integral(m.t, wrt=m.t)

            # test DerivativeVar reclassification after discretization

        def test_reclassification_finite_difference(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.finite_difference').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.finite_difference').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)
예제 #5
0
    def test_valid(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.assertTrue(isinstance(m.int1, Expression))
        self.assertTrue(isinstance(m.int2, Expression))
        self.assertTrue(isinstance(m.int3, Expression))
        self.assertTrue(isinstance(m.int4, Expression))
        self.assertTrue(m.int1.get_continuousset() is m.t)
        self.assertTrue(m.int2.get_continuousset() is m.t)
        self.assertTrue(m.int3.get_continuousset() is m.t)
        self.assertTrue(m.int4.get_continuousset() is m.x)
        self.assertEqual(len(m.int1), 1)
        self.assertEqual(len(m.int2), 3)
        self.assertEqual(len(m.int3), 2)
        self.assertEqual(len(m.int4), 1)
        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)

        repn = generate_standard_repn(m.int1.expr)
        self.assertEqual(repn.linear_coefs, (0.5, 0.5))
        self.assertTrue(repn.linear_vars[0] is m.v[1])
        self.assertTrue(repn.linear_vars[1] is m.v[0])

        repn = generate_standard_repn(m.int2[1].expr)
        self.assertEqual(repn.linear_coefs, (0.5, 0.5))
        self.assertTrue(repn.linear_vars[0] is m.v2[1, 1])
        self.assertTrue(repn.linear_vars[1] is m.v2[1, 0])

        repn = generate_standard_repn(m.int4.expr)
        self.assertEqual(repn.linear_coefs, (1.25, 1.25, 1.25, 1.25))
        self.assertTrue(repn.linear_vars[0] is m.v3[1, 10])
        self.assertTrue(repn.linear_vars[1] is m.v3[0, 10])
        self.assertTrue(repn.linear_vars[2] is m.v3[1, 5])
        self.assertTrue(repn.linear_vars[3] is m.v3[0, 5])
예제 #6
0
    def test_battery_v0(self):
        from lms2 import BatteryV0, PowerLoad, FixedPowerLoad, AbsLModel
        from pyomo.environ import TransformationFactory, SolverFactory
        from pyomo.dae import ContinuousSet
        from pyomo.network import Arc

        m = AbsLModel()
        m.time = ContinuousSet()
        m.b = BatteryV0()
        m.pl = FixedPowerLoad()
        m.ps = PowerLoad()
        m.arc1 = Arc(source=m.b.outlet, dest=m.pl.inlet)
        m.arc2 = Arc(source=m.b.outlet, dest=m.ps.inlet)

        data_batt = dict(
            time={None: [0, 10]},
            dpcmax={None: 100000},
            dpdmax={None: 100000},
            emin={None: 0},
            emax={None: 500},
            pcmax={None: 80},
            pdmax={None: 80},
            e0={None: 50},
            ef={None: None},
            etac={None: 1.0},
            etad={None: 1.0})

        data_pl = {
            'time': {None: [0, 10]},
            'profile_index': {None: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]},
            'profile_value': dict(zip([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10], [10, 0, -10, -90, -20, 20, 30, 40, 40, 10]))
        }

        data_ps = {
            'time': {None: (0, 10)}
        }

        data = \
            {None:
                {
                    'time': {None: [0, 10]},
                    'b': data_batt,
                    'pl': data_pl,
                    'ps': data_ps
                }
            }

        inst = m.create_instance(data)

        from lms2.economic.cost import def_absolute_cost
        from pyomo.environ import Objective
        from pyomo.dae import Integral

        inst.ps.instant_cost = def_absolute_cost(inst.ps, var_name='p')
        inst.new_int = Integral(inst.time, wrt=inst.time, rule=lambda b, t: b.ps.instant_cost[t])

        TransformationFactory('dae.finite_difference').apply_to(inst, nfe=5)
        TransformationFactory("network.expand_arcs").apply_to(inst)

        inst.obj = Objective(expr=inst.new_int)

        opt = SolverFactory("glpk")

        from time import time

        t1 = time()
        results = opt.solve(inst, tee=False)
        print(f'Solve time : {time() - t1:0.4f} s')

        from pyomo.opt import SolverStatus, TerminationCondition
        self.assertTrue(results.solver.status == SolverStatus.ok)
        self.assertTrue(results.solver.termination_condition == TerminationCondition.optimal)
예제 #7
0
    def test_battery_v3(self):
        from lms2 import BatteryV3, FixedPowerLoad, AbsLModel, PVPanels, DebugSource, MainGridV1
        from lms2.economic.cost import def_absolute_cost

        from pyomo.environ import TransformationFactory, SolverFactory
        from pyomo.dae import ContinuousSet
        from pyomo.network import Arc

        import numpy as np
        import pandas as pd

        m = AbsLModel()
        m.time = ContinuousSet(initialize=(0, 10))
        m.b = BatteryV3(method='piecewise')
        m.pl = FixedPowerLoad()
        m.debug = DebugSource()
        m.mg = MainGridV1()
        m.ps = PVPanels(curtailable=True)
        m.arc1 = Arc(source=m.b.outlet, dest=m.pl.inlet)
        m.arc2 = Arc(source=m.ps.outlet, dest=m.pl.inlet)
        m.arc3 = Arc(source=m.debug.outlet, dest=m.pl.inlet)
        m.arc4 = Arc(source=m.mg.outlet, dest=m.pl.inlet)

        m.b.inst_cost = def_absolute_cost(m.b, var_name='dp')

        t = pd.timedelta_range(start=0, end='2 days',
                               freq='30Min').total_seconds()
        ps = [(-np.cos(2 * np.pi * i / (86400)) + 1)**6 / 2**6 *
              (0.2 * np.sin(2 * np.pi * i / (86400 * 7)) + 0.4) * 10
              for i in t]
        pl = np.array([5] * len(t))
        time = (t[0], 86400 * 2)
        nfe = 24 * 2 * 60 / 30

        data_batt = dict(
            time={None: time},
            dpcmax={None: 100},
            dpdmax={None: 100},
            socmin={None: 40},
            socmax={None: 100},
            soc0={None: 50},
            socf={None: 50},  # final soc
            socabs={None: 85},  # absorption soc
            emin={None: 40},
            emax={None: 100},
            pcmax={None: 20},
            pdmax={None: 20},
            etac={None: 0.90},
            etad={None: 0.90},
            pw_i={None: [1, 2, 3]},
            pw_j={None: [1, 2]},
            pw_soc={
                1: 40,
                2: 85,
                3: 100
            },
            pw_pcmax={
                1: 20,
                2: 20,
                3: 1
            },
            pfloat={None: 0.125},
            max_cycles={None: 10},
            cycle_passed={None: 8},
            dp_cost={None: 0})

        data_mg = {
            'time': {
                None: time
            },
            'cost_out': {
                None: 0.15
            },
            'cost_in': {
                None: 0
            },
            'pmax': {
                None: 30
            },
            'pmin': {
                None: 0
            }
        }

        data_pl = {
            'time': {
                None: time
            },
            'profile_index': {
                None: t
            },
            'profile_value': dict(zip(t, pl))
        }

        data_ps = {
            'time': {
                None: time
            },
            'profile_index': {
                None: t
            },
            'profile_value': dict(zip(t, ps))
        }

        data_debug = {'time': {None: time}, 'p_cost': {None: 10}}

        data = {
            None:
            dict(time={None: time},
                 b=data_batt,
                 mg=data_mg,
                 ps=data_ps,
                 debug=data_debug,
                 pl=data_pl)
        }

        inst = m.create_instance(data)
        inst.ps.surf.fix(4)

        from lms2.economic.cost import def_absolute_cost
        from pyomo.environ import Objective
        from pyomo.dae import Integral
        from pyomo.opt import SolverStatus, TerminationCondition

        TransformationFactory('dae.finite_difference').apply_to(inst, nfe=nfe)
        TransformationFactory("network.expand_arcs").apply_to(inst)

        inst.ps.instant_cost = def_absolute_cost(inst.ps, var_name='p')
        inst.new_int = Integral(inst.time,
                                wrt=inst.time,
                                rule=lambda b, t: b.debug.inst_cost[t] + b.b.
                                inst_cost[t] + b.mg.instant_cost[t])

        inst.b._nbr_charge.reconstruct()
        inst.obj = Objective(expr=inst.new_int)

        opt = SolverFactory("gurobi", solver_io="direct")

        results = opt.solve(inst, tee=False)

        self.assertTrue(results.solver.status == SolverStatus.ok)
        self.assertTrue(results.solver.termination_condition ==
                        TerminationCondition.optimal)
        self.assertAlmostEqual(7.8386091, inst.obj(), places=5)