Пример #1
0
def setup_mccormick_cuts(b, name, nsegs, *sets):
    print(
        'Warning: setup_mccormick_cuts is now deprecated in favor of the util.mccormick.add_mccormick_relaxation function, which automatically performs setup.'
    )
    cuts = b.mccormick_cuts = Set(initialize=['lb1', 'lb2', 'ub1', 'ub2'])
    sets_cuts = sets + (cuts, )
    setattr(b, name, Constraint(*sets_cuts))
    if nsegs > 1:
        # If we are doing piecewise McCormick, set up additional constraints and variables.
        b.seg_length = Param(*sets, mutable=True)
        segs = b.segs = RangeSet(nsegs)
        sets_segs = sets + (segs, )
        b.seg_active = Var(*sets_segs, domain=Binary)
        b.delta_y = Var(*sets_segs, domain=NonNegativeReals)
        b.eq_seg_active_sum = Constraint(*sets)
        b.eq_y = Constraint(*sets)
        b.eq_dy_ub = Constraint(*sets)
        b.eq_x_lb = Constraint(*sets)
        b.eq_x_ub = Constraint(*sets)
Пример #2
0
    def test_polynomial_degree(self):
        pipe = ConcreteModel()
        pipe.SPECIES = Set(initialize=['a', 'b', 'c'])
        pipe.flow = Var()
        pipe.composition = Var(pipe.SPECIES)
        pipe.pIn = Var(within=NonNegativeReals)

        pipe.OUT = Connector()
        self.assertEqual(pipe.OUT.polynomial_degree(), 0)

        pipe.OUT.add(pipe.flow, "flow")
        self.assertEqual(pipe.OUT.polynomial_degree(), 1)

        pipe.flow.fix(0)
        self.assertEqual(pipe.OUT.polynomial_degree(), 0)

        pipe.OUT.add(-pipe.pIn, "pressure")
        self.assertEqual(pipe.OUT.polynomial_degree(), 1)

        pipe.pIn.fix(1)
        self.assertEqual(pipe.OUT.polynomial_degree(), 0)

        pipe.OUT.add(pipe.composition, "composition")
        self.assertEqual(pipe.OUT.polynomial_degree(), 1)

        pipe.composition['a'].fix(1)
        self.assertEqual(pipe.OUT.polynomial_degree(), 1)

        pipe.composition['b'].fix(1)
        pipe.composition['c'].fix(1)
        self.assertEqual(pipe.OUT.polynomial_degree(), 0)

        pipe.OUT.add(pipe.flow * pipe.pIn, "quadratic")
        self.assertEqual(pipe.OUT.polynomial_degree(), 0)

        pipe.flow.unfix()
        self.assertEqual(pipe.OUT.polynomial_degree(), 1)

        pipe.pIn.unfix()
        self.assertEqual(pipe.OUT.polynomial_degree(), 2)

        pipe.OUT.add(pipe.flow / pipe.pIn, "nonLin")
        self.assertEqual(pipe.OUT.polynomial_degree(), None)
Пример #3
0
    def test_Expression_component(self):
        m = ConcreteModel()
        m.s = Set(initialize=['A', 'B'])
        m.x = Var(m.s, domain=NonNegativeReals)

        def y_rule(m, s):
            return m.x[s] * 2

        m.y = Expression(m.s, rule=y_rule)

        expr = 1 - m.y['A']**2
        jacs = differentiate(expr, wrt_list=[m.x['A'], m.x['B']])
        self.assertEqual(str(jacs[0]), "-8.0*x[A]")
        self.assertEqual(str(jacs[1]), "0.0")

        expr = 1 - m.y['B']**2
        jacs = differentiate(expr, wrt_list=[m.x['A'], m.x['B']])
        self.assertEqual(str(jacs[0]), "0.0")
        self.assertEqual(str(jacs[1]), "-8.0*x[B]")
Пример #4
0
    def test_update_contset_indexed_component_vars_single(self):
        m = ConcreteModel()
        m.t = ContinuousSet(bounds=(0, 10))
        m.t2 = ContinuousSet(initialize=[1, 2, 3])
        m.s = Set(initialize=[1, 2, 3])
        m.v1 = Var(m.t, initialize=3)
        m.v2 = Var(m.t, bounds=(4, 10), initialize={0: 2, 10: 12})

        def _init(m, i):
            return i

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

        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) == 6)
        self.assertTrue(len(m.v2) == 6)
        self.assertTrue(len(m.v3) == 6)
        self.assertTrue(len(m.v4) == 3)
        self.assertTrue(len(m.v5) == 3)

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

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

        self.assertTrue(value(m.v3[2]) == 2)
        self.assertTrue(m.v3[4].lb == -5)
        self.assertTrue(m.v3[6].ub == 5)
        self.assertTrue(value(m.v3[8]) == 8)
