Exemplo n.º 1
0
 def test_subproblem_preprocessing_encounters_trivial_constraints(self):
     m = ConcreteModel()
     m.x = Var(bounds=(0, 10))
     m.z = Var(bounds=(-10, 10))
     m.disjunction = Disjunction(expr=[[m.x == 0, m.z >= 4], 
                                       [m.x + m.z <= 0]])
     m.cons = Constraint(expr=m.x*m.z <= 0)
     m.obj = Objective(expr=-m.z)
     m.disjunction.disjuncts[0].indicator_var.fix(True)
     m.disjunction.disjuncts[1].indicator_var.fix(False)
     SolverFactory('gdpopt').solve(m, strategy='RIC', mip_solver=mip_solver,
                                   nlp_solver=nlp_solver,
                                   init_strategy='fix_disjuncts')
     # The real test is that this doesn't throw an error when we preprocess
     # to solve the first subproblem (in the initialization). The nonlinear
     # constraint becomes trivial, which we need to make sure is handled
     # correctly.
     self.assertEqual(value(m.x), 0)
     self.assertEqual(value(m.z), 10)
     self.assertTrue(value(m.disjunction.disjuncts[0].indicator_var))
     self.assertFalse(value(m.disjunction.disjuncts[1].indicator_var))
Exemplo n.º 2
0
    def setUp(self):

        m = ConcreteModel()
        m.z = Var(range(3), domain=Reals, initialize=2.)
        m.x = Var(range(2), initialize=2.)
        m.x[1] = 1.0

        def blackbox(a, b):
            return sin(a - b)

        self.bb = ExternalFunction(blackbox)

        m.obj = Objective(
            expr=(m.z[0]-1.0)**2 + (m.z[0]-m.z[1])**2 + (m.z[2]-1.0)**2 \
                + (m.x[0]-1.0)**4 + (m.x[1]-1.0)**6 # + m.bb(m.x[0],m.x[1])
            )
        m.c1 = Constraint(expr=m.x[0] * m.z[0]**2 +
                          self.bb(m.x[0], m.x[1]) == 2 * sqrt(2.0))
        m.c2 = Constraint(expr=m.z[2]**4 * m.z[1]**2 + m.z[1] == 8 + sqrt(2.0))

        self.m = m.clone()
Exemplo n.º 3
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))
Exemplo n.º 4
0
 def test_model_clone(self):
     model = ConcreteModel()
     model.x = Var(initialize=2.0)
     model.y = Var(initialize=0.0)
     model.ec = Expression(initialize=model.x**2 + 1)
     model.obj = Objective(expr=model.y + model.ec)
     self.assertEqual(model.obj.expr(), 5.0)
     self.assertTrue(id(model.ec) in [id(e) for e in model.obj.expr.args])
     inst = model.clone()
     self.assertEqual(inst.obj.expr(), 5.0)
     if not id(inst.ec) in [id(e) for e in inst.obj.expr.args]:
         print("BUG?")
         print(id(inst.ec))
         print(inst.obj.expr.__class__)
         print([id(e) for e in inst.obj.expr.args])
         print([e.__class__ for e in inst.obj.expr.args])
         print([id(e) for e in model.obj.expr.args])
         print([e.__class__ for e in model.obj.expr.args])
     self.assertTrue(id(inst.ec) in [id(e) for e in inst.obj.expr.args])
     self.assertNotEqual(id(model.ec), id(inst.ec))
     self.assertFalse(id(inst.ec) in [id(e) for e in model.obj.expr.args])
Exemplo n.º 5
0
def test_pysmo_rbf(branin_dataset):
    m, x, y = branin_dataset

    pysmo_rbf_settings = {
        'basis_function': 'gaussian',
        'regularization': True,
        'pyomo_vars': [m.x[1], m.x[2]]
    }
    modeler = Pysmo_rbf(**pysmo_rbf_settings)

    modeler.regressed_data(x, y)
    modeler.build_model()

    m.obj = Objective(expr=modeler._model)
    m.pprint()

    modeler.save_results('results.pickle', overwrite=True)

    check_metrics(modeler.get_results())

    return True
Exemplo n.º 6
0
def test_pysmo_krig(branin_dataset):
    m, x, y = branin_dataset

    pysmo_krg_settings = {
        'numerical_gradients': True,
        'regularization': True,
        'pyomo_vars': [m.x[1], m.x[2]]
    }
    modeler = Pysmo_kriging(**pysmo_krg_settings)

    modeler.regressed_data(x, y)
    modeler.build_model()

    m.obj = Objective(expr=modeler._model)
    m.pprint()

    modeler.save_results('results.pickle', overwrite=True)

    check_metrics(modeler.get_results())

    return True
