def main(plot=True, n_points=200): import numpy as np # create a Pyomo model m = pe.ConcreteModel() m.x = pe.Var() m.y = pe.Var() m.p = pe.Param(initialize=1, mutable=True) m.obj = pe.Objective(expr=m.x**2 + m.y**2) m.c1 = pe.Constraint(expr=m.y >= (m.x + 1)**2) m.c2 = pe.Constraint(expr=m.y >= (m.x - m.p)**2) opt = appsi.solvers.Cplex() # create an APPSI solver interface opt.config.load_solution = False # modify the config options opt.update_config.check_for_new_or_removed_vars = False # change how automatic updates are handled opt.update_config.update_vars = False # write a for loop to vary the value of parameter p from 1 to 10 p_values = [float(i) for i in np.linspace(1, 10, n_points)] obj_values = list() x_values = list() timer = HierarchicalTimer() # create a timer for some basic profiling timer.start('p loop') for p_val in p_values: m.p.value = p_val res = opt.solve(m, timer=timer) assert res.termination_condition == appsi.base.TerminationCondition.optimal obj_values.append(res.best_feasible_objective) opt.load_vars([m.x]) x_values.append(m.x.value) timer.stop('p loop') print(timer) if plot: import matplotlib.pyplot as plt # plot the results fig, ax1 = plt.subplots() ax1.set_xlabel('p') ax1.set_ylabel('objective') ax1.plot(p_values, obj_values, ':k', label='objective') ax2 = ax1.twinx() ax2.set_ylabel('x') ax2.plot(p_values, x_values, '-b', label='x') fig.legend() plt.show()
def get_initialized_model(self): # create a model with two inputs for the convergence evaluation # one that is a fixed variable and one that is a mutable param m = pe.ConcreteModel() m.var_a = pe.Var(initialize=1.0) m.var_a.fix(1.0) m.param_b = pe.Param(initialize=100) m.x = pe.Var(initialize=2.0) m.y = pe.Var(initialize=2.0) m.obj = pe.Objective(expr=(m.var_a - m.x)**2 + m.param_b * (m.y - m.x**2)**2) # return the initialized model return m
def test_pow_neg_odd2(self): m = pe.ConcreteModel() m.x = pe.Var(bounds=(-2, -1)) m.y = pe.Var() m.z = pe.Var() m.w = pe.Var() m.p = pe.Param(initialize=-3) m.c = pe.Constraint(expr=m.x**m.p + m.y + m.z == 0) m.c2 = pe.Constraint(expr=m.w - 3 * m.x**m.p == 0) rel = coramin.relaxations.relax(m) self.assertTrue(hasattr(rel, 'aux_cons')) self.assertTrue(hasattr(rel, 'aux_vars')) self.assertEqual(len(rel.aux_cons), 2) self.assertEqual(len(rel.aux_vars), 1) self.assertAlmostEqual(rel.aux_vars[1].lb, -1) self.assertAlmostEqual(rel.aux_vars[1].ub, -0.125) self.assertEqual(rel.aux_cons[1].lower, 0) self.assertEqual(rel.aux_cons[1].upper, 0) ders = reverse_sd(rel.aux_cons[1].body) self.assertEqual(ders[rel.z], 1) self.assertEqual(ders[rel.aux_vars[1]], 1) self.assertEqual(ders[rel.y], 1) self.assertEqual(len(list(identify_variables(rel.aux_cons[1].body))), 3) self.assertEqual(rel.aux_cons[2].lower, 0) self.assertEqual(rel.aux_cons[2].upper, 0) ders = reverse_sd(rel.aux_cons[2].body) self.assertEqual(ders[rel.w], 1) self.assertEqual(ders[rel.aux_vars[1]], -3) self.assertEqual(len(list(identify_variables(rel.aux_cons[2].body))), 2) self.assertTrue(hasattr(rel, 'relaxations')) self.assertTrue(hasattr(rel.relaxations, 'rel0')) self.assertTrue( isinstance(rel.relaxations.rel0, coramin.relaxations.PWUnivariateRelaxation)) self.assertIn(rel.x, ComponentSet(rel.relaxations.rel0.get_rhs_vars())) self.assertEqual(id(rel.aux_vars[1]), id(rel.relaxations.rel0.get_aux_var())) self.assertFalse(rel.relaxations.rel0.is_rhs_convex()) self.assertTrue(rel.relaxations.rel0.is_rhs_concave()) self.assertFalse(hasattr(rel.relaxations, 'rel1'))
def beta_pf_block_rule(block): #------------------------------LOCAL VARIABLES------------------------------ block.beta = pe.Var(within=pe.NonNegativeReals, initialize=1) #,bounds=(1e-3,None)) block.s_L = pe.Var(within=pe.NonNegativeReals, initialize=0) #,bounds=(0,1)) block.s_V = pe.Var(within=pe.NonNegativeReals, initialize=0) block.pf = pe.Var(within=pe.NonNegativeReals, initialize=0) #-----------------------------LOCAL parameters------------------------------ block.rho = pe.Param(initialize=1, mutable=True) print('>', 'Importing MPCC_beta_Reg Blocks......') print('>', 'Adding the following local variable:') print('-' * 50) for i in block.component_objects(pe.Var, active=True): print('|', i) for i in block.component_objects(pe.Param, active=True): print('|', i) print('-' * 50) print('>', 'Adjusting the f_V = f_L bounds to f_V = beta * f_L') print('') #------------------------------MPCC equations------------------------------- def penalty_rule(block): return block.pf >= block.rho*(sum(block.parent_block().L[s] for s in block.parent_block().outlet)*block.s_L \ + sum(block.parent_block().V[s] for s in block.parent_block().outlet)*block.s_V) block.penalty_con = pe.Constraint(rule=penalty_rule) def beta_rule(block): return block.beta == 1 - block.s_L + block.s_V block.beta_con = pe.Constraint(rule=beta_rule) #-----------------------------Global equations------------------------------ block.parent_block().del_component(block.parent_block().VL_equil_con) def VL_equil_rule(model, i): return model.f_V[i] == block.beta * model.f_L[i] block.parent_block().VL_equil_con = pe.Constraint(m.COMP_TOTAL, rule=VL_equil_rule)
def _set_QP_objective(self): ''' Attach dual weights, objective function and solver to each QP. QP dual weights are initialized to the MIP dual weights. ''' for name, mip in self.local_subproblems.items(): QP = self.local_QP_subproblems[name] obj, new = self._extract_objective(mip) ## Finish setting up objective for QP if self.bundling: m_source = self.local_scenarios[mip.scen_list[0]] x_source = QP.xr else: m_source = mip x_source = QP.x QP._mpisppy_model.W = pyo.Param( m_source._mpisppy_data.nonant_indices.keys(), mutable=True, initialize=m_source._mpisppy_model.W) # rhos are attached to each scenario, not each bundle (should they be?) ph_term = pyo.quicksum( (QP._mpisppy_model.W[nni] * x_source[nni] + (m_source._mpisppy_model.rho[nni] / 2.) * (x_source[nni] - m_source._mpisppy_model.xbars[nni]) * (x_source[nni] - m_source._mpisppy_model.xbars[nni]) for nni in m_source._mpisppy_data.nonant_indices)) if obj.is_minimizing(): QP.obj = pyo.Objective(expr=new + ph_term, sense=pyo.minimize) else: QP.obj = pyo.Objective(expr=-new + ph_term, sense=pyo.minimize) ''' Attach a solver with various options ''' solver = pyo.SolverFactory(self.FW_options['solvername']) if sputils.is_persistent(solver): solver.set_instance(QP) if 'qp_solver_options' in self.FW_options: qp_opts = self.FW_options['qp_solver_options'] if qp_opts: for (key, option) in qp_opts.items(): solver.options[key] = option self.local_QP_subproblems[name]._QP_solver_plugin = solver
def test_stoch_data_nontrivial_expression_constraint2(self): model = self._get_base_model() model.q = aml.Param(mutable=True, initialize=0.0) model.stochdata.declare(model.q, distribution=TableDistribution([0.0, 1.0])) model.c2._body = (model.d2 + model.q) * model.y sp = EmbeddedSP(model) with self.assertRaises(ValueError) as cm: pyomo.pysp.convert.smps.convert_embedded(self.tmpdir, 'test', sp) self.assertEqual( str(cm.exception), ("Cannot output embedded SP representation for component " "'c2'. The embedded SMPS writer does not yet handle the " "case where multiple stochastic data components appear " "in an expression that defines a single variable's " "coefficient. The coefficient for variable 'y' involves " "stochastic parameters: ['d2', 'q']"))
def test_stoch_range_constraint(self): model = self._get_base_model() model.q = aml.Param(mutable=True, initialize=0.0) model.stochdata.declare( model.q, distribution=TableDistribution([0.0,1.0])) model.c3 = aml.Constraint(expr=aml.inequality(model.q, model.y, 0)) sp = EmbeddedSP(model) with self.assertRaises(ValueError) as cm: pyomo.pysp.convert.smps.convert_embedded(self.tmpdir, 'test', sp) self.assertEqual( str(cm.exception), ("Cannot output embedded SP representation for component " "'c3'. The embedded SMPS writer does not yet handle range " "constraints that have stochastic data."))
def test_wind_dispatch(site): expected_objective = 20719.281 dispatch_n_look_ahead = 48 wind = WindPlant(site, technologies['wind']) model = pyomo.ConcreteModel(name='wind_only') model.forecast_horizon = pyomo.Set(initialize=range(dispatch_n_look_ahead)) wind._dispatch = WindDispatch(model, model.forecast_horizon, wind._system_model, wind._financial_model) # Manually creating objective for testing model.price = pyomo.Param(model.forecast_horizon, within=pyomo.Reals, default=60.0, # assuming flat PPA of $60/MWh mutable=True, units=u.USD / u.MWh) def create_test_objective_rule(m): return sum((m.wind[t].time_duration * (m.price[t] - m.wind[t].cost_per_generation) * m.wind[t].generation) for t in m.wind.index_set()) model.test_objective = pyomo.Objective( rule=create_test_objective_rule, sense=pyomo.maximize) assert_units_consistent(model) wind.dispatch.initialize_parameters() wind.simulate(1) wind.dispatch.update_time_series_parameters(0) results = HybridDispatchBuilderSolver.glpk_solve_call(model) assert results.solver.termination_condition == TerminationCondition.optimal assert pyomo.value(model.test_objective) == pytest.approx(expected_objective, 1e-5) available_resource = wind.generation_profile[0:dispatch_n_look_ahead] dispatch_generation = wind.dispatch.generation for t in model.forecast_horizon: assert dispatch_generation[t] * 1e3 == pytest.approx(available_resource[t], 1e-3)
def pyomo(G): opt = pyo.SolverFactory('gurobi') model = pyo.ConcreteModel() model.n = pyo.Param(default=G.numberOfNodes()) model.x = pyo.Var(pyo.RangeSet(0, model.n - 1), within=pyo.Binary) model.obj = pyo.Objective(expr=0) model.c = pyo.Constraint(rule=model.x[2] <= 1) for u, v in G.iterEdges(): w = G.weight(u, v) model.obj.expr += (2 * w * model.x[u] * model.x[v]) model.obj.expr += (-w * model.x[u]) + (-w * model.x[v]) results = opt.solve(model) solution = {} for i in range(G.numberOfNodes()): solution[i] = model.x[i].value if solution[i] == None: solution[i] = 0 return solution
def test_stoch_constraint_body_constant(self): model = self._get_base_model() model.q = aml.Param(mutable=True, initialize=0.0) model.stochdata.declare(model.q, distribution=TableDistribution([0.0, 1.0])) model.c2._body = model.d2 * model.y + model.q sp = EmbeddedSP(model) with self.assertRaises(ValueError) as cm: pyomo.pysp.convert.smps.convert_embedded(self.tmpdir, 'test', sp) self.assertEqual( str(cm.exception), ("Cannot output embedded SP representation for component " "'c2'. The embedded SMPS writer does not yet handle the " "case where a stochastic data appears in the body of a " "constraint expression that must be moved to the bounds. " "The constraint must be written so that the stochastic " "element 'q' is a simple bound or a simple variable " "coefficient."))
def test_abstract_model_with_constraints() -> None: abs_model = pyomo.AbstractModel() abs_model.F = pyomo.Set() abs_model.Xmin = pyomo.Param(abs_model.F, within=pyomo.Reals, default=0.0) abs_model.x = pyomo.Var(abs_model.F, within=pyomo.Reals) abs_model.constraints = pyomo.Constraint(abs_model.F, rule=lambda m, i: m.x[i] >= m.Xmin[i]) abs_model.obj = pyomo.Objective(rule=square) # Load the values of the parameters from external file dirname = os.path.dirname(__file__) filename = os.path.join(dirname, "test_model_1.dat") model = abs_model.create_instance(filename) func = core.Pyomo(model) optimizer = ng.optimizers.OnePlusOne(parametrization=func.parametrization, budget=200) recommendation = optimizer.minimize(func.function) np.testing.assert_almost_equal(recommendation.kwargs['x["New York"]'], model.Xmin["New York"], decimal=1) np.testing.assert_almost_equal(recommendation.kwargs['x["Hong Kong"]'], model.Xmin["Hong Kong"], decimal=1)
def create_model(model): ## Conjuntos model.NODOS = pyo.Set() model.ORDEN = pyo.Set() model.R = pyo.Set() ## Parámetros model.Distancia = pyo.Param(model.NODOS, model.NODOS) ## Variables model.x = pyo.Var(model.ORDEN, model.ORDEN, domain=pyo.Binary) model.aux = pyo.Var(model.R) ## Función Objetivo def ObjFunc(model): return sum(model.Distancia[i, j] * model.x[i, j] for i in model.ORDEN for j in model.ORDEN) model.FO = pyo.Objective(rule=ObjFunc) ## Restricciones def r1(model, j): return sum(model.x[i, j] for i in model.ORDEN) == 1 model.r1 = pyo.Constraint(model.ORDEN, rule=r1) def r2(model, i): return sum(model.x[i, j] for j in model.ORDEN) == 1 model.r2 = pyo.Constraint(model.ORDEN, rule=r2) def r3(model, i): return model.x[i, i] == 0 model.r3 = pyo.Constraint(model.ORDEN, rule=r3) def r4(model, i, j): if (i != j): return model.aux[i] - model.aux[j] + len( model.R) * model.x[i, j] <= len(model.R) - 1 return pyo.Constraint.Skip model.r4 = pyo.Constraint(model.R, model.R, rule=r4)
def _create_storage_parameters(self, storage): ################################## # Parameters # ################################## storage.time_duration = pyomo.Param( doc="Time step [hour]", default=1.0, within=pyomo.NonNegativeReals, mutable=True, units=u.hr) storage.cost_per_charge = pyomo.Param( doc="Operating cost of " + self.block_set_name + " charging [$/MWh]", default=0., within=pyomo.NonNegativeReals, mutable=True, units=u.USD / u.MWh) storage.cost_per_discharge = pyomo.Param( doc="Operating cost of " + self.block_set_name + " discharging [$/MWh]", default=0., within=pyomo.NonNegativeReals, mutable=True, units=u.USD / u.MWh) storage.minimum_power = pyomo.Param( doc=self.block_set_name + " minimum power rating [MW]", default=0.0, within=pyomo.NonNegativeReals, mutable=True, units=u.MW) storage.maximum_power = pyomo.Param( doc=self.block_set_name + " maximum power rating [MW]", within=pyomo.NonNegativeReals, mutable=True, units=u.MW) storage.minimum_soc = pyomo.Param( doc=self.block_set_name + " minimum state-of-charge [-]", default=0.1, within=pyomo.PercentFraction, mutable=True, units=u.dimensionless) storage.maximum_soc = pyomo.Param( doc=self.block_set_name + " maximum state-of-charge [-]", default=0.9, within=pyomo.PercentFraction, mutable=True, units=u.dimensionless)
def add_parameter(self, name, index=None, values=None, mutable=True, default=None, **kwargs): name = self._id(name) self._parent_problem().add_component_to_problem( pyomo.Param(index, name=name, mutable=mutable, default=default, **kwargs)) if values is not None: if pd.Series(values).count() != len(values): raise ValueError("a parameter value cannot be NaN") var = self._parent_problem().get_component(name) for i in index: var[i] = values[i]
def test_x_sq(self): m = pe.ConcreteModel() m.p = pe.Param(initialize=-1, mutable=True) m.x = pe.Var(bounds=(-1, 1)) m.y = pe.Var() m.z = pe.Var(bounds=(0, None)) m.c = coramin.relaxations.PWXSquaredRelaxation() m.c.build(x=m.x, w=m.y, relaxation_side=coramin.utils.RelaxationSide.BOTH) m.c2 = pe.ConstraintList() m.c2.add(m.z >= m.y - m.p) m.c2.add(m.z >= m.p - m.y) m.obj = pe.Objective(expr=m.z) opt = pe.SolverFactory('glpk') for xval in [-1, -0.5, 0, 0.5, 1]: pval = xval**2 m.x.fix(xval) m.p.value = pval res = opt.solve(m, tee=False) self.assertTrue(res.solver.termination_condition == pe.TerminationCondition.optimal) self.assertAlmostEqual(m.y.value, m.p.value, 6)
def addParameter(self, name, index=None, values=None, mutable=True, default=None, **kwargs): """ Create a new Parameter and add it to the optimization problem @ In, name, str, name used to define Pyomo.Param parameter, self._model.name can be used to retrieve this parameter @ In, index, list-like, index for the parameter @ In, values, dict, {index:value}, the index will be tuple for 2 or high dimensions @ In, mutable, boolean, True if the parameter is mutable @ In, default, float, the value absent any other specification @ In, kwargs, dict, other related parameters @ Out, None """ self._model.add_component( name, pyomo.Param(index, name=name, mutable=mutable, default=default, **kwargs)) if mutable: if values is not None: var = self.getComponent(name) if index is not None: for i in index: var[i] = values[i] else: var[index] = values[index] else: raise IOError( '"values" should be provided when trying to add new paramter "{}"' .format(name)) else: raise IOError( 'Parameter "{}" need to be defined as mutable in order to change the value of this paramter dynamically.' .format(name))
def test_abstract_model_example(): import pyomo.environ as pyomo import os def square(m): return pyomo.quicksum((m.x[i] - 0.5)**2 for i in m.x) abstract_model = pyomo.AbstractModel() abstract_model.F = pyomo.Set() abstract_model.Xmin = pyomo.Param(abstract_model.F, within=pyomo.Reals, default=0.0) abstract_model.x = pyomo.Var(abstract_model.F, within=pyomo.Reals) abstract_model.constraints = pyomo.Constraint( abstract_model.F, rule=lambda m, i: m.x[i] >= m.Xmin[i]) abstract_model.obj = pyomo.Objective(rule=square) import nevergrad as ng import nevergrad.functions.pyomo as ng_pyomo # Load the values of the parameters from external file dirname = os.path.dirname(__file__) data_path = os.path.join(dirname, "test_model_1.dat") # DOC_ABSTRACT_100 data = pyomo.DataPortal() data.load(filename=data_path, model=abstract_model) model = abstract_model.create_instance(data) # DOC_ABSTRACT_101 func = ng_pyomo.Pyomo(model) optimizer = ng.optimizers.OnePlusOne(parametrization=func.parametrization, budget=200) recommendation = optimizer.minimize(func.function) np.testing.assert_almost_equal(recommendation.kwargs['x["New York"]'], model.Xmin["New York"], decimal=1) np.testing.assert_almost_equal(recommendation.kwargs['x["Hong Kong"]'], model.Xmin["Hong Kong"], decimal=1)
def test6c(self): # All variables used in an expression # One of the Integer variables looks like a binary M = pe.ConcreteModel() M.p = pe.Param(initialize=1) M.x = pe.Var() M.y = pe.Var([1, 2], within=pe.Binary) M.z = pe.Var([3, 4, 5], within=pe.Integers) M.z[4].setlb(0) M.z[4].setub(1) M.o = pe.Objective(expr=M.x + sum(M.y[i] for i in M.y) + sum(M.z[i] for i in M.z)) #M.c1 = pe.Constraint(expr=M.p == 0) Changed in Pyomo 6.0 var = {} try: tree = collect_multilevel_tree(M, var) self.fail("Expected AssertionError") except AssertionError: pass
def _prepare_pyomo_function1(self): model1 = pyo.AbstractModel() model1.m = pyo.Param( within=pyo.NonNegativeIntegers) # количество ограничений model1.n = pyo.Param( within=pyo.NonNegativeIntegers) # количество переменных model1.I = pyo.RangeSet(1, model1.m) # индексы ограничений model1.J = pyo.RangeSet(1, model1.n) # индексы переменных model1.a = pyo.Param(model1.I, model1.J) # объявляем матрицу ограничений model1.b = pyo.Param(model1.I) # правые части model1.c = pyo.Param(model1.J) # коэффициенты цф model1.lb = pyo.Param(model1.J) # нижние границы model1.sense = pyo.Param(model1.I) # знаки в ограничениях # the next line declares a variable indexed by the set J model1.x = pyo.Var(model1.J) def obj_expression(m): return pyo.summation(m.c, m.x) model1.OBJ = pyo.Objective(rule=obj_expression) def ax_constraint_rule(m, i): if m.sense[i] == -1: return sum(m.a[i, j] * m.x[j] for j in m.J) <= m.b[i] if m.sense[i] == 0: return sum(m.a[i, j] * m.x[j] for j in m.J) == m.b[i] if m.sense[i] == 1: return sum(m.a[i, j] * m.x[j] for j in m.J) >= m.b[i] # the next line creates one constraint for each member of the set model.I model1.AxbConstraint = pyo.Constraint(model1.I, rule=ax_constraint_rule) def bounds_rule(m, j): return (m.lb[j], m.x[j], None) model1.boundx = pyo.Constraint(model1.J, rule=bounds_rule) self._inverse_cost_vector_model = model1
def get_factory(): tree = networkx.DiGraph() tree.add_node("r", variables=["x"], cost="t0_cost") for i in range(3): tree.add_node("s"+str(i), variables=["Y","stale","fixed"], cost="t1_cost", bundle="b"+str(i)) tree.add_edge("r", "s"+str(i), weight=1.0/3) model = aml.ConcreteModel() model.x = aml.Var() model.Y = aml.Var([1], bounds=(None, 1)) model.stale = aml.Var(initialize=0.0) model.fixed = aml.Var(initialize=0.0) model.fixed.fix() model.p = aml.Param(mutable=True) model.t0_cost = aml.Expression(expr=model.x) model.t1_cost = aml.Expression(expr=model.Y[1]) model.o = aml.Objective(expr=model.t0_cost + model.t1_cost) model.c = aml.ConstraintList() model.c.add(model.x >= 1) model.c.add(model.Y[1] >= model.p) def _create_model(scenario_name, node_names): m = model.clone() if scenario_name == "s0": m.p.value = 0.0 elif scenario_name == "s1": m.p.value = 1.0 else: assert(scenario_name == "s2") m.p.value = 2.0 return m return ScenarioTreeInstanceFactory( model=_create_model, scenario_tree=tree)
def create_warehouse_linear_expr(num_locations=50, num_customers=50): N = list(range(num_locations)) # warehouse locations M = list(range(num_customers)) # customers d = dict() # distances from warehouse locations to customers for n in N: for m in M: d[n, m] = np.random.randint(low=1, high=100) max_num_warehouses = 2 model = pyo.ConcreteModel(name="(WL)") model.P = pyo.Param(initialize=max_num_warehouses, mutable=True) model.x = pyo.Var(N, M, bounds=(0, 1)) model.y = pyo.Var(N, bounds=(0, 1)) def obj_rule(mdl): return sum(d[n, m] * mdl.x[n, m] for n in N for m in M) model.obj = pyo.Objective(rule=obj_rule) def demand_rule(mdl, m): return sum(mdl.x[n, m] for n in N) == 1 model.demand = pyo.Constraint(M, rule=demand_rule) def warehouse_active_rule(mdl, n, m): expr = LinearExpression(constant=0, linear_coefs=[1, -1], linear_vars=[mdl.x[n, m], mdl.y[n]]) return expr <= 0 model.warehouse_active = pyo.Constraint(N, M, rule=warehouse_active_rule) def num_warehouses_rule(mdl): return sum(mdl.y[n] for n in N) <= model.P model.num_warehouses = pyo.Constraint(rule=num_warehouses_rule) return model
def P_pf_block_rule(block): #------------------------------LOCAL VARIABLES------------------------------ block.s_L = pe.Var(within=pe.NonNegativeReals, initialize=0) #,bounds=(0,1)) block.s_V = pe.Var(within=pe.NonNegativeReals, initialize=0) block.pf = pe.Var(within=pe.NonNegativeReals, initialize=0) #-----------------------------LOCAL parameters------------------------------ block.rho = pe.Param(initialize=1, mutable=True) print('>', 'Importing MPCC_P_Reg Blocks......') print('>', 'Adding the following local variable:') print('-' * 50) for i in block.component_objects(pe.Var, active=True): print('|', i) for i in block.component_objects(pe.Param, active=True): print('|', i) print('-' * 50) print('>', 'Spliting pressure used in VLE') print('') #------------------------------MPCC equations------------------------------- def penalty_rule(block): return block.pf >= block.rho*(sum(block.parent_block().L[s] for s in block.parent_block().outlet)*block.s_L \ + sum(block.parent_block().V[s] for s in block.parent_block().outlet)*block.s_V) block.penalty_con = pe.Constraint(rule=penalty_rule) #-----------------------------Global equations------------------------------ block.parent_block().VLE_block.del_component( block.parent_block().VLE_block.pressure_equal_con) def pressure_equal_rule(block): return block.parent_block().VLE_block.P_VLE - block.parent_block( ).P == block.s_L - block.s_V block.pressure_equal_con = pe.Constraint(rule=pressure_equal_rule)
def createPyomoModel(pts,cap): #preparacao dos dados C = dist(pts) Cdic = matrixToDic(C) demTotal = sum(pts[i][2] for i in range(1, len(pts))) dem = [pts[j][2] for j in range(len(pts))] model = env.ConcreteModel() model.pts = pts model.name = 'PCV' #criacao dos conjuntos model.V = env.Set(initialize=range(len(pts)),doc='conjunto dos vertices') model.Vs0= env.Set(initialize=range(1,len(pts)), doc='conjunto dos vertices sem a origem') model.x = env.Var(model.V,model.V,within=env.Binary,doc='se o arco (i,j) eh usado ou nao') model.c = env.Param(model.V,model.V,initialize=Cdic,doc='custo do arco (i,j)') #funcao objetvo model.objective = env.Objective(rule=lambda model: sum(model.x[i,j]*model.c[i,j] for i in model.V for j in model.V if i!=j) ,sense=env.minimize) #restricoes de designacao / assingment model.leaving = env.Constraint(model.Vs0, rule=lambda model,i:sum(model.x[i,j] for j in model.V if i!=j) ==1) model.incoming = env.Constraint(model.Vs0, rule=lambda model, j: sum(model.x[i,j] for i in model.V if i != j) == 1) #remocao dos subcirclos e limitacao da capacidade model.y = env.Var(model.V, model.V, within=env.NonNegativeIntegers, doc='qtd. de comodities trans. de (i,j)') model.c1 = env.Constraint(expr=sum(model.y[0,i] for i in model.V) == demTotal, doc='todal da demanda de comodities saindo da origem') model.c2 = env.Constraint(expr=sum(model.y[i,0] for i in model.V) == 0, doc='zero comodite volta para a origem') model.c3 = env.Constraint(model.V,model.V,rule=lambda model,i,j:model.y[i,j]<=demTotal*model.x[i,j]) model.c4 = env.Constraint(model.Vs0, rule=lambda model,j:sum(model.y[i,j] for i in model.V if (i!=j)) - sum(model.y[j,i] for i in model.V if (i!=j)) == dem[j], doc='cada cliente absorve sua demanda de comodite') model.c5 = env.Constraint(model.V, rule=lambda model, i: model.y[0, i] <= cap, doc='cada rota nao pode fornecer mais do que a capacidade') return model
def test_univariate_log(self): m = pe.ConcreteModel() m.p = pe.Param(initialize=-1, mutable=True) m.x = pe.Var(bounds=(0.5, 1.5)) m.y = pe.Var() m.z = pe.Var(bounds=(0, None)) m.c = coramin.relaxations.PWUnivariateRelaxation() m.c.build(x=m.x, w=m.y, relaxation_side=coramin.utils.RelaxationSide.BOTH, shape=coramin.utils.FunctionShape.CONCAVE, f_x_expr=pe.log(m.x)) m.c.rebuild() m.c2 = pe.ConstraintList() m.c2.add(m.z >= m.y - m.p) m.c2.add(m.z >= m.p - m.y) m.obj = pe.Objective(expr=m.z) opt = pe.SolverFactory('glpk') for xval in [0.5, 0.75, 1, 1.25, 1.5]: pval = math.log(xval) m.x.fix(xval) m.p.value = pval res = opt.solve(m, tee=False) self.assertTrue(res.solver.termination_condition == pe.TerminationCondition.optimal) self.assertAlmostEqual(m.y.value, m.p.value, 6)
def __setup_model(self): # Number of timestamps self.model.n_timestamps = pyo.Param(domain=pyo.PositiveIntegers) # Number of PV profiles self.model.n_pv = pyo.Param(domain=pyo.NonNegativeIntegers) # Number of wind profiles self.model.n_wind = pyo.Param(domain=pyo.NonNegativeIntegers) # Number of loads of type 1 self.model.n_load_t1 = pyo.Param(domain=pyo.NonNegativeIntegers) # Number of loads of type 2 self.model.n_load_t2 = pyo.Param(domain=pyo.NonNegativeIntegers) # Number of loads of type 3 self.model.n_load_t3 = pyo.Param(domain=pyo.NonNegativeIntegers) # Number of CHP profiles self.model.n_chp = pyo.Param(domain=pyo.NonNegativeIntegers) # Storage - 1: yes, 0: no self.model.storage = pyo.Param(domain=pyo.Binary) self.model.T = pyo.RangeSet(0, self.model.n_timestamps - 1) # 0..95 self.model.PV = pyo.RangeSet(0, self.model.n_pv - 1) # 0..n_pv - 1 self.model.WIND = pyo.RangeSet(0, self.model.n_wind - 1) # 0..n_pv - 1 self.model.L1 = pyo.RangeSet(0, self.model.n_load_t1 - 1) # 0..n_t1_loads - 1 self.model.L2 = pyo.RangeSet(0, self.model.n_load_t2 - 1) # 0..n_t2_loads - 1 self.model.L3 = pyo.RangeSet(0, self.model.n_load_t3 - 1) # 0..n_t3_loads - 1 self.model.CHP = pyo.RangeSet(0, self.model.n_chp - 1) # 0..n_chp - 1
def test_mutable_parameter(self): m = _make_simple_model() m.p1 = pyo.Param(mutable=True, initialize=7.0) n_scenario = 2 input_values = ComponentMap([ (m.v3, [1.3, 2.3]), (m.v4, [1.4, 2.4]), (m.p1, [1.5, 2.5]), ]) to_fix = [m.v3, m.v4] to_deactivate = [m.con1] with ParamSweeper(2, input_values, to_fix=to_fix, to_deactivate=to_deactivate) as sweeper: self.assertFalse(m.v1.fixed) self.assertFalse(m.v2.fixed) self.assertTrue(m.v3.fixed) self.assertTrue(m.v4.fixed) self.assertFalse(m.con1.active) self.assertTrue(m.con2.active) self.assertTrue(m.con3.active) for i, (inputs, outputs) in enumerate(sweeper): self.assertIn(m.v3, inputs) self.assertIn(m.v4, inputs) self.assertIn(m.p1, inputs) self.assertEqual(len(inputs), 3) for var, val in inputs.items(): self.assertEqual(var.value, val) self.assertEqual(var.value, input_values[var][i]) # Values have been reset after exit. self.assertIs(m.v3.value, None) self.assertIs(m.v4.value, None) self.assertEqual(m.p1.value, 7.0)
def helper(self, func, bounds_list, relaxation_side, expected_relaxation_side): for lb, ub in bounds_list: m = pe.ConcreteModel() m.x = pe.Var(bounds=(lb, ub)) m.aux = pe.Var() if relaxation_side == coramin.utils.RelaxationSide.BOTH: m.c = pe.Constraint(expr=m.aux == func(m.x)) elif relaxation_side == coramin.utils.RelaxationSide.UNDER: m.c = pe.Constraint(expr=m.aux >= func(m.x)) elif relaxation_side == coramin.utils.RelaxationSide.OVER: m.c = pe.Constraint(expr=m.aux <= func(m.x)) coramin.relaxations.relax(m, in_place=True) rels = list(coramin.relaxations.relaxation_data_objects(m)) self.assertEqual(len(rels), 1) r = rels[0] self.assertEqual(r.relaxation_side, expected_relaxation_side) m.p = pe.Param(mutable=True, initialize=0) m.c2 = pe.Constraint(expr=m.x == m.p) opt = pe.SolverFactory('gurobi_persistent') opt.set_instance(m) for _x in [float(i) for i in np.linspace(lb, ub, 10)]: m.p.value = _x opt.remove_constraint(m.c2) opt.add_constraint(m.c2) if relaxation_side in {coramin.utils.RelaxationSide.BOTH, coramin.utils.RelaxationSide.UNDER}: m.obj = pe.Objective(expr=m.aux) opt.set_objective(m.obj) res = opt.solve() self.assertEqual(res.solver.termination_condition, pe.TerminationCondition.optimal) self.assertLessEqual(m.aux.value, func(_x) + 1e-10) del m.obj if relaxation_side in {coramin.utils.RelaxationSide.BOTH, coramin.utils.RelaxationSide.OVER}: m.obj = pe.Objective(expr=m.aux, sense=pe.maximize) opt.set_objective(m.obj) res = opt.solve() self.assertEqual(res.solver.termination_condition, pe.TerminationCondition.optimal) self.assertGreaterEqual(m.aux.value, func(_x) - 1e-10) del m.obj
def test_set_odes_rule(self): builder = TemplateBuilder() # define explicit system of ODEs def rule_odes(m, t): exprs = dict() exprs['A'] = -m.P['k'] * m.Z[t, 'A'] exprs['B'] = m.P['k'] * m.Z[t, 'A'] return exprs builder.set_odes_rule(rule_odes) m = pe.ConcreteModel() m.P = pe.Param(['k'], initialize=0.01) m.t = dae.ContinuousSet(bounds=(0, 1)) m.Z = pe.Var(m.t, ['A', 'B']) self.assertIsInstance(builder._odes(m, 0), dict) def rule(x, y, z): return x + y + z self.assertRaises(RuntimeError, builder.set_odes_rule, rule)
def output_datarate_optimization_PYOMO(q, w, N, M, P, T_s, U_max=1000, Q_max=1, tol=1e-7): if N == 0: return [] m = pyo.ConcreteModel() m.N = pyo.RangeSet(0, N - 1) m.M = pyo.RangeSet(0, M - 1) m.q = pyo.Param(m.N, initialize={i: q[i] for i in m.N}, within=pyo.Reals) m.w = pyo.Param(m.N, initialize={i: w[i] for i in m.N}, within=pyo.NonNegativeReals) m.P = pyo.Param(m.N, m.M, initialize={(i, j): P[i][j] for j in m.M for i in m.N}, within=pyo.NonNegativeReals) m.T_s = pyo.Param(initialize=T_s, within=pyo.NonNegativeReals) m.U_max = pyo.Param(initialize=U_max, within=pyo.NonNegativeReals) m.Q_max = pyo.Param(initialize=Q_max, within=pyo.NonNegativeReals) m.u_k = pyo.Var(m.N, m.M, domain=pyo.NonNegativeReals) m.visible_basestation_constraint = pyo.Constraint( m.N, m.M, rule=visible_basestation_constraint_rule) m.max_U_constraint = pyo.Constraint(m.M, rule=max_U_constraint_rule) m.queue_constraint_lower = pyo.Constraint(m.N, rule=queue_constraint_lower_rule) m.queue_constraint_upper = pyo.Constraint(m.N, rule=queue_constraint_upper_rule) m.obj = pyo.Objective(rule=obj_rule) opt = pyo.SolverFactory("ipopt", executable="ipopt-win64\\ipopt.exe") ret = opt.solve(m) u_final = np.zeros((N, M)) for i in range(N): for j in range(M): u_final[i, j] = pyo.value(m.u_k[i, j]) return u_final
def _create_soc_linking_constraint(self): ################################## # Parameters # ################################## self.model.initial_soc = pyomo.Param( doc=self.block_set_name + " initial state-of-charge at beginning of the horizon[-]", within=pyomo.PercentFraction, default=0.5, mutable=True, units=u.dimensionless) ################################## # Constraints # ################################## # Linking time periods together def storage_soc_linking_rule(m, t): if t == self.blocks.index_set().first(): return self.blocks[t].soc0 == self.model.initial_soc return self.blocks[t].soc0 == self.blocks[t - 1].soc self.model.soc_linking = pyomo.Constraint( self.blocks.index_set(), doc=self.block_set_name + " state-of-charge block linking constraint", rule=storage_soc_linking_rule)