Пример #5
0
    def test_display(self):
        pipe = ConcreteModel()
        pipe.SPECIES = Set(initialize=['a', 'b', 'c'])
        pipe.flow = Var(initialize=10)
        pipe.composition = Var(pipe.SPECIES,
                               initialize=lambda m, i: ord(i) - ord('a'))
        pipe.pIn = Var(within=NonNegativeReals, initialize=3.14)

        pipe.OUT = Port(implicit=['imp'])
        pipe.OUT.add(-pipe.flow, "flow")
        pipe.OUT.add(pipe.composition, "composition")
        pipe.OUT.add(pipe.pIn, "pressure")

        os = StringIO()
        pipe.OUT.display(ostream=os)
        self.assertEqual(
            os.getvalue(), """OUT : Size=1
    Key  : Name        : Value
    None : composition : {'a': 0, 'b': 1, 'c': 2}
         :        flow : -10
         :         imp : -
         :    pressure : 3.14
""")

        def _IN(m, i):
            return {
                'pressure': pipe.pIn,
                'flow': pipe.composition[i] * pipe.flow
            }

        pipe.IN = Port(pipe.SPECIES, rule=_IN)
        os = StringIO()
        pipe.IN.display(ostream=os)
        self.assertEqual(
            os.getvalue(), """IN : Size=3
    Key : Name     : Value
      a :     flow :     0
        : pressure :  3.14
      b :     flow :    10
        : pressure :  3.14
      c :     flow :    20
        : pressure :  3.14
""")
Пример #6
0
    def test_pprint(self):
        pipe = ConcreteModel()
        pipe.SPECIES = Set(initialize=['a', 'b', 'c'])
        pipe.flow = Var()
        pipe.composition = Var(pipe.SPECIES)
        pipe.pIn = Var(within=NonNegativeReals)

        pipe.OUT = Connector()
        pipe.OUT.add(-pipe.flow, "flow")
        pipe.OUT.add(pipe.composition, "composition")
        pipe.OUT.add(pipe.composition['a'], "comp_a")
        pipe.OUT.add(pipe.pIn, "pressure")

        os = StringIO()
        pipe.OUT.pprint(ostream=os)
        self.assertEqual(
            os.getvalue(), """OUT : Size=1, Index=None
    Key  : Name        : Size : Variable
    None :      comp_a :    1 : composition[a]
         : composition :    3 : composition
         :        flow :    1 : - flow
         :    pressure :    1 : pIn
""")

        def _IN(m, i):
            return {
                'pressure': pipe.pIn,
                'flow': pipe.composition[i] * pipe.flow
            }

        pipe.IN = Connector(pipe.SPECIES, rule=_IN)
        os = StringIO()
        pipe.IN.pprint(ostream=os)
        self.assertEqual(
            os.getvalue(), """IN : Size=3, Index=SPECIES
    Key : Name     : Size : Variable
      a :     flow :    1 : composition[a]*flow
        : pressure :    1 :                 pIn
      b :     flow :    1 : composition[b]*flow
        : pressure :    1 :                 pIn
      c :     flow :    1 : composition[c]*flow
        : pressure :    1 :                 pIn
""")
Пример #7
0
    def test_simple_lookup(self):
        m = self.m

        self._lookupTester(m.b[:, :].x[:, :], (1, 5, 7, 10), m.b[1, 5].x[7,
                                                                         10])
        self._lookupTester(m.b[:, 4].x[8, :], (1, 10), m.b[1, 4].x[8, 10])
        self._lookupTester(m.b[:, 4].x[8, 10], (1, ), m.b[1, 4].x[8, 10])
        self._lookupTester(m.b[1, 4].x[8, :], (10, ), m.b[1, 4].x[8, 10])

        self._lookupTester(m.b[:, :].y[:], (1, 5, 7), m.b[1, 5].y[7])
        self._lookupTester(m.b[:, 4].y[:], (1, 7), m.b[1, 4].y[7])
        self._lookupTester(m.b[:, 4].y[8], (1, ), m.b[1, 4].y[8])

        self._lookupTester(m.b[:, :].z, (1, 5), m.b[1, 5].z)
        self._lookupTester(m.b[:, 4].z, (1, ), m.b[1, 4].z)

        self._lookupTester(m.c[:].x[:, :], (1, 7, 10), m.c[1].x[7, 10])
        self._lookupTester(m.c[:].x[8, :], (1, 10), m.c[1].x[8, 10])
        self._lookupTester(m.c[:].x[8, 10], (1, ), m.c[1].x[8, 10])
        self._lookupTester(m.c[1].x[:, :], (8, 10), m.c[1].x[8, 10])
        self._lookupTester(m.c[1].x[8, :], (10, ), m.c[1].x[8, 10])

        self._lookupTester(m.c[:].y[:], (1, 7), m.c[1].y[7])
        self._lookupTester(m.c[:].y[8], (1, ), m.c[1].y[8])
        self._lookupTester(m.c[1].y[:], (8, ), m.c[1].y[8])

        self._lookupTester(m.c[:].z, (1, ), m.c[1].z)

        m.jagged_set = Set(initialize=[1, (2, 3)], dimen=None)
        m.jb = Block(m.jagged_set)
        m.jb[1].x = Var([1, 2, 3])
        m.jb[2, 3].x = Var([1, 2, 3])
        self._lookupTester(m.jb[...], (1, ), m.jb[1])
        self._lookupTester(m.jb[...].x[:], (1, 2), m.jb[1].x[2])
        self._lookupTester(m.jb[...].x[:], (2, 3, 2), m.jb[2, 3].x[2])

        rd = _ReferenceDict(m.jb[:, :, :].x[:])
        with self.assertRaises(KeyError):
            rd[2, 3, 4, 2]
        rd = _ReferenceDict(m.b[:, 4].x[:])
        with self.assertRaises(KeyError):
            rd[1, 0]