Exemplo n.º 7
0
    def test_var_on_nonblock(self):
        class Foo(Block().__class__):
            def __init__(self, *args, **kwds):
                kwds.setdefault('ctype', Foo)
                super(Foo, self).__init__(*args, **kwds)

        model = ConcreteModel()
        model.x = Var()
        model.other = Foo()
        model.other.a = Var()
        model.c = Constraint(expr=model.other.a + 2 * model.x <= 0)
        model.obj = Objective(expr=model.x)

        baseline_fname, test_fname = self._get_fnames()
        self._cleanup(test_fname)
        self.assertRaisesRegex(KeyError,
                               "'other.a' exists within Foo 'other'",
                               model.write,
                               test_fname,
                               format='nl')
        self._cleanup(test_fname)
Exemplo n.º 8
0
 def test_replaceExternalFunctionsWithVariables(self):
     # In running this method, we not only replace EFs
     # with 'holder' vars; we also get useful information
     # about inputs, outputs, basis expressions, etc.
     self.interface.replaceExternalFunctionsWithVariables()
     # Check the directly defined model vars against all_variables
     for var in self.interface.model.component_data_objects(Var):
         self.assertIn(var, ComponentSet(self.interface.data.all_variables))
     # Check the output vars against all_variables
     for i in self.interface.data.ef_outputs:
         self.assertIn(self.interface.data.ef_outputs[i],
                       ComponentSet(self.interface.data.all_variables))
     # The truth models should be a mapping from the EF to
     # the replacement
     for i, k in self.interface.data.truth_models.items():
         self.assertIsInstance(k, ExternalFunctionExpression)
         self.assertIn(str(self.interface.model.x[0]), str(k))
         self.assertIn(str(self.interface.model.x[1]), str(k))
         self.assertIsInstance(i, _GeneralVarData)
         self.assertEqual(i, self.interface.data.ef_outputs[1])
     for i, k in self.interface.data.basis_expressions.items():
         self.assertEqual(k, 0)
         self.assertEqual(i, self.interface.data.ef_outputs[1])
     self.assertEqual(1, list(self.interface.data.ef_inputs.keys())[0])
     self.assertEqual(
         self.interface.data.ef_inputs[1],
         [self.interface.model.x[0], self.interface.model.x[1]])
     # HACK: This was in response to a hack.
     # Remove when NL writer re-write is complete.
     # Make sure that EFs were removed from the cloned model.
     self.assertEqual(
         list(self.interface.model.component_objects(ExternalFunction)), [])
     # TRF only supports one active Objective.
     # Make sure that it fails if there are multiple objs.
     self.m.obj2 = Objective(expr=(self.m.x[0]**2 - (self.m.z[1] - 3)**3))
     interface = TRFInterface(self.m,
                              [self.m.z[0], self.m.z[1], self.m.z[2]],
                              self.ext_fcn_surrogate_map_rule, self.config)
     with self.assertRaises(ValueError):
         interface.replaceExternalFunctionsWithVariables()
Exemplo n.º 9
0
def optimize_set_up(m):
    # objective
    m.fs.objective = Objective(expr=m.fs.costing.LCOW)

    # unfix decision variables and add bounds
    # pump 1 and pump 2
    m.fs.P1.control_volume.properties_out[0].pressure.unfix()
    m.fs.P1.control_volume.properties_out[0].pressure.setlb(10e5)
    m.fs.P1.control_volume.properties_out[0].pressure.setub(80e5)
    m.fs.P1.deltaP.setlb(0)
    m.fs.P2.control_volume.properties_out[0].pressure.setlb(10e5)
    m.fs.P2.control_volume.properties_out[0].pressure.setub(80e5)
    m.fs.P2.deltaP.setlb(0)

    # RO
    m.fs.RO.area.setlb(1)
    m.fs.RO.area.setub(150)

    # additional specifications
    m.fs.product_salinity = Param(
        initialize=500e-6, mutable=True
    )  # product NaCl mass fraction [-]
    m.fs.minimum_water_flux = Param(
        initialize=1.0 / 3600.0, mutable=True
    )  # minimum water flux [kg/m2-s]

    # additional constraints
    m.fs.eq_product_quality = Constraint(
        expr=m.fs.product.properties[0].mass_frac_phase_comp["Liq", "NaCl"]
        <= m.fs.product_salinity
    )
    iscale.constraint_scaling_transform(
        m.fs.eq_product_quality, 1e3
    )  # scaling constraint
    m.fs.eq_minimum_water_flux = Constraint(
        expr=m.fs.RO.flux_mass_phase_comp[0, 1, "Liq", "H2O"] >= m.fs.minimum_water_flux
    )

    # ---checking model---
    assert_degrees_of_freedom(m, 1)