Пример #8
0
    def test_multidim_nested_getattr_sum_rule(self):
        m = ConcreteModel()
        m.I = RangeSet(3)
        m.J = RangeSet(3)
        m.JI = m.J*m.I
        m.K = Set(m.I, initialize={1:[10], 2:[10,20], 3:[10,20,30]})
        m.x = Var(m.I,m.J,[10,20,30])
        @m.Block(m.I)
        def b(b, i):
            b.K = RangeSet(10, 10*i, 10)
        @m.Constraint()
        def c(m):
            return sum( sum(m.x[i,j,k] for k in m.b[i].K)
                        for j,i in m.JI) <= 0

        template, indices = templatize_constraint(m.c)
        self.assertEqual(len(indices), 0)
        self.assertEqual(
            template.to_string(verbose=True),
            "templatesum("
            "templatesum(getitem(x, _2, _1, _3), "
            "iter(_3, getattr(getitem(b, _2), 'K'))), "
            "iter(_1, _2, JI))  <=  0.0"
        )
        self.assertEqual(
            str(template),
            "SUM(SUM(x[_2,_1,_3] for _3 in b[_2].K) "
            "for _1, _2 in JI)  <=  0.0"
        )
        # Evaluate the template
        self.assertEqual(
            str(resolve_template(template)),
            'x[1,1,10] + '
            '(x[2,1,10] + x[2,1,20]) + '
            '(x[3,1,10] + x[3,1,20] + x[3,1,30]) + '
            '(x[1,2,10]) + '
            '(x[2,2,10] + x[2,2,20]) + '
            '(x[3,2,10] + x[3,2,20] + x[3,2,30]) + '
            '(x[1,3,10]) + '
            '(x[2,3,10] + x[2,3,20]) + '
            '(x[3,3,10] + x[3,3,20] + x[3,3,30])  <=  0.0'
        )