Exemplo n.º 10
0
    def test_solve_with_store5(self):
        model = ConcreteModel()
        model.A = RangeSet(1, 4)
        model.b = Block()
        model.b.x = Var(model.A, bounds=(-1, 1))
        model.b.obj = Objective(expr=sum_product(model.b.x))
        model.c = Constraint(expr=model.b.x[1] >= 0)

        smanager = SolverManager_Serial()
        ah = smanager.queue(model, solver='glpk', load_solutions=False)
        results = smanager.wait_for(ah)
        self.assertEqual(len(model.solutions), 0)
        self.assertEqual(len(results.solution), 1)
        model.solutions.load_from(results)
        self.assertEqual(len(model.solutions), 1)
        self.assertEqual(len(results.solution), 1)
        #
        model.solutions.store_to(results)
        results.write(filename=join(currdir, 'solve_with_store8.out'),
                      format='json')
        self.assertMatchesYamlBaseline(join(currdir, "solve_with_store8.out"),
                                       join(currdir, "solve_with_store4.txt"))
Exemplo n.º 11
0
    def test_optimal_mip(self):
        self.model.Idx = RangeSet(2)
        self.model.X = Var(self.model.Idx, within=NonNegativeIntegers)
        self.model.Y = Var(self.model.Idx, within=Binary)
        self.model.C1 = Constraint(expr=self.model.X[1] == self.model.X[2] + 1)
        self.model.Obj = Objective(expr=self.model.Y[1] + self.model.Y[2] -
                                   self.model.X[1],
                                   sense=maximize)

        results = self.opt.solve(self.model)

        self.assertEqual(1.0, results.problem.lower_bound)
        self.assertEqual(1.0, results.problem.upper_bound)
        self.assertEqual(results.problem.number_of_binary_variables, 2)
        self.assertEqual(results.problem.number_of_integer_variables, 4)
        self.assertEqual(ProblemSense.maximize, results.problem.sense)
        self.assertEqual(TerminationCondition.optimal,
                         results.solver.termination_condition)
        self.assertEqual(
            'Model was solved to optimality (subject to tolerances), and an optimal solution is available.',
            results.solver.termination_message)
        self.assertEqual(SolverStatus.ok, results.solver.status)
Exemplo n.º 12
0
    def _construct_objective(self):
        """
        Construction of the objectives.

        When using Continuous Set, the implicit expression such as sum(x[t] for t in Time)
        must be created after time discrimination. Otherwise, the expression will only consider
        existing timeSteps.
        To overcome this behaviour, this method allows to automatically redefine objectives after time discretization.

        ..note: should be used in some rare cases. Normally, the Integral object should be able to do the trick.
        """

        for block in self.component_map(active=True, ctype=Block):
            try:
                block.construct_objective()
            except OSError as err:
                raise err

        for obj in self.component_map(active=True, ctype=Objective):
            rule = self.component(obj).rule
            self.del_component(obj)
            self.add_component(obj, Objective(rule=rule))
Exemplo n.º 13
0
 def test_solve4(self):
     model = ConcreteModel()
     model.A = RangeSet(1,4)
     model.x = Var(model.A, bounds=(-1,1))
     def obj_rule(model):
         return sum_product(model.x)
     model.obj = Objective(rule=obj_rule)
     def c_rule(model):
         expr = 0
         for i in model.A:
             expr += i*model.x[i]
         return expr == 0
     model.c = Constraint(rule=c_rule)
     opt = SolverFactory('glpk')
     results = opt.solve(model, symbolic_solver_labels=True)
     model.solutions.store_to(results)
     results.write(filename=join(currdir,'solve4.out'), format='json')
     with open(join(currdir,"solve4.out"), 'r') as out, \
         open(join(currdir,"solve1.txt"), 'r') as txt:
         self.assertStructuredAlmostEqual(json.load(txt), json.load(out),
                                          abstol=1e-4,
                                          allow_second_superset=True)