Пример #9
0
def add_model_components(m, d, scenario_directory, subproblem, stage):
    """
    The following Pyomo model components are defined in this module:

    +-------------------------------------------------------------------------+
    | Sets                                                                    |
    +=========================================================================+
    | | :code:`TX_AVL_EXOG_MNTH`                                              |
    |                                                                         |
    | The set of transmission lines of the :code:`exogenous_monthly`          |
    | availability type.                                                      |
    +-------------------------------------------------------------------------+

    |

    +-------------------------------------------------------------------------+
    | Optional Input Params                                                   |
    +=========================================================================+
    | | :code:`tx_avl_exog_mnth_derate`                                       |
    | | *Defined over*: :code:`TX_AVL_EXOG_MNTH_OPR_TMPS`                     |
    | | *Within*: :code:`NonNegativeReals`                                    |
    | | *Default*: :code:`1`                                                  |
    |                                                                         |
    | The pre-specified availability derate (e.g. for maintenance/planned     |
    | outages). Defaults to 1 if not specified. Availaibility can also be     |
    | more than 1.                                                            |
    +-------------------------------------------------------------------------+

    """

    # Sets
    ###########################################################################

    m.TX_AVL_EXOG_MNTH = Set(within=m.TX_LINES)

    # Required Params
    ###########################################################################

    m.tx_avl_exog_mnth_derate = Param(m.TX_AVL_EXOG_MNTH,
                                      m.MONTHS,
                                      within=NonNegativeReals,
                                      default=1)
Пример #10
0
 def test_indexed_construct_expr(self):
     model = ConcreteModel()
     model.Index = Set(initialize=[1,2,3])
     model.E = Expression(model.Index,
                          expr=Expression.Skip)
     self.assertEqual(len(model.E), 0)
     model.E = Expression(model.Index)
     self.assertEqual(model.E.extract_values(),
                      {1:None, 2:None, 3:None})
     model.del_component(model.E)
     model.E = Expression(model.Index, expr=1.0)
     self.assertEqual(model.E.extract_values(),
                      {1:1.0, 2:1.0, 3:1.0})
     model.del_component(model.E)
     model.E = Expression(model.Index,
                          expr={1: Expression.Skip,
                                2: Expression.Skip,
                                3: 1.0})
     self.assertEqual(model.E.extract_values(),
                      {3: 1.0})
Пример #11
0
    def m(self):
        m = ConcreteModel()

        m.meta_object = PropertyClassMetadata()
        m.meta_object.add_default_units({
            'time': pyunits.s,
            'length': pyunits.m,
            'mass': pyunits.kg,
            'amount': pyunits.mol,
            'temperature': pyunits.K})

        def get_metadata(self):
            return m.meta_object
        m.get_metadata = types.MethodType(get_metadata, m)

        m.cation_set = Set()

        m.comp = Cation(default={"charge": +1, "_electrolyte": True})

        return m
Пример #12
0
    def populate_block(self, block, additional_options=None):
        """
        Method to populate a Pyomo Block with surrogate model constraints.

        Args:
            block: Pyomo Block component to be populated with constraints.
            additional_options: None
               No additional options are required for this surrogate object
        Returns:
            None
        """

        # TODO: do we need to add the index_set stuff back in?
        output_set = Set(initialize=self._output_labels, ordered=True)
        def alamo_rule(b, o):
            lvars = block.input_vars_as_dict()
            lvars.update(block.output_vars_as_dict())
            return eval(self._surrogate_expressions[o], GLOBAL_FUNCS, lvars)

        block.alamo_constraint = Constraint(output_set, rule=alamo_rule)
Пример #13
0
def setup_multiparametric_disagg(b, name, minPow, maxPow, *sets):
    setattr(b, name, Constraint(*sets))
    digits = b.digits = RangeSet(0, 9)
    powers = b.powers = RangeSet(minPow, maxPow)
    b.minPow = Param(initialize=minPow)
    b.maxPow = Param(initialize=maxPow)
    skl = sets + (digits, powers)
    sl = sets + (powers, )
    b.y_hat = Var(*skl, domain=Reals)
    b.w_slack = Var(*sets, domain=Reals)
    b.dig_active = Var(*skl, domain=Binary)
    b.x_slack = Var(*sets, domain=NonNegativeReals)
    b.eq_x = Constraint(*sets)
    b.eq_y = Constraint(*sl)
    b.eq_y_hat_lb = Constraint(*skl)
    b.eq_y_hat_ub = Constraint(*skl)
    b.eq_z_sum = Constraint(*sl)
    mc = b.w_slack_mc = Set(initialize=['lb1', 'lb2', 'ub1', 'ub2'])
    sets_mc = sets + (mc, )
    b.eq_w_slack = Constraint(*sets_mc)
Пример #14
0
 def test_pickle2(self):
     model = AbstractModel()
     model.A = Set(initialize=[1, 2, 3])
     model.B = Param(model.A,
                     initialize={
                         1: 100,
                         2: 200,
                         3: 300
                     },
                     mutable=True)
     model.x = Var(model.A)
     model.y = Var(model.A)
     model.obj = Objective(rule=obj_rule)
     model.constr = Constraint(model.A, rule=constr_rule)
     tmp = model.create_instance()
     pickle_str = pickle.dumps(tmp)
     instance = pickle.loads(pickle_str)
     expr = sum_product(instance.x, instance.B, instance.y)
     baseline = "B[1]*x[1]*y[1] + B[2]*x[2]*y[2] + B[3]*x[3]*y[3]"
     self.assertEqual(str(expr), baseline)
Пример #15
0
    def test_io(self):
        model = AbstractModel()
        model.c1 = BuildCheck(rule=lambda M: True)
        model.A = Set(initialize=[1,2,3])
        model.c2 = BuildCheck(model.A, rule=lambda M,i: True)
        instance = model.create_instance()
        #
        buf = StringIO()
        instance.pprint(ostream=buf)
        self.assertEqual(buf.getvalue(),"""1 Set Declarations
    A : Size=1, Index=None, Ordered=Insertion
        Key  : Dimen : Domain : Size : Members
        None :     1 :    Any :    3 : {1, 2, 3}

2 BuildCheck Declarations
    c1 : 
    c2 : 

3 Declarations: c1 A c2
""")
Пример #16
0
def new_scenario_tree_model():
    # https://software.sandia.gov/trac/coopr/browser/coopr.pysp/trunk/coopr/pysp/util/scenariomodels.py
    scenario_tree_model = AbstractModel()

    # all set/parameter values are strings, representing the names of various
    # entities/variables.

    scenario_tree_model.Stages = Set(ordered=True)
    scenario_tree_model.Nodes = Set()

    scenario_tree_model.NodeStage = Param(scenario_tree_model.Nodes,
                                          within=scenario_tree_model.Stages)
    scenario_tree_model.Children = Set(scenario_tree_model.Nodes,
                                       within=scenario_tree_model.Nodes,
                                       ordered=True)
    scenario_tree_model.ConditionalProbability = Param(
        scenario_tree_model.Nodes)

    scenario_tree_model.Scenarios = Set(ordered=True)
    scenario_tree_model.ScenarioLeafNode = Param(
        scenario_tree_model.Scenarios, within=scenario_tree_model.Nodes)

    scenario_tree_model.StageVariables = Set(scenario_tree_model.Stages)
    scenario_tree_model.StageCostVariable = Param(scenario_tree_model.Stages)

    # scenario data can be populated in one of two ways. the first is "scenario-based",
    # in which a single .dat file contains all of the data for each scenario. the .dat
    # file prefix must correspond to the scenario name. the second is "node-based",
    # in which a single .dat file contains only the data for each node in the scenario
    # tree. the node-based method is more compact, but the scenario-based method is
    # often more natural when parameter data is generated via simulation. the default
    # is scenario-based.
    scenario_tree_model.ScenarioBasedData = Param(within=Boolean,
                                                  default=True,
                                                  mutable=True)

    # do we bundle, and if so, how?
    scenario_tree_model.Bundling = Param(within=Boolean,
                                         default=False,
                                         mutable=True)
    scenario_tree_model.Bundles = Set()  # bundle names
    scenario_tree_model.BundleScenarios = Set(scenario_tree_model.Bundles)

    return scenario_tree_model
Пример #17
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.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(hasattr(m, 'dv3_disc_eq'))
        self.assertTrue(len(m.dv2_disc_eq) == 45)
        self.assertTrue(len(m.v2) == 48)
        self.assertTrue(len(m.dv3_disc_eq) == 45)
        self.assertTrue(len(m.v3) == 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)
        self.assertTrue(m.dv3 in m._pyomo_dae_reclassified_derivativevars)
Пример #18
0
    def __init__(self, *args, flow_name='p', **kwds):

        from lms2 import fix_profile
        from pyomo.core import Binary
        from pyomo.environ import Param, Var, Set

        super().__init__(*args, flow_name=flow_name, **kwds)

        def _bound_u(m, t):
            if m.window.bounds()[0] <= t <= m.window.bounds()[-1]:
                return 0, 1
            else:
                return 0, 0

        fix_profile(self,
                    flow_name='pp',
                    profile_name='profile_value',
                    index_name='profile_index')

        self.w1 = Param()
        self.w2 = Param()
        self.window = Set(doc='time window where load can be turned ON.')

        self.u = Var(
            self.time,
            bounds=_bound_u,
            within=Binary,
            doc='binary, equals to 1 when the load is turned ON, 0 otherwise.')

        @self.Constraint(doc='the load is turned on only once')
        def _turned_on(m):
            return sum([m.u[t] for t in m.time]) == 1

        @self.Constraint(
            self.time,
            doc='the load is contraint to be off outside the time range')
        def _bound_p(m, t):
            if m.window.bounds()[0] <= t <= m.window.bounds()[-1]:
                return Constraint.Skip
            else:
                return 0, m.p[t], 0