Exemplo n.º 14
0
    def test_logical_constraints_transformed(self):
        """It is expected that the result of this transformation is a MI(N)LP,
        so check that LogicalConstraints are handeled correctly"""
        m = ConcreteModel()
        m.x = Var(bounds=(0, 10))
        m.d1 = Disjunct()
        m.d2 = Disjunct()
        m.d2.c = Constraint()
        m.d = Disjunction(expr=[m.d1, m.d2])
        m.another = Disjunction(expr=[[m.x == 3], [m.x == 0]])
        m.Y = BooleanVar()
        m.global_logical = LogicalConstraint(expr=m.Y.xor(m.d1.indicator_var))
        m.d1.logical = LogicalConstraint(
            expr=implies(~m.Y, m.another.disjuncts[0].indicator_var))
        m.obj = Objective(expr=m.x)

        m.d1.indicator_var.set_value(True)
        m.d2.indicator_var.set_value(False)
        m.another.disjuncts[0].indicator_var.set_value(True)
        m.another.disjuncts[1].indicator_var.set_value(False)

        TransformationFactory('gdp.fix_disjuncts').apply_to(m)

        # Make sure there are no active LogicalConstraints
        self.assertEqual(
            len(
                list(
                    m.component_data_objects(LogicalConstraint,
                                             active=True,
                                             descend_into=(Block, Disjunct)))),
            0)
        # See that it solves as expected
        SolverFactory('gurobi').solve(m)
        self.assertTrue(value(m.d1.indicator_var))
        self.assertFalse(value(m.d2.indicator_var))
        self.assertTrue(value(m.another.disjuncts[0].indicator_var))
        self.assertFalse(value(m.another.disjuncts[1].indicator_var))
        self.assertEqual(value(m.Y.get_associated_binary()), 0)
        self.assertEqual(value(m.x), 3)
def test_pysmo_poly(branin_dataset):
    m, x, y = branin_dataset

    pysmo_pr_settings = {'maximum_polynomial_order':4,
                         'multinomials':1,
                         'pyomo_vars': [m.x[1], m.x[2]],
                         'training_split':0.9,
                         'number_of_crossvalidations': 5,
                         'additional_features_list': ['ft[0] * ft[0] * ft[1] * ft[1]', 'pyo.exp(ft[0])', 'pyo.exp(ft[1])']}
    modeler = Pysmo_polyregression(**pysmo_pr_settings)

    modeler.regressed_data(x, y)
    modeler.build_model()

    m.obj = Objective(expr=modeler._model)
    m.pprint()

    modeler.save_results('results.pickle', overwrite=True)

    check_metrics(modeler.get_results())

    return True
Exemplo n.º 16
0
 def test_solve_with_pickle(self):
     model = ConcreteModel()
     model.A = RangeSet(1, 4)
     model.b = Block()
     model.b.x = Var(model.A, bounds=(-1, 1))
     model.b.obj = Objective(expr=sum_product(model.b.x))
     model.c = Constraint(expr=model.b.x[1] >= 0)
     opt = SolverFactory('glpk')
     self.assertEqual(len(model.solutions), 0)
     results = opt.solve(model, symbolic_solver_labels=True)
     self.assertEqual(len(model.solutions), 1)
     #
     self.assertEqual(model.solutions[0].gap, 0.0)
     #self.assertEqual(model.solutions[0].status, SolutionStatus.feasible)
     self.assertEqual(model.solutions[0].message, None)
     #
     buf = pickle.dumps(model)
     tmodel = pickle.loads(buf)
     self.assertEqual(len(tmodel.solutions), 1)
     self.assertEqual(tmodel.solutions[0].gap, 0.0)
     #self.assertEqual(tmodel.solutions[0].status, SolutionStatus.feasible)
     self.assertEqual(tmodel.solutions[0].message, None)