Пример #19
0
    def test_rule(self):
        def rule1(model):
            return Constraint.Skip

        model = ConcreteModel()
        try:
            model.o = Constraint(rule=rule1)
        except Exception:
            e = sys.exc_info()[1]
            self.fail("Failure to create empty constraint: %s" % str(e))
        #
        def rule1(model):
            return (0.0, model.x, 2.0)

        model = ConcreteModel()
        model.x = Var(initialize=1.1)
        model.o = Constraint(rule=rule1)

        self.assertEqual(model.o(), 1.1)

        #
        def rule1(model, i):
            return Constraint.Skip

        model = ConcreteModel()
        model.a = Set(initialize=[1, 2, 3])
        try:
            model.o = Constraint(model.a, rule=rule1)
        except Exception:
            self.fail("Error generating empty constraint")

        #
        def rule1(model):
            return (0.0, 1.1, 2.0, None)

        model = ConcreteModel()
        try:
            model.o = Constraint(rule=rule1)
            self.fail("Can only return tuples of length 2 or 3")
        except ValueError:
            pass
Пример #20
0
    def test_config_validation_time(self, model):
        # Test validation of time argument
        model.test_set = Set(initialize=[0, 1, 2])
        model.test_contset = ContinuousSet(bounds=[0, 1])

        model.fs.config.time = model.test_set
        assert model.fs.config.time == model.test_set

        model.fs.config.time = model.test_contset
        assert model.fs.config.time == model.test_contset

        with pytest.raises(ValueError):
            model.fs.config.time = "foo"
        with pytest.raises(ValueError):
            model.fs.config.time = 1
        with pytest.raises(ValueError):
            model.fs.config.time = 2.0
        with pytest.raises(ValueError):
            model.fs.config.time = [1]
        with pytest.raises(ValueError):
            model.fs.config.time = {"foo": 1}
Пример #21
0
    def m(self):
        m = ConcreteModel()

        m.meta_object = PropertyClassMetadata()
        m.meta_object.add_default_units({
            'time': pyunits.s,
            'length': pyunits.m,
            'mass': pyunits.kg,
            'amount': pyunits.mol,
            'temperature': pyunits.K})

        def get_metadata(self):
            return m.meta_object
        m.get_metadata = types.MethodType(get_metadata, m)

        m._apparent_set = Set()

        m.comp = Apparent(default={"dissociation_species": {"comp": 1},
                                   "_electrolyte": True})

        return m
Пример #22
0
 def test_expr5(self):
     model = ConcreteModel()
     model.A = Set(initialize=[1,2,3], doc='set A')
     model.B = Param(model.A, initialize={1:100,2:200,3:300}, doc='param B', mutable=True)
     model.C = Param(initialize=3, doc='param C', mutable=True)
     model.x = Var(model.A, doc='var x')
     model.y = Var(doc='var y')
     model.o = Objective(expr=model.y, doc='obj o')
     model.c1 = Constraint(expr=model.x[1] >= 0, doc='con c1')
     def c2_rule(model, a):
         return model.B[a] * model.x[a] <= 1
     model.c2 = Constraint(model.A, doc='con c2', rule=c2_rule)
     model.c3 = ConstraintList(doc='con c3')
     model.c3.add(model.y <= 0)
     #
     OUTPUT=open(join(currdir, "test_expr5.out"), "w")
     model.pprint(ostream=OUTPUT)
     OUTPUT.close()
     _out, _txt = join(currdir, "test_expr5.out"), join(currdir, "test_expr5.txt")
     self.assertTrue(cmp(_out, _txt), 
                     msg="Files %s and %s differ" % (_out, _txt))
Пример #23
0
def generic_add_model_components(m, d, reserve_zone_param, reserve_zone_set,
                                 reserve_generator_set,
                                 generator_reserve_provision_variable,
                                 total_reserve_provision_expression):
    """
    Generic treatment of reserves. This function creates model components
    related to a particular reserve requirement, including
    1) an expression aggregating generator-level provision to total provision
    :param m:
    :param d:
    :param reserve_zone_param:
    :param reserve_zone_set:
    :param reserve_generator_set:
    :param generator_reserve_provision_variable:
    :param total_reserve_provision_expression:
    :return:
    """

    # Reserve generators operational generators in timepoint
    # This will be the intersection of the reserve generator set and the set of
    # generators operational in the timepoint
    op_set = str(reserve_generator_set) + "_OPERATIONAL_IN_TIMEPOINT"
    setattr(
        m, op_set,
        Set(m.TMPS,
            initialize=lambda mod, tmp: getattr(mod, reserve_generator_set) &
            mod.OPR_PRJS_IN_TMP[tmp]))

    # Reserve provision
    def total_reserve_rule(mod, ba, tmp):
        return sum(
            getattr(mod, generator_reserve_provision_variable)[g, tmp]
            for g in getattr(mod, op_set)[tmp]
            if getattr(mod, reserve_zone_param)[g] == ba)

    setattr(
        m, total_reserve_provision_expression,
        Expression(getattr(m, reserve_zone_set),
                   m.TMPS,
                   rule=total_reserve_rule))
Пример #24
0
    def test_indexed_block(self):
        m = ConcreteModel()
        m.time = ContinuousSet(bounds=(0,1))
        m.comp = Set(initialize=['a', 'b'])

        def bb_rule(bb, t):
            bb.dae_var = Var()

        def b_rule(b, c):
            b.bb = Block(m.time, rule=bb_rule)

        m.b = Block(m.comp, rule=b_rule)

        scalar, dae = flatten_dae_variables(m, m.time)
        self.assertEqual(len(scalar), 0)
        ref_data = {
                self._hashRef(Reference(m.b['a'].bb[:].dae_var)),
                self._hashRef(Reference(m.b['b'].bb[:].dae_var)),
                }
        self.assertEqual(len(dae), len(ref_data))
        for ref in dae:
            self.assertIn(self._hashRef(ref), ref_data)
Пример #25
0
        def _block_rule(b, t):
            m = b.model()

            b.s1 = Set(initialize=['A1', 'A2', 'A3'])

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

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

            def _con1(_b, ti):
                return _b.v1[ti] * _b.p1[ti] == _b.v1[t]**2

            b.con1 = Constraint(m.t, rule=_con1)

            def _con2(_b, i, ti):
                return _b.v2[ti] - _b.v3[ti, i] + _b.p1[ti]

            b.con2 = Expression(b.s1, m.t, rule=_con2)
Пример #26
0
def add_model_components(m, d, scenario_directory, subproblem, stage):
    """
    :param m: the Pyomo abstract model object we are adding components to
    :param d: the dynamic inputs class object; not used here

    The module adds the *LOAD_ZONES* set to the model formulation.

    We will designate the *LOAD_ZONES* set with *Z* and the load zones index
    will be *z*.
    """
    m.LOAD_ZONES = Set()

    m.allow_overgeneration = Param(m.LOAD_ZONES, within=Boolean)
    m.overgeneration_penalty_per_mw = Param(m.LOAD_ZONES, within=NonNegativeReals)

    m.allow_unserved_energy = Param(m.LOAD_ZONES, within=Boolean)
    m.unserved_energy_penalty_per_mwh = Param(m.LOAD_ZONES, within=NonNegativeReals)

    m.max_unserved_load_penalty_per_mw = Param(m.LOAD_ZONES, within=NonNegativeReals)

    # Can only be applied if transmission is included
    m.export_penalty_cost_per_mwh = Param(m.LOAD_ZONES, within=NonNegativeReals)
Пример #27
0
    def model(self):
        m = ConcreteModel()

        m.fs = FlowsheetBlock(default={"dynamic": False})

        m.fs.params = CubicParameterBlock(default={"valid_phase": "Vap"})
        m.fs.params.component_list = Set(initialize=["a", "b"])
        m.fs.params.cubic_type = CubicEoS.SRK

        m.fs.params.gas_const = Param(default=8.314462618)

        m.fs.params.pressure_crit = Param(m.fs.params.component_list,
                                          initialize={
                                              'a': 5e6,
                                              'b': 4e6
                                          })
        m.fs.params.temperature_crit = Param(m.fs.params.component_list,
                                             initialize={
                                                 "a": 500,
                                                 "b": 600
                                             })

        m.fs.params.omega = Param(m.fs.params.component_list,
                                  initialize={
                                      "a": 0.2,
                                      "b": 0.2
                                  })

        m.fs.params.kappa = Param(m.fs.params.component_list,
                                  m.fs.params.component_list,
                                  initialize={
                                      ('a', 'a'): 0.0,
                                      ('a', 'b'): 0.0,
                                      ('b', 'a'): 0.0,
                                      ('b', 'b'): 0.0
                                  })

        return m