Exemplo n.º 17
0
    def __init__(self, *args, **kwargs):
        """Create the problem."""
        kwargs.setdefault('name', 'DuranEx1')
        super(SimpleMINLP, self).__init__(*args, **kwargs)
        m = self
        """Set declarations"""
        I = m.I = RangeSet(1, 4, doc="continuous variables")
        J = m.J = RangeSet(1, 3, doc="discrete variables")

        # initial point information for discrete variables
        initY = {1: 1, 2: 0, 3: 1}
        # initial point information for continuous variables
        initX = {1: 0, 2: 0, 3: 0, 4: 0}
        """Variable declarations"""
        # DISCRETE VARIABLES
        Y = m.Y = Var(J, domain=Binary, initialize=initY)
        # CONTINUOUS VARIABLES
        X = m.X = Var(I, domain=NonNegativeReals, initialize=initX)
        """Constraint definitions"""
        # CONSTRAINTS
        m.const1 = Constraint(expr=0.8 * log(X[2] + 1) +
                              0.96 * log(X[1] - X[2] + 1) - 0.8 * X[3] >= 0)
        m.const2 = Constraint(expr=log(X[2] + 1) + 1.2 * log(X[1] - X[2] + 1) -
                              X[3] - 2 * Y[3] >= -2)
        m.const3 = Constraint(expr=10 * X[1] - 7 * X[3] - 18 * log(X[2] + 1) -
                              19.2 * log(X[1] - X[2] + 1) + 10 - X[4] <= 0)
        m.const4 = Constraint(expr=X[2] - X[1] <= 0)
        m.const5 = Constraint(expr=X[2] - 2 * Y[1] <= 0)
        m.const6 = Constraint(expr=X[1] - X[2] - 2 * Y[2] <= 0)
        m.const7 = Constraint(expr=Y[1] + Y[2] <= 1)
        """Cost (objective) function definition"""
        m.cost = Objective(expr=-5 * Y[1] - 6 * Y[2] - 8 * Y[3] - X[4],
                           sense=maximize)
        """Bound definitions"""
        # x (continuous) upper bounds
        x_ubs = {1: 2, 2: 2, 3: 1, 4: 100}
        for i, x_ub in iteritems(x_ubs):
            X[i].setub(x_ub)
Exemplo n.º 18
0
    def test_clear_attribute(self):
        # Test coverage of the _clear_attribute method
        model = ConcreteModel()
        obj = Set()
        model.A = obj
        self.assertEqual(model.A.local_name, "A")
        self.assertEqual(obj.local_name, "A")
        self.assertIs(obj, model.A)

        obj = Var()
        model.A = obj
        self.assertEqual(model.A.local_name, "A")
        self.assertEqual(obj.local_name, "A")
        self.assertIs(obj, model.A)

        obj = Param()
        model.A = obj
        self.assertEqual(model.A.local_name, "A")
        self.assertEqual(obj.local_name, "A")
        self.assertIs(obj, model.A)

        obj = Objective()
        model.A = obj
        self.assertEqual(model.A.local_name, "A")
        self.assertEqual(obj.local_name, "A")
        self.assertIs(obj, model.A)

        obj = Constraint()
        model.A = obj
        self.assertEqual(model.A.local_name, "A")
        self.assertEqual(obj.local_name, "A")
        self.assertIs(obj, model.A)

        obj = Set()
        model.A = obj
        self.assertEqual(model.A.local_name, "A")
        self.assertEqual(obj.local_name, "A")
        self.assertIs(obj, model.A)
Exemplo n.º 19
0
 def test_solve_with_store4(self):
     model = ConcreteModel()
     model.A = RangeSet(1,4)
     model.b = Block()
     model.b.x = Var(model.A, bounds=(-1,1))
     model.b.obj = Objective(expr=sum_product(model.b.x))
     model.c = Constraint(expr=model.b.x[1] >= 0)
     opt = SolverFactory('glpk')
     results = opt.solve(model, load_solutions=False)
     self.assertEqual(len(model.solutions), 0)
     self.assertEqual(len(results.solution), 1)
     model.solutions.load_from(results)
     self.assertEqual(len(model.solutions), 1)
     self.assertEqual(len(results.solution), 1)
     #
     model.solutions.store_to(results)
     results.write(filename=join(currdir,'solve_with_store8.out'),
                   format='json')
     with open(join(currdir,"solve_with_store8.out"), 'r') as out, \
         open(join(currdir,"solve_with_store4.txt"), 'r') as txt:
         self.assertStructuredAlmostEqual(yaml.full_load(txt),
                                          yaml.full_load(out),
                                          allow_second_superset=True)
Exemplo n.º 20
0
    def test_rule_option1(self):
        """Test rule option"""
        model = self.create_model()
        model.B = RangeSet(1,4)
        def f(model, i, k):
            ans=0
            for j in model.B:
                ans = ans + model.x[j]
            ans *= i
            return ans
        model.x = Var(model.B, initialize=2)
        model.obj = Objective(model.A,model.A, rule=f)

        try:
            self.assertEqual(model.obj(),None)
            self.fail("Expected TypeError")
        except TypeError:
            pass

        self.assertEqual(model.obj[1,1](), 8)
        self.assertEqual(model.obj[2,1](), 16)
        self.assertEqual(value(model.obj[1,1]), 8)
        self.assertEqual(value(model.obj[2,1]), 16)
Exemplo n.º 21
0
    def test_blending(self):
        """ The blending example from the PuLP documentation """
        model = ConcreteModel()

        model.x1 = Var(bounds=(0,None), doc="ChickenPercent")
        model.x2 = Var(bounds=(0,None), doc="BeefPercent")

        model.obj = Objective(expr=0.013*model.x1 + 0.008*model.x2, doc="Total Cost of Ingredients per can")

        model.c0 = Constraint(expr=model.x1+model.x2 == 100.0, doc="Percentage Sum")
        model.c1 = Constraint(expr=0.100*model.x1 + 0.200*model.x2 >= 8.0, doc="Protein Requirement")
        model.c2 = Constraint(expr=0.080*model.x1 + 0.100*model.x2 >= 6.0, doc="Fat Requirement")
        model.c3 = Constraint(expr=0.001*model.x1 + 0.005*model.x2 <= 2.0, doc="Fiber Requirement")
        model.c4 = Constraint(expr=0.002*model.x1 + 0.005*model.x2 <= 0.4, doc="Salt Requirement")
        opt = SolverFactory('glpk')
        results = opt.solve(model)
        model.solutions.store_to(results)
        results.write(filename=join(currdir, "blend.out"), format='json')
        with open(join(currdir,"blend.out"), 'r') as out, \
            open(join(currdir,"blend.txt"), 'r') as txt:
            self.assertStructuredAlmostEqual(json.load(txt), json.load(out),
                                             abstol=1e-2,
                                             allow_second_superset=True)