Пример #28
0
    def build(self):
        super(EnzymeReactionParameterData, self).build()

        self.reaction_block_class = EnzymeReactionBlock

        self.rate_reaction_idx = Set(initialize=['R1', 'R2', 'R3'])
        self.rate_reaction_stoichiometry = {('R1', 'aq', 'S'): -1,
                                            ('R1', 'aq', 'E'): -1,
                                            ('R1', 'aq', 'C'): 1,
                                            ('R1', 'aq', 'P'): 0,
                                            ('R1', 'aq', 'Solvent'): 0,
                                            ('R2', 'aq', 'S'): 1,
                                            ('R2', 'aq', 'E'): 1,
                                            ('R2', 'aq', 'C'): -1,
                                            ('R2', 'aq', 'P'): 0,
                                            ('R2', 'aq', 'Solvent'): 0,
                                            ('R3', 'aq', 'S'): 0,
                                            ('R3', 'aq', 'E'): 1,
                                            ('R3', 'aq', 'C'): -1,
                                            ('R3', 'aq', 'P'): 1,
                                            ('R3', 'aq', 'Solvent'): 0}

        self.act_energy = Param(self.rate_reaction_idx,
                initialize={'R1': 8.0e3,
                            'R2': 9.0e3,
                            'R3': 1.0e4},
                doc='Activation energy [kcal/kmol]')

        self.gas_const = Param(initialize=1.987, 
                doc='Gas constant R [kcal/kmol/K]')

        self.temperature_ref = Param(initialize=300.0, doc='Reference temperature')

        self.k_rxn = Param(self.rate_reaction_idx,
                initialize={'R1': 3.36e6,
                            'R2': 1.80e6,
                            'R3': 5.79e7},
                doc='Pre-exponential rate constant in Arrhenius expression')
Пример #29
0
    def _add_category_blocks(self):
        """ Adds an indexed block for each category of variable and
        attach a reference to each variable to one of the BlockDatas.
        """
        category_dict = self.category_dict
        var_name = self._var_name
        for categ, varlist in category_dict.items():
            ctype = CATEGORY_TYPE_MAP.get(categ, NmpcVar)
            # These names are e.g. 'DIFFERENTIAL_BLOCK', 'DIFFERENTIAL_SET'
            # They serve as a way to access all the "differential variables"
            block_name = self.get_category_block_name(categ)
            set_name = self.get_category_set_name(categ)
            set_range = range(len(varlist))

            # Construct a set that indexes, eg, the "differential variables"
            category_set = Set(initialize=set_range)
            self.add_component(set_name, category_set)

            # Construct an IndexedBlock, each data object of which
            # will contain a single reference-to-timeslice of that
            # category, and with the corresponding custom ctype
            category_block = Block(category_set)
            self.add_component(block_name, category_block)

            # Don't want these blocks sent to any solver.
            category_block.deactivate()

            for i, var in enumerate(varlist):
                # Add reference-to-timeslices to new blocks:
                #
                # Create a new reference if var is not a reference or
                # it has the wrong ctype...
                # We may want to reconsider overriding the user's ctype...
                # We may also want to make sure these references are not
                # attached to anything. Otherwise we will fail here.
                ref = var if var.is_reference() and var.ctype is ctype \
                        else Reference(var, ctype=ctype)
                category_block[i].add_component(var_name, ref)
Пример #30
0
    def test_index1(self):
        self.model.A = Set(initialize=range(0, 4))

        def B_index(model):
            for i in model.A:
                if i % 2 == 0:
                    yield i

        def B_init(model, i, j):
            if j:
                return 2 + i
            return -(2 + i)

        self.model.B = Var(B_index, [True, False],
                           initialize=B_init,
                           dense=True)
        self.instance = self.model.create_instance()
        self.assertEqual(set(self.instance.B.keys()),
                         set([(0, True), (2, True), (0, False), (2, False)]))
        self.assertEqual(self.instance.B[0, True], 2)
        self.assertEqual(self.instance.B[0, False], -2)
        self.assertEqual(self.instance.B[2, True], 4)
        self.assertEqual(self.instance.B[2, False], -4)