Exemplo n.º 22
0
def Build_Model(model):

    #******** OBJECTIVE FUNCTION *******#
    model.OBJ = Objective(rule=Equations.Compute_NPC, sense=minimize)

    #******** CONSTRAINTS ********#
    model.ConstraintEnergyBalance = Constraint(model.TimeSteps,
                                               rule=Equations.Balance_Energy)
    model.ConstraintEquivalentLossFactorLimit = Constraint(
        rule=Equations.Limit_EquivalentLossFactor)

    #*** Battery-Related Constraints
    model.ConstraintBatCharge = Constraint(model.TimeSteps,
                                           rule=Equations.Update_BatCharge)
    model.ConstraintBatChargeMin = Constraint(
        model.TimeSteps, rule=Equations.Limit_BatChargeMin)
    model.ConstraintBatChargeMax = Constraint(
        model.TimeSteps, rule=Equations.Limit_BatChargeMax)
    model.ConstraintMaxStorageOut = Constraint(model.TimeSteps,
                                               rule=Equations.Limit_StorageOut)
    model.ConstraintMaxStorageIn = Constraint(model.TimeSteps,
                                              rule=Equations.Limit_StorageIn)
    '''
Exemplo n.º 23
0
    def test_execute_TRF(self):
        m = ConcreteModel()
        m.z = Var(range(3), domain=Reals, initialize=2.)
        m.x = Var(range(2), initialize=2.)
        m.x[1] = 1.0

        def blackbox(a,b):
            return sin(a-b)
        bb = ExternalFunction(blackbox)

        m.obj = Objective(
            expr=(m.z[0]-1.0)**2 + (m.z[0]-m.z[1])**2 + (m.z[2]-1.0)**2 \
            + (m.x[0]-1.0)**4 + (m.x[1]-1.0)**6 # + m.bb(m.x[0],m.x[1])
        )
        m.c1 = Constraint(
            expr=m.x[0] * m.z[0]**2 + bb(m.x[0],m.x[1]) == 2*sqrt(2.0))
        m.c2 = Constraint(expr=m.z[2]**4 * m.z[1]**2 + m.z[1] == 8+sqrt(2.0))

        SolverFactory('trustregion').solve(m, [bb])

        self.assertAlmostEqual(value(m.obj), 0.277044789315, places=4)
        self.assertAlmostEqual(value(m.x[0]), 1.32193855369, places=4)
        self.assertAlmostEqual(value(m.x[1]), 0.628744699822, places=4)
Exemplo n.º 24
0
    def test_keepfiles_py(self):
        with SolverFactory("gams", solver_io="python") as opt:

            m = ConcreteModel()
            m.x = Var()
            m.c = Constraint(expr=m.x >= 10)
            m.o = Objective(expr=m.x)

            tmpdir = mkdtemp()

            results = opt.solve(m, tmpdir=tmpdir, keepfiles=True)

            self.assertTrue(os.path.exists(tmpdir))
            self.assertTrue(
                os.path.exists(os.path.join(tmpdir, '_gams_py_gjo0.gms')))
            self.assertTrue(
                os.path.exists(os.path.join(tmpdir, '_gams_py_gjo0.lst')))
            self.assertTrue(
                os.path.exists(os.path.join(tmpdir, '_gams_py_gdb0.gdx')))
            self.assertTrue(
                os.path.exists(os.path.join(tmpdir, '_gams_py_gjo0.pf')))

            shutil.rmtree(tmpdir)
Exemplo n.º 25
0
    def makeModel():
        m = ConcreteModel()
        m.x = Var(bounds=(0, 5))
        m.y = Var(bounds=(0, 5))

        def d_rule(disjunct, flag):
            m = disjunct.model()
            if flag:
                disjunct.c1 = Constraint(expr=1 <= m.x <= 2)
                disjunct.c2 = Constraint(expr=3 <= m.y <= 4)
            else:
                disjunct.c1 = Constraint(expr=3 <= m.x <= 4)
                disjunct.c2 = Constraint(expr=1 <= m.y <= 2)

        m.d = Disjunct([0, 1], rule=d_rule)

        def disj_rule(m):
            return [m.d[0], m.d[1]]

        m.disjunction = Disjunction(rule=disj_rule)

        m.obj = Objective(expr=m.x + 2 * m.y)
        return m
Exemplo n.º 26
0
 def test_solve_linear_GDP_unbounded(self):
     m = ConcreteModel()
     m.GDPopt_utils = Block()
     m.x = Var(bounds=(-1, 10))
     m.y = Var(bounds=(2, 3))
     m.z = Var()
     m.d = Disjunction(expr=[[m.x + m.y >= 5], [m.x - m.y <= 3]])
     m.o = Objective(expr=m.z)
     m.GDPopt_utils.variable_list = [m.x, m.y, m.z]
     m.GDPopt_utils.disjunct_list = [
         m.d._autodisjuncts[0], m.d._autodisjuncts[1]
     ]
     output = StringIO()
     with LoggingIntercept(output, 'pyomo.contrib.gdpopt', logging.WARNING):
         solver_data = GDPoptSolveData()
         solver_data.timing = Container()
         with time_code(solver_data.timing, 'main', is_main_timer=True):
             solve_linear_GDP(
                 m, solver_data,
                 GDPoptSolver.CONFIG(dict(mip_solver=mip_solver)))
         self.assertIn(
             "Linear GDP was unbounded. Resolving with arbitrary bound values",
             output.getvalue().strip())
Exemplo n.º 27
0
def test_noscalers():
    keras_folder_name = os.path.join(this_file_dir(), 'data', 'keras_models')
    keras_model = load_keras_json_hd5(keras_folder_name,
                                      'PT_data_2_10_10_2_sigmoid')

    input_labels = ['Temperature_K', 'Pressure_Pa']
    output_labels = ['EnthMol', 'VapFrac']
    input_bounds = {'Temperature_K': (-3.0, 3.0), 'Pressure_Pa': (-3.0, 3.0)}

    keras_surrogate = KerasSurrogate(keras_model=keras_model,
                                     input_labels=input_labels,
                                     output_labels=output_labels,
                                     input_bounds=input_bounds)
    # check solve with pyomo
    x_test = pd.DataFrame({'Temperature_K': [0.5], 'Pressure_Pa': [0.5]})
    y_test = keras_surrogate.evaluate_surrogate(x_test)

    m = ConcreteModel()
    m.obj = Objective(expr=1)
    m.surrogate = SurrogateBlock()
    m.surrogate.build_model(surrogate_object=keras_surrogate,
                            formulation=KerasSurrogate.Formulation.FULL_SPACE)
    m.surrogate.inputs['Temperature_K'].fix(0.5)
    m.surrogate.inputs['Pressure_Pa'].fix(0.5)
    solver = SolverFactory('ipopt')
    status = solver.solve(m, tee=True)
    assert_optimal_termination(status)

    y_test_pyomo = pd.DataFrame({
        'EnthMol': [value(m.surrogate.outputs['EnthMol'])],
        'VapFrac': [value(m.surrogate.outputs['VapFrac'])]
    })
    pd.testing.assert_frame_equal(y_test,
                                  y_test_pyomo,
                                  check_dtype=False,
                                  rtol=rtol,
                                  atol=atol)
Exemplo n.º 28
0
def get_model():
    # Borrowed this test model from the trust region tests
    m = ConcreteModel()
    m.z = Var(range(3), domain=Reals, initialize=2.)
    m.x = Var(range(4), initialize=2.)
    m.x[1] = 1.0
    m.x[2] = 0.0
    m.x[3] = None

    m.b1 = Block()
    m.b1.e1 = Expression(expr=m.x[0] + m.x[1])
    m.b1.e2 = Expression(expr=m.x[0] / m.x[2])
    m.b1.e3 = Expression(expr=m.x[3] * m.x[1])
    m.b1.e4 = Expression(expr=log(m.x[2]))
    m.b1.e5 = Expression(expr=log(m.x[2] - 2))

    def blackbox(a, b):
        return sin(a - b)

    m.bb = ExternalFunction(blackbox)

    m.obj = Objective(
        expr=(m.z[0]-1.0)**2 + (m.z[0]-m.z[1])**2 + (m.z[2]-1.0)**2 \
            + (m.x[0]-1.0)**4 + (m.x[1]-1.0)**6 # + m.bb(m.x[0],m.x[1])
        )
    m.c1 = Constraint(expr=m.x[0] * m.z[0]**2 + m.bb(m.x[0], m.x[1]) == 2 *
                      sqrt(2.0))
    m.c2 = Constraint(expr=m.z[2]**4 * m.z[1]**2 + m.z[1] == 8 + sqrt(2.0))
    m.c3 = Constraint(expr=m.x[1] == 3)
    m.c4 = Constraint(expr=0 == 3 / m.x[2])
    m.c5 = Constraint(expr=0 == log(m.x[2]))
    m.c6 = Constraint(expr=0 == log(m.x[2] - 4))
    m.c7 = Constraint(expr=0 == log(m.x[3]))
    m.p1 = Param(mutable=True, initialize=1)
    m.c8 = Constraint(expr=m.x[1] <= 1 / m.p1)
    m.p1 = 0
    return m
Exemplo n.º 29
0
def set_optimization_components(m, system_recovery, **kwargs):
    """
    adds max_saturation_index and system_recovery_target
    """
    m.fs.pump_RO.control_volume.properties_out[0].pressure.unfix()
    m.fs.pump_RO.control_volume.properties_out[0].pressure.setlb(20e5)
    m.fs.pump_RO.control_volume.properties_out[0].pressure.setub(75e5)

    m.fs.RO.area.unfix()
    m.fs.RO.area.setlb(10)
    m.fs.RO.area.setub(300)

    m.fs.RO.N_Re[0, 0].unfix()

    # Set lower bound for water flux at the RO outlet, based on a minimum net driving pressure, NDPmin
    m.fs.RO.NDPmin = Param(initialize=1e5, mutable=True, units=pyunits.Pa)
    m.fs.RO.flux_mass_phase_comp[0, 1, "Liq", "H2O"].setlb(
        value(m.fs.RO.A_comp[0, "H2O"] * m.fs.RO.dens_solvent *
              m.fs.RO.NDPmin))

    # saturation index
    m.fs.max_saturation_index = Param(initialize=1.0, mutable=True)
    m.fs.eq_max_saturation_index_desal = Constraint(
        expr=m.fs.desal_saturation.saturation_index <=
        m.fs.max_saturation_index)

    m.fs.system_recovery_target = Param(initialize=system_recovery,
                                        mutable=True)
    m.fs.system_recovery_tol = Param(initialize=5e-3, mutable=True)
    m.fs.eq_system_recovery = Constraint(expr=(
        m.fs.system_recovery_target,
        m.fs.system_recovery,
        m.fs.system_recovery_target + m.fs.system_recovery_tol,
    ))

    # set objective
    m.fs.objective = Objective(expr=m.fs.costing.LCOW)
def simple_reaction_model(data):

    # Create the concrete model
    model = ConcreteModel()

    model.x1 = Param(initialize=float(data['x1']))
    model.x2 = Param(initialize=float(data['x2']))

    # Rate constants
    model.rxn = RangeSet(2)
    initial_guess = {1: 750, 2: 1200}
    model.k = Var(model.rxn, initialize=initial_guess, within=PositiveReals)

    # reaction product
    model.y = Expression(expr=exp(-model.k[1] *
                                  model.x1 * exp(-model.k[2] / model.x2)))
                                  
    # fix all of the regressed parameters
    model.k.fix()


    #===================================================================
    # Stage-specific cost computations
    def ComputeFirstStageCost_rule(model):
        return 0
    model.FirstStageCost = Expression(rule=ComputeFirstStageCost_rule)

    def AllMeasurements(m):
        return (float(data['y']) - m.y) ** 2
    model.SecondStageCost = Expression(rule=AllMeasurements)

    def total_cost_rule(m):
        return m.FirstStageCost + m.SecondStageCost
    model.Total_Cost_Objective = Objective(rule=total_cost_rule,
                                           sense=minimize)

    return model