print('Creating NLP and relaxation') nlp = read_osil('camshape800.osil', objective_prefix='obj_', constraint_prefix='con_') relaxation = coramin.relaxations.relax(nlp, in_place=False, use_fbbt=True, fbbt_options={'deactivate_satisfied_constraints': True, 'max_iter': 2}) # perform decomposition print('Decomposing relaxation') relaxation, component_map = coramin.domain_reduction.decompose_model(relaxation, max_leaf_nnz=1000) # rebuild the relaxations for b in coramin.relaxations.relaxation_data_objects(relaxation, descend_into=True, active=True, sort=True): b.rebuild() # create solvers nlp_opt = pe.SolverFactory('ipopt') rel_opt = pe.SolverFactory('gurobi_persistent') # solve the nlp to get the upper bound print('Solving NLP') res = nlp_opt.solve(nlp) assert res.solver.termination_condition == pe.TerminationCondition.optimal ub = pe.value(coramin.utils.get_objective(nlp)) # solve the relaxation to get the lower bound print('Solving relaxation') rel_opt.set_instance(relaxation) res = rel_opt.solve(save_results=False) assert res.solver.termination_condition == pe.TerminationCondition.optimal lb = pe.value(coramin.utils.get_objective(relaxation)) gap = (ub - lb) / abs(ub) * 100
Author: Carl Laird """ import io import json import pytest import os import os.path import pyomo.environ as pe from pyomo.common.fileutils import this_file_dir from pyomo.common.unittest import assertStructuredAlmostEqual import idaes.core.util.convergence.convergence_base as cb import idaes # See if ipopt is available and set up solver ipopt_available = pe.SolverFactory('ipopt').available() ceval_fixedvar_mutableparam_str = ( 'idaes.core.util.convergence.tests.' 'conv_eval_classes.ConvEvalFixedVarMutableParam') ceval_fixedvar_immutableparam_str = ( 'idaes.core.util.convergence.tests.' 'conv_eval_classes.ConvEvalFixedVarImmutableParam') ceval_unfixedvar_mutableparam_str = ( 'idaes.core.util.convergence.tests.' 'conv_eval_classes.ConvEvalUnfixedVarMutableParam') currdir = this_file_dir() wrtdir = idaes.testing_directory @pytest.mark.unit
def test_power_plant_costing(): # Create a Concrete Model as the top level object m = pyo.ConcreteModel() # Add a flowsheet object to the model m.fs = FlowsheetBlock(default={"dynamic": False}) m.fs.get_costing(year='2018') ########################################################################### # Create costing constraints # ########################################################################### # subcritical PC coal_accounts = ['1.1', '1.2', '1.3'] m.fs.subcritical_PC = pyo.Block() m.fs.subcritical_PC.coal_feed_rate = pyo.Var(initialize=7613.37) # tpd m.fs.subcritical_PC.coal_feed_rate.fix() get_PP_costing(m.fs.subcritical_PC, coal_accounts, m.fs.subcritical_PC.coal_feed_rate, 'tpd', 1) # two-stage, slurry-feed IGCC feedwater_accounts = ['3.1', '3.3', '3.5'] m.fs.IGCC_1 = pyo.Block() m.fs.IGCC_1.feedwater_flow_rate = pyo.Var(initialize=1576062.15) # lb/hr m.fs.IGCC_1.feedwater_flow_rate.fix() get_PP_costing(m.fs.IGCC_1, feedwater_accounts, m.fs.IGCC_1.feedwater_flow_rate, 'lb/hr', 3) # single-stage, slurry-feed, IGCC syngas_accounts = ['6.1', '6.2', '6.3'] m.fs.IGCC_2 = pyo.Block() m.fs.IGCC_2.syngas_flow_rate = pyo.Var(initialize=182335.921) # lb/hr m.fs.IGCC_2.syngas_flow_rate.fix() get_PP_costing(m.fs.IGCC_2, syngas_accounts, m.fs.IGCC_2.syngas_flow_rate, 'lb/hr', 4) # single-stage, dry-feed, IGCC HRSG_accounts = ['7.1', '7.2'] m.fs.IGCC_3 = pyo.Block() m.fs.IGCC_3.HRSG_duty = pyo.Var(initialize=1777.86) # MMBtu/hr m.fs.IGCC_3.HRSG_duty.fix() get_PP_costing(m.fs.IGCC_3, HRSG_accounts, m.fs.IGCC_3.HRSG_duty, 'MMBtu/hr', 5) # NGCC steam_turbine_accounts = ['8.1', '8.2', '8.5'] m.fs.NGCC = pyo.Block() m.fs.NGCC.turbine_power = pyo.Var(initialize=212500) # kW m.fs.NGCC.turbine_power.fix() get_PP_costing(m.fs.NGCC, steam_turbine_accounts, m.fs.NGCC.turbine_power, 'kW', 6) # AUSC PC AUSC_accounts = ['4.9', '8.4'] m.fs.AUSC = pyo.Block() m.fs.AUSC.feedwater_flow = pyo.Var(initialize=3298815.58) # lb/hr m.fs.AUSC.feedwater_flow.fix() get_PP_costing(m.fs.AUSC, AUSC_accounts, m.fs.AUSC.feedwater_flow, 'lb/hr', 7) # add total cost build_flowsheet_cost_constraint(m) # add initialize costing_initialization(m.fs) # try solving solver = pyo.SolverFactory('ipopt') results = solver.solve(m, tee=True) assert results.solver.termination_condition == \ pyo.TerminationCondition.optimal # all numbers come from the NETL excel file # "201.001.001_BBR4 COE Spreadsheet_Rev0U_20190919_njk.xlsm" assert pytest.approx(pyo.value( m.fs.subcritical_PC.costing.total_plant_cost['1.1']), abs=1e-1) == 2379 / 1e3 assert pytest.approx(pyo.value( m.fs.subcritical_PC.costing.total_plant_cost['1.2']), abs=1e-1) == 6588 / 1e3 assert pytest.approx(pyo.value( m.fs.subcritical_PC.costing.total_plant_cost['1.3']), abs=1e-1) == 61409 / 1e3 assert pytest.approx(pyo.value( m.fs.IGCC_1.costing.total_plant_cost['3.1']), abs=1e-1) == 10807 / 1e3 assert pytest.approx(pyo.value( m.fs.IGCC_1.costing.total_plant_cost['3.3']), abs=1e-1) == 2564 / 1e3 assert pytest.approx(pyo.value( m.fs.IGCC_1.costing.total_plant_cost['3.5']), abs=1e-1) == 923 / 1e3 assert pytest.approx(pyo.value( m.fs.IGCC_2.costing.total_plant_cost['6.1']), abs=1e-1) == 117850 / 1e3 assert pytest.approx(pyo.value( m.fs.IGCC_2.costing.total_plant_cost['6.2']), abs=1e-1) == 3207 / 1e3 assert pytest.approx(pyo.value( m.fs.IGCC_2.costing.total_plant_cost['6.3']), abs=1e-1) == 3770 / 1e3 assert pytest.approx(pyo.value( m.fs.IGCC_3.costing.total_plant_cost['7.1']), abs=1e-1) == 53530 / 1e3 assert pytest.approx(pyo.value( m.fs.IGCC_3.costing.total_plant_cost['7.2']), abs=1e-1) == 19113 / 1e3 assert pytest.approx(pyo.value(m.fs.NGCC.costing.total_plant_cost['8.1']), abs=1e-1) == 49468 / 1e3 assert pytest.approx(pyo.value(m.fs.NGCC.costing.total_plant_cost['8.2']), abs=1e-1) == 565 / 1e3 assert pytest.approx(pyo.value(m.fs.NGCC.costing.total_plant_cost['8.5']), abs=1e-1) == 4094 / 1e3 assert pytest.approx(pyo.value(m.fs.AUSC.costing.bare_erected_cost['4.9']), abs=1e-1) == 295509 / 1e3 assert pytest.approx(pyo.value(m.fs.AUSC.costing.bare_erected_cost['8.4']), abs=1e-1) == 57265 / 1e3 return m
def rule_rest1(modelo, i): return sum(modelo.x[i, j] for j in modelo.J) <= modelo.b[i] modelo.rest1 = pyEnv.Constraint(modelo.I, rule=rule_rest1) ##------------------------------------------------------## #Cada cliente ter sua demanda atendida def rule_rest2(modelo, j): return sum(modelo.x[i, j] for i in modelo.I) >= modelo.d[j] modelo.rest2 = pyEnv.Constraint(modelo.J, rule=rule_rest2) ##-------------------------------RESOLUCAO DO MODELO-----------------------------------## solver = pyEnv.SolverFactory('cplex', executable=path) resultado = solver.solve(modelo, tee=True) print('\n-------------------------\n') #modelo.pprint() modelo.objetivo() print(resultado) ##-------------------------PRINT DAS VARIAVEIS DE DECISAO ESCOLHIDAS--------------------## ##(cliente,facilidade) lista = list(modelo.x.keys()) for i in lista: print(i, '--', modelo.x[i]())
def test_farmer(self): class Farmer(object): def __init__(self): self.crops = ['WHEAT', 'CORN', 'SUGAR_BEETS'] self.total_acreage = 500 self.PriceQuota = { 'WHEAT': 100000.0, 'CORN': 100000.0, 'SUGAR_BEETS': 6000.0 } self.SubQuotaSellingPrice = { 'WHEAT': 170.0, 'CORN': 150.0, 'SUGAR_BEETS': 36.0 } self.SuperQuotaSellingPrice = { 'WHEAT': 0.0, 'CORN': 0.0, 'SUGAR_BEETS': 10.0 } self.CattleFeedRequirement = { 'WHEAT': 200.0, 'CORN': 240.0, 'SUGAR_BEETS': 0.0 } self.PurchasePrice = { 'WHEAT': 238.0, 'CORN': 210.0, 'SUGAR_BEETS': 100000.0 } self.PlantingCostPerAcre = { 'WHEAT': 150.0, 'CORN': 230.0, 'SUGAR_BEETS': 260.0 } self.scenarios = [ 'BelowAverageScenario', 'AverageScenario', 'AboveAverageScenario' ] self.crop_yield = dict() self.crop_yield['BelowAverageScenario'] = { 'WHEAT': 2.0, 'CORN': 2.4, 'SUGAR_BEETS': 16.0 } self.crop_yield['AverageScenario'] = { 'WHEAT': 2.5, 'CORN': 3.0, 'SUGAR_BEETS': 20.0 } self.crop_yield['AboveAverageScenario'] = { 'WHEAT': 3.0, 'CORN': 3.6, 'SUGAR_BEETS': 24.0 } self.scenario_probabilities = dict() self.scenario_probabilities['BelowAverageScenario'] = 0.3333 self.scenario_probabilities['AverageScenario'] = 0.3334 self.scenario_probabilities['AboveAverageScenario'] = 0.3333 def create_master(farmer): m = pe.ConcreteModel() m.crops = pe.Set(initialize=farmer.crops, ordered=True) m.scenarios = pe.Set(initialize=farmer.scenarios, ordered=True) m.devoted_acreage = pe.Var(m.crops, bounds=(0, farmer.total_acreage)) m.eta = pe.Var(m.scenarios) for s in m.scenarios: m.eta[s].setlb(-432000 * farmer.scenario_probabilities[s]) m.total_acreage_con = pe.Constraint( expr=sum(m.devoted_acreage.values()) <= farmer.total_acreage) m.obj = pe.Objective(expr=sum( farmer.PlantingCostPerAcre[crop] * m.devoted_acreage[crop] for crop in m.crops) + sum(m.eta.values())) return m def create_subproblem(master, farmer, scenario): m = pe.ConcreteModel() m.crops = pe.Set(initialize=farmer.crops, ordered=True) m.devoted_acreage = pe.Var(m.crops) m.QuantitySubQuotaSold = pe.Var(m.crops, bounds=(0.0, None)) m.QuantitySuperQuotaSold = pe.Var(m.crops, bounds=(0.0, None)) m.QuantityPurchased = pe.Var(m.crops, bounds=(0.0, None)) def EnforceCattleFeedRequirement_rule(m, i): return ( farmer.CattleFeedRequirement[i] <= (farmer.crop_yield[scenario][i] * m.devoted_acreage[i]) + m.QuantityPurchased[i] - m.QuantitySubQuotaSold[i] - m.QuantitySuperQuotaSold[i]) m.EnforceCattleFeedRequirement = pe.Constraint( m.crops, rule=EnforceCattleFeedRequirement_rule) def LimitAmountSold_rule(m, i): return m.QuantitySubQuotaSold[i] + m.QuantitySuperQuotaSold[ i] - (farmer.crop_yield[scenario][i] * m.devoted_acreage[i]) <= 0.0 m.LimitAmountSold = pe.Constraint(m.crops, rule=LimitAmountSold_rule) def EnforceQuotas_rule(m, i): return (0.0, m.QuantitySubQuotaSold[i], farmer.PriceQuota[i]) m.EnforceQuotas = pe.Constraint(m.crops, rule=EnforceQuotas_rule) obj_expr = sum(farmer.PurchasePrice[crop] * m.QuantityPurchased[crop] for crop in m.crops) obj_expr -= sum(farmer.SubQuotaSellingPrice[crop] * m.QuantitySubQuotaSold[crop] for crop in m.crops) obj_expr -= sum(farmer.SuperQuotaSellingPrice[crop] * m.QuantitySuperQuotaSold[crop] for crop in m.crops) m.obj = pe.Objective(expr=farmer.scenario_probabilities[scenario] * obj_expr) complicating_vars_map = pe.ComponentMap() for crop in m.crops: complicating_vars_map[ master.devoted_acreage[crop]] = m.devoted_acreage[crop] return m, complicating_vars_map farmer = Farmer() m = create_master(farmer=farmer) master_vars = list(m.devoted_acreage.values()) m.benders = BendersCutGenerator() m.benders.set_input(master_vars=master_vars, tol=1e-8) for s in farmer.scenarios: subproblem_fn_kwargs = dict() subproblem_fn_kwargs['master'] = m subproblem_fn_kwargs['farmer'] = farmer subproblem_fn_kwargs['scenario'] = s m.benders.add_subproblem(subproblem_fn=create_subproblem, subproblem_fn_kwargs=subproblem_fn_kwargs, master_eta=m.eta[s], subproblem_solver='cplex_direct') opt = pe.SolverFactory('cplex_direct') for i in range(30): res = opt.solve(m, tee=False) cuts_added = m.benders.generate_cut() if len(cuts_added) == 0: break self.assertAlmostEqual(m.devoted_acreage['CORN'].value, 80, 7) self.assertAlmostEqual(m.devoted_acreage['SUGAR_BEETS'].value, 250, 7) self.assertAlmostEqual(m.devoted_acreage['WHEAT'].value, 170, 7)
def rest2(modelo, i): return sum(modelo.Variaveis[i, j] for j in modelo.Indices if j != i) == 1 def rest3(modelo, i, j): if i != j: return modelo.Variaveis2[i] - modelo.Variaveis2[j] + modelo.Variaveis[ i, j] * n <= n - 1 else: return modelo.Variaveis2[i] - modelo.Variaveis2[j] == 0 modelo.rest1 = pyEnv.Constraint(modelo.Indices, rule=rest1) modelo.rest2 = pyEnv.Constraint(modelo.Indices2, rule=rest2) modelo.rest3 = pyEnv.Constraint(modelo.Indices3, modelo.Indices2, rule=rest3) solver = pyEnv.SolverFactory('glpk') result_objetivo = solver.solve(modelo, tee=True) lista = list(modelo.Variaveis.keys()) print() print() print('Variaveis: ') print() for i in lista: print(i, '---', modelo.Variaveis[i]()) print() print('Valor da função objetivo =', modelo.Objetivo()) print()
def test_linear_scaling(self): model = pyo.ConcreteModel() model.x = pyo.Var([1, 2, 3], bounds=(-10, 10), initialize=5.0) model.z = pyo.Var(bounds=(10, 20)) model.obj = pyo.Objective(expr=model.z + model.x[1]) # test scaling of duals as well model.dual = pyo.Suffix(direction=pyo.Suffix.IMPORT) model.rc = pyo.Suffix(direction=pyo.Suffix.IMPORT) def con_rule(m, i): if i == 1: return m.x[1] + 2 * m.x[2] + 1 * m.x[3] == 4.0 if i == 2: return m.x[1] + 2 * m.x[2] + 2 * m.x[3] == 5.0 if i == 3: return m.x[1] + 3.0 * m.x[2] + 1 * m.x[3] == 5.0 model.con = pyo.Constraint([1, 2, 3], rule=con_rule) model.zcon = pyo.Constraint(expr=model.z >= model.x[2]) x_scale = 0.5 obj_scale = 2.0 z_scale = -10.0 con_scale1 = 0.5 con_scale2 = 2.0 con_scale3 = -5.0 zcon_scale = -3.0 unscaled_model = model.clone() unscaled_model.scaling_factor = pyo.Suffix(direction=pyo.Suffix.EXPORT) unscaled_model.scaling_factor[unscaled_model.obj] = obj_scale unscaled_model.scaling_factor[unscaled_model.x] = x_scale unscaled_model.scaling_factor[unscaled_model.z] = z_scale unscaled_model.scaling_factor[unscaled_model.con[1]] = con_scale1 unscaled_model.scaling_factor[unscaled_model.con[2]] = con_scale2 unscaled_model.scaling_factor[unscaled_model.con[3]] = con_scale3 unscaled_model.scaling_factor[unscaled_model.zcon] = zcon_scale scaled_model = pyo.TransformationFactory( 'core.scale_model').create_using(unscaled_model) # print('*** unscaled ***') # unscaled_model.pprint() # print('*** scaled ***') # scaled_model.pprint() glpk_solver = pyo.SolverFactory('glpk') if isinstance(glpk_solver, UnknownSolver) or \ (not glpk_solver.available()): raise unittest.SkipTest("glpk solver not available") glpk_solver.solve(unscaled_model) glpk_solver.solve(scaled_model) # check vars self.assertAlmostEqual(pyo.value(unscaled_model.x[1]), pyo.value(scaled_model.scaled_x[1]) / x_scale, 4) self.assertAlmostEqual(pyo.value(unscaled_model.x[2]), pyo.value(scaled_model.scaled_x[2]) / x_scale, 4) self.assertAlmostEqual(pyo.value(unscaled_model.x[3]), pyo.value(scaled_model.scaled_x[3]) / x_scale, 4) self.assertAlmostEqual(pyo.value(unscaled_model.z), pyo.value(scaled_model.scaled_z) / z_scale, 4) # check var lb self.assertAlmostEqual( pyo.value(unscaled_model.x[1].lb), pyo.value(scaled_model.scaled_x[1].lb) / x_scale, 4) self.assertAlmostEqual( pyo.value(unscaled_model.x[2].lb), pyo.value(scaled_model.scaled_x[2].lb) / x_scale, 4) self.assertAlmostEqual( pyo.value(unscaled_model.x[3].lb), pyo.value(scaled_model.scaled_x[3].lb) / x_scale, 4) # note: z_scale is negative, therefore, the inequality directions swap self.assertAlmostEqual(pyo.value(unscaled_model.z.lb), pyo.value(scaled_model.scaled_z.ub) / z_scale, 4) # check var ub self.assertAlmostEqual( pyo.value(unscaled_model.x[1].ub), pyo.value(scaled_model.scaled_x[1].ub) / x_scale, 4) self.assertAlmostEqual( pyo.value(unscaled_model.x[2].ub), pyo.value(scaled_model.scaled_x[2].ub) / x_scale, 4) self.assertAlmostEqual( pyo.value(unscaled_model.x[3].ub), pyo.value(scaled_model.scaled_x[3].ub) / x_scale, 4) # note: z_scale is negative, therefore, the inequality directions swap self.assertAlmostEqual(pyo.value(unscaled_model.z.ub), pyo.value(scaled_model.scaled_z.lb) / z_scale, 4) # check var multipliers (rc) self.assertAlmostEqual( pyo.value(unscaled_model.rc[unscaled_model.x[1]]), pyo.value(scaled_model.rc[scaled_model.scaled_x[1]]) * x_scale / obj_scale, 4) self.assertAlmostEqual( pyo.value(unscaled_model.rc[unscaled_model.x[2]]), pyo.value(scaled_model.rc[scaled_model.scaled_x[2]]) * x_scale / obj_scale, 4) self.assertAlmostEqual( pyo.value(unscaled_model.rc[unscaled_model.x[3]]), pyo.value(scaled_model.rc[scaled_model.scaled_x[3]]) * x_scale / obj_scale, 4) self.assertAlmostEqual( pyo.value(unscaled_model.rc[unscaled_model.z]), pyo.value(scaled_model.rc[scaled_model.scaled_z]) * z_scale / obj_scale, 4) # check constraint multipliers self.assertAlmostEqual( pyo.value(unscaled_model.dual[unscaled_model.con[1]]), pyo.value(scaled_model.dual[scaled_model.scaled_con[1]]) * con_scale1 / obj_scale, 4) self.assertAlmostEqual( pyo.value(unscaled_model.dual[unscaled_model.con[2]]), pyo.value(scaled_model.dual[scaled_model.scaled_con[2]]) * con_scale2 / obj_scale, 4) self.assertAlmostEqual( pyo.value(unscaled_model.dual[unscaled_model.con[3]]), pyo.value(scaled_model.dual[scaled_model.scaled_con[3]]) * con_scale3 / obj_scale, 4) # put the solution from the scaled back into the original pyo.TransformationFactory('core.scale_model').propagate_solution( scaled_model, model) # compare var values and rc with the unscaled soln for vm in model.component_objects(ctype=pyo.Var, descend_into=True): cuid = pyo.ComponentUID(vm) vum = cuid.find_component_on(unscaled_model) self.assertEqual((vm in model.rc), (vum in unscaled_model.rc)) if vm in model.rc: self.assertAlmostEqual(pyo.value(model.rc[vm]), pyo.value(unscaled_model.rc[vum]), 4) for k in vm: vmk = vm[k] vumk = vum[k] self.assertAlmostEqual(pyo.value(vmk), pyo.value(vumk), 4) self.assertEqual((vmk in model.rc), (vumk in unscaled_model.rc)) if vmk in model.rc: self.assertAlmostEqual(pyo.value(model.rc[vmk]), pyo.value(unscaled_model.rc[vumk]), 4) # compare constraint duals and value for model_con in model.component_objects(ctype=pyo.Constraint, descend_into=True): cuid = pyo.ComponentUID(model_con) unscaled_model_con = cuid.find_component_on(unscaled_model) self.assertEqual((model_con in model.rc), (unscaled_model_con in unscaled_model.rc)) if model_con in model.dual: self.assertAlmostEqual( pyo.value(model.dual[model_con]), pyo.value(unscaled_model.dual[unscaled_model_con]), 4) for k in model_con: mk = model_con[k] umk = unscaled_model_con[k] self.assertEqual((mk in model.dual), (umk in unscaled_model.dual)) if mk in model.dual: self.assertAlmostEqual(pyo.value(model.dual[mk]), pyo.value(unscaled_model.dual[umk]), 4)
def test_basics(self): m = pe.ConcreteModel() m.x = pe.Var(bounds=(-10, 10)) m.y = pe.Var() m.obj = pe.Objective(expr=m.x**2 + m.y**2) m.c1 = pe.Constraint(expr=m.y >= 2 * m.x + 1) opt = pe.SolverFactory('xpress_persistent') opt.set_instance(m) self.assertEqual(opt.get_xpress_attribute('cols'), 2) self.assertEqual(opt.get_xpress_attribute('rows'), 1) res = opt.solve() self.assertAlmostEqual(m.x.value, -0.4, delta=1e-6) self.assertAlmostEqual(m.y.value, 0.2, delta=1e-6) opt.load_duals() self.assertAlmostEqual(m.dual[m.c1], -0.4, delta=1e-6) del m.dual m.c2 = pe.Constraint(expr=m.y >= -m.x + 1) opt.add_constraint(m.c2) self.assertEqual(opt.get_xpress_attribute('cols'), 2) self.assertEqual(opt.get_xpress_attribute('rows'), 2) res = opt.solve(save_results=False, load_solutions=False) self.assertAlmostEqual(m.x.value, -0.4, delta=1e-6) self.assertAlmostEqual(m.y.value, 0.2, delta=1e-6) opt.load_vars() self.assertAlmostEqual(m.x.value, 0, delta=1e-6) self.assertAlmostEqual(m.y.value, 1, delta=2e-6) opt.remove_constraint(m.c2) m.del_component(m.c2) self.assertEqual(opt.get_xpress_attribute('cols'), 2) self.assertEqual(opt.get_xpress_attribute('rows'), 1) self.assertEqual(opt.get_xpress_control('feastol'), 1e-6) res = opt.solve(options={'feastol': '1e-7'}) self.assertEqual(opt.get_xpress_control('feastol'), 1e-7) self.assertAlmostEqual(m.x.value, -0.4, delta=1e-6) self.assertAlmostEqual(m.y.value, 0.2, delta=1e-6) m.x.setlb(-5) m.x.setub(5) opt.update_var(m.x) # a nice wrapper for xpress isn't implemented, # so we'll do this directly x_idx = opt._solver_model.getIndex( opt._pyomo_var_to_solver_var_map[m.x]) lb = [] opt._solver_model.getlb(lb, x_idx, x_idx) ub = [] opt._solver_model.getub(ub, x_idx, x_idx) self.assertEqual(lb[0], -5) self.assertEqual(ub[0], 5) m.x.fix(0) opt.update_var(m.x) lb = [] opt._solver_model.getlb(lb, x_idx, x_idx) ub = [] opt._solver_model.getub(ub, x_idx, x_idx) self.assertEqual(lb[0], 0) self.assertEqual(ub[0], 0) m.x.unfix() opt.update_var(m.x) lb = [] opt._solver_model.getlb(lb, x_idx, x_idx) ub = [] opt._solver_model.getub(ub, x_idx, x_idx) self.assertEqual(lb[0], -5) self.assertEqual(ub[0], 5) m.c2 = pe.Constraint(expr=m.y >= m.x**2) opt.add_constraint(m.c2) self.assertEqual(opt.get_xpress_attribute('cols'), 2) self.assertEqual(opt.get_xpress_attribute('rows'), 2) opt.remove_constraint(m.c2) m.del_component(m.c2) self.assertEqual(opt.get_xpress_attribute('cols'), 2) self.assertEqual(opt.get_xpress_attribute('rows'), 1) m.z = pe.Var() opt.add_var(m.z) self.assertEqual(opt.get_xpress_attribute('cols'), 3) opt.remove_var(m.z) del m.z self.assertEqual(opt.get_xpress_attribute('cols'), 2)
def cons3(m): return 38*m.x13 + 35*m.x23 + 40*m.x33 + M*m.x43 + M*m.x53 >= 800 m.cons3 = py.Constraint(rule = cons3) def cons4(m): return 31*m.x11 + 45*m.x12 + 38*m.x13 <= 400 m.cons4 = py.Constraint(rule = cons4) def cons5(m): return 29*m.x21 + 41*m.x22 + 35*m.x23 <= 600 m.cons5 = py.Constraint(rule = cons5) def cons6(m): return 32*m.x31 + 46*m.x32 + 40*m.x33 <= 400 m.cons6 = py.Constraint(rule = cons6) def cons7(m): return 28*m.x41 + 42*m.x42 + M*m.x43 <= 600 m.cons7 = py.Constraint(rule = cons7) def cons8(m): return 29*m.x51 + 43*m.x52 + M*m.x53 <= 1000 m.cons8 = py.Constraint(rule = cons8) py.SolverFactory("glpk").solve(m) m.pprint() m.display() #shows the constraints m.display() #shows the constraints
# @model: import pyomo.environ as pyo m = pyo.ConcreteModel() m.x = pyo.Var() m.y = pyo.Var() m.obj = pyo.Objective(expr=m.x**2 + m.y**2) m.c = pyo.Constraint(expr=m.y >= -2 * m.x + 5) # @:model # @creation: opt = pyo.SolverFactory('gurobi_persistent') # @:creation # @set_instance: opt.set_instance(m) # @:set_instance # @solve: results = opt.solve() # @:solve print('Objective after solve 1: ', pyo.value(m.obj)) # @add_constraint: m.c2 = pyo.Constraint(expr=m.y >= m.x) opt.add_constraint(m.c2) # @:add_constraint # @solve2: results = opt.solve()
## Criando a Função Objetivo ## modelo.Objetivo = pyEnv.Objective(expr = sum(modelo.Variaveis[i,j] * modelo.Custo_transporte[i,j] for i in modelo.Indices_fabricas for j in modelo.Indices_clientes), sense = pyEnv.minimize) ## Criando as restrições ## def rest1(modelo, i): return sum(modelo.Variaveis[i,j] for j in modelo.Indices_clientes) <= modelo.Suprimentos[i] def rest2(modelo, j): return sum(modelo.Variaveis[i,j] for i in modelo.Indices_fabricas) >= modelo.Demandas[j] modelo.rest1 = pyEnv.Constraint(modelo.Indices_fabricas, rule = rest1) modelo.rest2 = pyEnv.Constraint(modelo.Indices_clientes, rule = rest2) ## Chamando o Solver ## solver = pyEnv.SolverFactory('glpk', executable = '/usr/bin/glpsol') result_objetivo = solver.solve(modelo, tee = True) ## Printando o resultado ## lista = list(modelo.Variaveis.keys()) print() print() print() modelo.Objetivo() print(result_objetivo) print() for i in lista: if modelo.Variaveis[i]() != 0: print(i, '---', modelo.Variaveis[i]()) print() print('Valor da função objetivo =', modelo.Objetivo())
def __init__(self): self.model = pe.ConcreteModel() self.solver = pe.SolverFactory("couenne") self.top = 0
def test_interface_call(self): interface_instance = type(pyo.SolverFactory('mosek_persistent')) alt_1 = pyo.SolverFactory('mosek', solver_io='persistent') self.assertIsInstance(alt_1, interface_instance)
''' # @ Author: Zion Deng # @ Description: Nonlinear problem example 2 minimize: 3*sin(-2pi*z1) + 2z1 +4 + cos(2pi*z2) +z2 ''' import numpy as np import pyomo.environ as pyo from numpy import pi m = pyo.ConcreteModel() m.z1 = pyo.Var(initialize=0.1) m.z2 = pyo.Var(initialize=0.1) m.obj = pyo.Objective(expr=3 * pyo.sin(-2 * pi * m.z1) + 2 * m.z1 + 4 + pyo.cos(2 * pi * m.z2) + m.z2) m.c1 = pyo.Constraint(expr=(-1, m.z1, 1)) m.c2 = pyo.Constraint(expr=(-1, m.z2, 1)) solver = pyo.SolverFactory('ipopt') results = solver.solve(m) print('z1 value: %f, z2 value: %f' % (m.z1(), m.z2()))
def optimal_extraction(ti_controls, sampling_times, model_parameters): m = create_model_hgp(sampling_times) def _objective(m): # return m.a[1] / max(sampling_times) # maximum productivity (moles per time) return m.a[1] # maximum production m.objective = po.Objective(rule=_objective, sense=po.maximize) def _p_vac_cons(m, t): return m.p_vac[t] + 0.01 <= m.p[t] m.p_vac_cons = po.Constraint(m.t, rule=_p_vac_cons) m.p[0].fix(22) # 22 MPa - figure from first result of googling "pressure in ghawar field" m.T.fix(360) # 360 Kelvin - taken from (Bruno Stenger; Tony Pham; Nabeel Al-Afaleg; Paul Lawrence GeoArabia (2003) 8 (1): 9–42.) m.tau.fix(max(sampling_times)) # hours m.v.fix(model_parameters[0]) m.mu.fix(model_parameters[1]) m.L.fix(4500) m.R.fix(0.25) discretizer = po.TransformationFactory("dae.collocation") discretizer.apply_to(m, nfe=51, ncp=3) discretizer.reduce_collocation_points(m, var=m.p_vac, ncp=1, contset=m.t) solver = po.SolverFactory("ipopt") result = solver.solve(m) t = [po.value(t) * max(sampling_times) / 24 for t in m.t] p = [po.value(m.p[t]) for t in m.t] a = [po.value(m.a[t]) for t in m.t] q = [po.value(m.q[t]) for t in m.t] p_vac = [po.value(m.p_vac[t]) for t in m.t] if True: fig = plt.figure() axes = fig.add_subplot(111) axes.plot(t, p, label="Pressure in Reservoir (MPa)") axes.plot(t, p_vac, label="Outlet Pressure (MPa)") axes.set_xlabel("Time (Days)") axes.set_ylabel("Pressure (MPa)") axes.legend() fig.tight_layout() fig2 = plt.figure() axes2 = fig2.add_subplot(111) axes2.plot(t, np.asarray(a) * 1e9, label="Accumulated Production") axes2.set_xlabel("Time (Days)") axes2.set_ylabel(r"Accumulated Production ($10^{9}$ Moles)") fig2.tight_layout() fig3 = plt.figure() axes3 = fig3.add_subplot(111) axes3.plot(t, q) axes3.set_xlabel("Time (Days)") axes3.set_ylabel(r"Gas Flowrate $(10^{12} m^{3} / day)$") fig3.tight_layout() # fig4 = plt.figure() # axes4 = fig4.add_subplot(111) # axes4.set_xlabel("Time (Days)") # axes4.set_ylabel(r"Outlet Pressure (MPa)") # axes4.plot(t, p_vac) # fig4.tight_layout() print(f"Productivity: {po.value(m.a[1]) * 1e9 / max(sampling_times)} Billion moles per day") return t, p, a
class TestDecompose(unittest.TestCase): def helper(self, case, min_partition_ratio, expected_termination): test_dir = os.path.dirname(os.path.abspath(__file__)) pglib_dir = os.path.join(test_dir, 'pglib-opf-master') if not os.path.isdir(pglib_dir): get_pglib_opf(download_dir=test_dir) md = ModelData.read(filename=os.path.join(pglib_dir, case)) m, scaled_md = create_rsv_acopf_model(md) relaxed_m = coramin.relaxations.relax( m, in_place=False, use_fbbt=True, fbbt_options={ 'deactivate_satisfied_constraints': True, 'max_iter': 2 }) (decomposed_m, component_map, termination_reason) = decompose_model(model=relaxed_m, max_leaf_nnz=1000, min_partition_ratio=1.4, limit_num_stages=True) self.assertEqual(termination_reason, expected_termination) for r in coramin.relaxations.relaxation_data_objects(block=relaxed_m, descend_into=True, active=True, sort=True): r.rebuild(build_nonlinear_constraint=True) for r in coramin.relaxations.relaxation_data_objects( block=decomposed_m, descend_into=True, active=True, sort=True): r.rebuild(build_nonlinear_constraint=True) opt = pe.SolverFactory('ipopt') res = opt.solve(m, tee=False) relaxed_res = opt.solve(relaxed_m, tee=False) decomposed_res = opt.solve(decomposed_m, tee=False) self.assertEqual(res.solver.termination_condition, pe.TerminationCondition.optimal) self.assertEqual(relaxed_res.solver.termination_condition, pe.TerminationCondition.optimal) self.assertEqual(decomposed_res.solver.termination_condition, pe.TerminationCondition.optimal) obj = get_objective(m) relaxed_obj = get_objective(relaxed_m) decomposed_obj = get_objective(decomposed_m) val = pe.value(obj.expr) relaxed_val = pe.value(relaxed_obj.expr) decomposed_val = pe.value(decomposed_obj.expr) relaxed_rel_diff = abs(val - relaxed_val) / val decomposed_rel_diff = abs(val - decomposed_val) / val self.assertAlmostEqual(relaxed_rel_diff, 0) self.assertAlmostEqual(decomposed_rel_diff, 0) relaxed_vars = list( coramin.relaxations.nonrelaxation_component_data_objects( relaxed_m, pe.Var, sort=True, descend_into=True)) relaxed_cons = list( coramin.relaxations.nonrelaxation_component_data_objects( relaxed_m, pe.Constraint, active=True, sort=True, descend_into=True)) relaxed_rels = list( coramin.relaxations.relaxation_data_objects(relaxed_m, descend_into=True, active=True, sort=True)) decomposed_vars = list( coramin.relaxations.nonrelaxation_component_data_objects( decomposed_m, pe.Var, sort=True, descend_into=True)) decomposed_cons = list( coramin.relaxations.nonrelaxation_component_data_objects( decomposed_m, pe.Constraint, active=True, sort=True, descend_into=True)) decomposed_rels = list( coramin.relaxations.relaxation_data_objects(decomposed_m, descend_into=True, active=True, sort=True)) linking_cons = list() for stage in range(decomposed_m.num_stages()): for block in decomposed_m.stage_blocks(stage): if not block.is_leaf(): linking_cons.extend(block.linking_constraints.values()) relaxed_vars_mapped = list() for i in relaxed_vars: relaxed_vars_mapped.append(component_map[i]) var_diff = ComponentSet(decomposed_vars) - ComponentSet( relaxed_vars_mapped) vars_in_linking_cons = ComponentSet() for c in linking_cons: for v in identify_variables(c.body, include_fixed=True): vars_in_linking_cons.add(v) for v in var_diff: self.assertIn(v, vars_in_linking_cons) var_diff = ComponentSet(relaxed_vars_mapped) - ComponentSet( decomposed_vars) self.assertEqual(len(var_diff), 0) self.assertEqual( len(relaxed_vars) + len(linking_cons), len(decomposed_vars)) self.assertEqual( len(relaxed_cons) + len(linking_cons), len(decomposed_cons)) self.assertEqual(len(relaxed_rels), len(decomposed_rels))
def pyomosim(data): # Define rate parameters kco = 35 kst = 1.5 sparam = 1.0 flow = 1.0 vol = 1.0 gc = .008314 # Define kinetic rate parameters k = params[0] E = params[1] # define UB for concentration #nound_ub = 20 # pyomo solver options opt = pyo.SolverFactory('baron') cracmodel = pyo.ConcreteModel() ca0, cb0, cc0, cd0, cf0, cg0, ch0, ci0, cj0, T = [ float(v) for v in data ] bound_ub = 100.0 # Define cracmodel variables # A = Eb , B = St , C = Bz , D = Et, E = Tl, F = Me, G = Water, H = H2 I = CO2, J = N2 cracmodel.a = pyo.Var(domain=pyo.NonNegativeReals, bounds=(0, bound_ub), initialize=ca0) cracmodel.b = pyo.Var(domain=pyo.NonNegativeReals, bounds=(0, bound_ub), initialize=cb0) cracmodel.c = pyo.Var(domain=pyo.NonNegativeReals, bounds=(0, bound_ub), initialize=cc0) cracmodel.d = pyo.Var(domain=pyo.NonNegativeReals, bounds=(0, bound_ub), initialize=cd0) cracmodel.f = pyo.Var(domain=pyo.NonNegativeReals, bounds=(0, bound_ub), initialize=cf0) cracmodel.g = pyo.Var(domain=pyo.NonNegativeReals, bounds=(0, bound_ub), initialize=cg0) cracmodel.h = pyo.Var(domain=pyo.NonNegativeReals, bounds=(0, bound_ub), initialize=ch0) cracmodel.i = pyo.Var(domain=pyo.NonNegativeReals, bounds=(0, bound_ub), initialize=ci0) cracmodel.j = pyo.Var(domain=pyo.NonNegativeReals, bounds=(0, bound_ub), initialize=cj0) cracmodel.r1 = pyo.Var(domain=pyo.Reals) cracmodel.r2 = pyo.Var(domain=pyo.Reals) cracmodel.r4 = pyo.Var(domain=pyo.Reals) cracmodel.r5 = pyo.Var(domain=pyo.Reals) def keq(T): return pyo.exp(0.1 + (300 / T)) # return pyo.exp(-1.0*(122700-126.3*T-0.002194*T**2)/(gc*T)) * sparam # define reaction rate variable def fr1(cracmodel): # A <> B + H return cracmodel.r1 == k[0] * pyo.exp(-(E[0] / (gc)) * ( (1 / T) - (1 / Tr))) * (cracmodel.a - (cracmodel.b * cracmodel.h) / keq(T)) * (1.0 / ( (1 + kst * cracmodel.b) * (1 + kco * cracmodel.i))) def fr2(cracmodel): # A > C + D return cracmodel.r2 == k[1] * pyo.exp(-(E[1] / (gc)) * ( (1 / T) - (1 / Tr))) * cracmodel.a * (1.0 / (1 + kco * cracmodel.i)) def fr4(cracmodel): # D + 2H > 2F return cracmodel.r4 == k[2] * pyo.exp(-(E[2] / (gc)) * ( (1 / T) - (1 / Tr))) * cracmodel.d * cracmodel.h def fr5(cracmodel): # F+G > I + 4H return cracmodel.r5 == k[3] * pyo.exp(-(E[3] / (gc)) * ( (1 / T) - (1 / Tr))) * cracmodel.f * cracmodel.g cracmodel.er1 = pyo.Constraint(rule=fr1) cracmodel.er2 = pyo.Constraint(rule=fr2) cracmodel.er4 = pyo.Constraint(rule=fr4) cracmodel.er5 = pyo.Constraint(rule=fr5) cracmodel.sets = pyo.RangeSet(9) cracmodel.dum = pyo.Var(cracmodel.sets, domain=pyo.Reals) def fra(cracmodel): # A - 1,2,3 return cracmodel.dum[ 1] == ca0 - cracmodel.a - cracmodel.r1 - cracmodel.r2 def frb(cracmodel): # B - 1 return cracmodel.dum[2] == cb0 - cracmodel.b + cracmodel.r1 def frc(cracmodel): # C - 2 return cracmodel.dum[3] == cc0 - cracmodel.c + cracmodel.r2 def frd(cracmodel): # D - 2,4 return cracmodel.dum[ 4] == cd0 - cracmodel.d + cracmodel.r2 - cracmodel.r4 def frf(cracmodel): # F - 3,4,5 return cracmodel.dum[ 5] == cf0 - cracmodel.f + 2 * cracmodel.r4 - cracmodel.r5 def frg(cracmodel): # G - 5 return cracmodel.dum[6] == cg0 - cracmodel.g - 2 * cracmodel.r5 def frh(cracmodel): # H - 1,3,4,5 return cracmodel.dum[ 7] == ch0 - cracmodel.h + cracmodel.r1 - 2 * cracmodel.r4 + 4 * cracmodel.r5 def fri(cracmodel): # I - 5 return cracmodel.dum[8] == ci0 - cracmodel.i + cracmodel.r5 def frj(cracmodel): # J - N2 is inert return cracmodel.dum[9] == cj0 - cracmodel.j cracmodel.era = pyo.Constraint(rule=fra) cracmodel.erb = pyo.Constraint(rule=frb) cracmodel.erc = pyo.Constraint(rule=frc) cracmodel.erd = pyo.Constraint(rule=frd) cracmodel.erf = pyo.Constraint(rule=frf) cracmodel.erg = pyo.Constraint(rule=frg) cracmodel.erh = pyo.Constraint(rule=frh) cracmodel.eri = pyo.Constraint(rule=fri) cracmodel.erj = pyo.Constraint(rule=frj) # minimize square of dummy variables to find steady-state concentrations def objf(cracmodel): return sum(cracmodel.dum[s]**2 for s in cracmodel.sets) cracmodel.OBJ = pyo.Objective(rule=objf) results = opt.solve(cracmodel) cracmodel.solutions.store_to(results) klist = ['a', 'b', 'c', 'd', 'f', 'g', 'h', 'i', 'j'] # Add noise of the specifiec SNR, noise has variance eps ~ N(0,noise*conc) vn = [ results.Solution.Variable[key]['Value'] + np.random.normal( 0, noise * results.Solution.Variable[key]['Value']) for key in klist ] return vn
def _Q_at_theta(self, thetavals): """ Return the objective function value with fixed theta values. Parameters ---------- thetavals: dict A dictionary of theta values. Returns ------- objectiveval: float The objective function value. thetavals: dict A dictionary of all values for theta that were input. solvertermination: Pyomo TerminationCondition Tries to return the "worst" solver status across the scenarios. pyo.TerminationCondition.optimal is the best and pyo.TerminationCondition.infeasible is the worst. """ optimizer = pyo.SolverFactory('ipopt') dummy_tree = lambda: None # empty object (we don't need a tree) dummy_tree.CallbackModule = None dummy_tree.CallbackFunction = self._instance_creation_callback dummy_tree.ThetaVals = thetavals dummy_tree.cb_data = self.callback_data if self.diagnostic_mode: print(' Compute objective at theta = ', str(thetavals)) # start block of code to deal with models with no constraints # (ipopt will crash or complain on such problems without special care) instance = _pysp_instance_creation_callback(dummy_tree, "FOO1", None) try: # deal with special problems so Ipopt will not crash first = next( instance.component_objects(pyo.Constraint, active=True)) except: sillylittle = True else: sillylittle = False # end block of code to deal with models with no constraints WorstStatus = pyo.TerminationCondition.optimal totobj = 0 for snum in self._numbers_list: sname = "scenario_NODE" + str(snum) instance = _pysp_instance_creation_callback( dummy_tree, sname, None) if not sillylittle: if self.diagnostic_mode: print(' Experiment = ', snum) print( ' First solve with with special diagnostics wrapper' ) status_obj, solved, iters, time, regu \ = ipopt_solver_wrapper.ipopt_solve_with_stats(instance, optimizer, max_iter=500, max_cpu_time=120) print( " status_obj, solved, iters, time, regularization_stat = ", str(status_obj), str(solved), str(iters), str(time), str(regu)) results = optimizer.solve(instance) if self.diagnostic_mode: print('standard solve solver termination condition=', str(results.solver.termination_condition)) if results.solver.termination_condition \ != pyo.TerminationCondition.optimal : # DLW: Aug2018: not distinguishing "middlish" conditions if WorstStatus != pyo.TerminationCondition.infeasible: WorstStatus = results.solver.termination_condition objobject = getattr(instance, self._second_stage_cost_exp) objval = pyo.value(objobject) totobj += objval retval = totobj / len(self._numbers_list) # -1?? return retval, thetavals, WorstStatus
model.nominal_eta1 = aml.Param(initialize=eta1, mutable=True) model.nominal_eta2 = aml.Param(initialize=eta2, mutable=True) # constraints + objective model.const1 = aml.Constraint(expr=6*model.x1+3*model.x2+2*model.x3 - model.eta1 == 0) model.const2 = aml.Constraint(expr=model.eta2*model.x1+model.x2-model.x3-1 == 0) model.cost = aml.Objective(expr=model.x1**2 + model.x2**2 + model.x3**2) model.consteta1 = aml.Constraint(expr=model.eta1 == model.nominal_eta1) model.consteta2 = aml.Constraint(expr=model.eta2 == model.nominal_eta2) return model ################################################################# m = create_model(4.5, 1.0) opt = aml.SolverFactory('ipopt') results = opt.solve(m, tee=True) ################################################################# nlp = PyomoNLP(m) x = nlp.x_init() y = compute_init_lam(nlp, x=x) J = nlp.jacobian_g(x) H = nlp.hessian_lag(x, y) M = BlockSymMatrix(2) M[0, 0] = H M[1, 0] = J Np = BlockMatrix(2, 1)
def main(): start_time = dt.datetime.now() # start options casename = "pglib-opf-master/pglib_opf_case14_ieee.m" # pglib_opf_case3_lmbd.m # pglib_opf_case118_ieee.m # pglib_opf_case300_ieee.m # pglib_opf_case2383wp_k.m # pglib_opf_case2000_tamu.m # do not use pglib_opf_case89_pegase egret_path_to_data = "/thirdparty/" + casename number_of_stages = 4 stage_duration_minutes = [5, 15, 30, 30] if len(sys.argv) != number_of_stages + 3: print("Usage: python fourstage.py bf1 bf2 bf3 iters scenperbun(!)") exit(1) branching_factors = [int(sys.argv[1]), int(sys.argv[2]), int(sys.argv[3])] PHIterLimit = int(sys.argv[4]) scenperbun = int(sys.argv[5]) solvername = sys.argv[6] seed = 1134 a_line_fails_prob = 0.1 # try 0.2 for more excitement repair_fct = FixFast verbose = False # end options # create an arbitrary xhat for xhatspecific to use xhat_dict = {"ROOT": "Scenario_1"} for i in range(branching_factors[0]): st1scen = 1 + i * (branching_factors[1] + branching_factors[2]) xhat_dict["ROOT_" + str(i)] = "Scenario_" + str(st1scen) for j in range(branching_factors[2]): st2scen = st1scen + j * branching_factors[2] xhat_dict["ROOT_" + str(i) + '_' + str(j)] = "Scenario_" + str(st2scen) cb_data = dict() cb_data["convex_relaxation"] = True cb_data["epath"] = egret_path_to_data if cb_data["convex_relaxation"]: # for initialization solve solvername = solvername solver = pyo.SolverFactory(solvername) cb_data["solver"] = None ##if "gurobi" in solvername: ##solver.options["BarHomogeneous"] = 1 else: solvername = "ipopt" solver = pyo.SolverFactory(solvername) if "gurobi" in solvername: solver.options["BarHomogeneous"] = 1 cb_data["solver"] = solver md_dict = _md_dict(cb_data) if verbose: print("start data dump") print(list(md_dict.elements("generator"))) for this_branch in md_dict.elements("branch"): print("TYPE=", type(this_branch)) print("B=", this_branch) print("IN SERVICE=", this_branch[1]["in_service"]) print("GENERATOR SET=", md_dict.attributes("generator")) print("end data dump") lines = list() for this_branch in md_dict.elements("branch"): lines.append(this_branch[0]) acstream = np.random.RandomState() cb_data["etree"] = etree.ACTree(number_of_stages, branching_factors, seed, acstream, a_line_fails_prob, stage_duration_minutes, repair_fct, lines) cb_data["acstream"] = acstream all_scenario_names=["Scenario_"+str(i)\ for i in range(1,len(cb_data["etree"].\ rootnode.ScenarioList)+1)] all_nodenames = cb_data["etree"].All_Nonleaf_Nodenames() PHoptions = dict() if cb_data["convex_relaxation"]: PHoptions["solvername"] = solvername if "gurobi" in PHoptions["solvername"]: PHoptions["iter0_solver_options"] = {"BarHomogeneous": 1} PHoptions["iterk_solver_options"] = {"BarHomogeneous": 1} else: PHoptions["iter0_solver_options"] = None PHoptions["iterk_solver_options"] = None else: PHoptions["solvername"] = "ipopt" PHoptions["iter0_solver_options"] = None PHoptions["iterk_solver_options"] = None PHoptions["PHIterLimit"] = PHIterLimit PHoptions["defaultPHrho"] = 1 PHoptions["convthresh"] = 0.001 PHoptions["subsolvedirectives"] = None PHoptions["verbose"] = False PHoptions["display_timing"] = False PHoptions["display_progress"] = True PHoptions["iter0_solver_options"] = None PHoptions["iterk_solver_options"] = None PHoptions["branching_factors"] = branching_factors # try to do something interesting for bundles per rank if scenperbun > 0: nscen = branching_factors[0] * branching_factors[1] PHoptions["bundles_per_rank"] = int((nscen / n_proc) / scenperbun) if rank_global == 0: appfile = "acopf.app" if not os.path.isfile(appfile): with open(appfile, "w") as f: f.write("datetime, hostname, BF1, BF2, seed, solver, n_proc") f.write(", bunperank, PHIterLimit, convthresh") f.write(", PH_IB, PH_OB") f.write(", PH_lastiter, PH_wallclock, aph_frac_needed") f.write(", APH_IB, APH_OB") f.write(", APH_lastiter, APH_wallclock") if "bundles_per_rank" in PHoptions: nbunstr = str(PHoptions["bundles_per_rank"]) else: nbunstr = "0" oline = "\n" + str(start_time) + "," + socket.gethostname() oline += "," + str(branching_factors[0]) + "," + str( branching_factors[1]) oline += ", " + str(seed) + ", " + str(PHoptions["solvername"]) oline += ", " + str(n_proc) + ", " + nbunstr oline += ", " + str(PHoptions["PHIterLimit"]) oline += ", " + str(PHoptions["convthresh"]) with open(appfile, "a") as f: f.write(oline) print(oline) # PH hub PHoptions["tee-rank0-solves"] = True hub_dict = { "hub_class": PHHub, "hub_kwargs": { "options": None }, "opt_class": PH, "opt_kwargs": { "PHoptions": PHoptions, "all_scenario_names": all_scenario_names, "scenario_creator": pysp2_callback, 'scenario_denouement': scenario_denouement, "cb_data": cb_data, "rho_setter": rho_setter.ph_rhosetter_callback, "PH_extensions": None, "all_nodenames": all_nodenames, } } xhat_options = PHoptions.copy() xhat_options['bundles_per_rank'] = 0 # no bundles for xhat xhat_options["xhat_specific_options"] = { "xhat_solver_options": PHoptions["iterk_solver_options"], "xhat_scenario_dict": xhat_dict, "csvname": "specific.csv" } ub2 = { 'spoke_class': XhatSpecificInnerBound, "spoke_kwargs": dict(), "opt_class": PHBase, 'opt_kwargs': { 'PHoptions': xhat_options, 'all_scenario_names': all_scenario_names, 'scenario_creator': pysp2_callback, 'scenario_denouement': scenario_denouement, "cb_data": cb_data, 'all_nodenames': all_nodenames }, } list_of_spoke_dict = [ub2] spcomm, opt_dict = spin_the_wheel(hub_dict, list_of_spoke_dict) if "hub_class" in opt_dict: # we are hub rank if spcomm.opt.rank == spcomm.opt.rank0: # we are the reporting hub rank ph_end_time = dt.datetime.now() IB = spcomm.BestInnerBound OB = spcomm.BestOuterBound print("BestInnerBound={} and BestOuterBound={}".\ format(IB, OB)) with open(appfile, "a") as f: f.write(", " + str(IB) + ", " + str(OB) + ", " + str(spcomm.opt._PHIter)) f.write(", " + str((ph_end_time - start_time).total_seconds()))
# @script: from warehouse_data import * import pyomo.environ as pe import warehouse_function as wf # call function to create model model = wf.create_wl_model(N, M, d, P) # solve the model solver = pe.SolverFactory('glpk') solver_opt = dict() solver_opt['log'] = 'warehouse.log' solver_opt['nointopt'] = None solver.solve(model, options=solver_opt) # look at the solution model.y.pprint() # @:script import os os.remove('warehouse.log')
def find_component(self, n, coeffs_centered): def norm(model): out = 0 for i in range(self.ndata): x_i = np.copy(coeffs_centered[i, :]) pt_i = np.copy(self.coeff_mat[i, :]) center = np.copy(self.bary) PT = [] for s in range(self.nbasis): vector = model.lamb[i] * model.w[s] PT.append(center[s] + vector) for h in range(model.nvar): for s in range(model.nvar): out += (PT[h] - pt_i[h]) * \ self.metric_aug[h, s]*(PT[s] - pt_i[s]) return out model = pyo.ConcreteModel() model.nvar = self.nbasis model.npoints = self.ndata model.w = pyo.Var(np.arange(model.nvar), domain=pyo.Reals, initialize=lambda m, i: self.initialization[i, n]) model.lamb = pyo.Var(np.arange(model.npoints), domain=pyo.Reals, initialize=1) model.obj = pyo.Objective(rule=norm, sense=pyo.minimize) model.costr = pyo.ConstraintList() # costraint ||w||_E=1 aux = 0 for i in range(model.nvar): aux += self.metric_aug[i, i] * model.w[i]**2 for j in range(i): aux += 2 * model.w[i] * model.w[j] * self.metric_aug[i, j] model.costr.add(aux == 1) # monothonicity contstraint for i in range(self.ndata): x_i = np.copy(coeffs_centered[i, :]) center = np.copy(self.bary) for s in range(n): eig = np.copy(self.eig_vecs[:, s]) center += eig * self.coords[i, s] for j in range(self.nbasis - 1): costr = sum([ self.constraints_mat[j, k] * (model.lamb[i] * model.w[k] + center[k]) for k in range(self.nbasis) ]) model.costr.add(costr <= 0) # orthogonality constraints wrt previous components if n > 0: for s in range(n): eig = np.copy(self.eig_vecs[:, s]) angle = 0 for h in range(model.nvar): for k in range(model.nvar): angle += model.w[h] * eig[k] * self.metric_aug[h, k] model.costr.add(angle == 0) solver = pyo.SolverFactory('ipopt') S = solver.solve(model) cost = model.obj() # needed to get argmin # TODO maybe find more intellingent way w_eval = np.ones((model.nvar, )) for key, val in model.w.extract_values().items(): w_eval[key] = val lamb_eval = np.ones((model.npoints, )) for key, val in model.lamb.extract_values().items(): lamb_eval[key] = val return w_eval, lamb_eval
import pyutilib.th as unittest from pyomo.contrib.benders.benders_cuts import BendersCutGenerator import pyomo.environ as pe try: import mpi4py mpi4py_available = True except: mpi4py_available = False try: import numpy as np numpy_available = True except: numpy_available = False ipopt_opt = pe.SolverFactory('ipopt') ipopt_available = ipopt_opt.available(exception_flag=False) cplex_opt = pe.SolverFactory('cplex_direct') cplex_available = cplex_opt.available(exception_flag=False) @unittest.category('mpi') class MPITestBenders(unittest.TestCase): @unittest.skipIf(not mpi4py_available, 'mpi4py is not available.') @unittest.skipIf(not numpy_available, 'numpy is not available.') @unittest.skipIf(not cplex_available, 'cplex is not available.') def test_farmer(self): class Farmer(object): def __init__(self): self.crops = ['WHEAT', 'CORN', 'SUGAR_BEETS'] self.total_acreage = 500
import pyomo.environ as pyo import time size = 500000 start_time = time.time() model = pyo.ConcreteModel() model.set = pyo.RangeSet(0, size) model.x = pyo.Var(model.set, within=pyo.Reals) model.constrList = pyo.ConstraintList() for i in range(size): model.constrList.add(expr = model.x[i] >= 1) model.obj = pyo.Objective(expr=sum(model.x[i] for i in range(size)), sense=pyo.minimize) opt = pyo.SolverFactory('cbc', io_format='python') _time = time.time() res = opt.solve(model, report_timing=True) print("the model buid" time.time() -a) print(">>> total time () in {:.2f}s".format(time.time() - _time)) print(time.time() -a) print(res)
# University Research Corporation, et al. All rights reserved. # # Please see the files COPYRIGHT.txt and LICENSE.txt for full copyright and # license information, respectively. Both files are also available online # at the URL "https://github.com/IDAES/idaes-pse". ############################################################################## __author__ = "John Eslick" import pytest import idaes.generic_models.properties.iapws95 as iapws95 from idaes.generic_models.properties.tests.test_harness import PropertyTestHarness from idaes.generic_models.properties.iapws95 import iapws95_available as prop_available import pyomo.environ as pyo if pyo.SolverFactory('ipopt').available(): solver = pyo.SolverFactory('ipopt') solver.options = {'tol': 1e-6} else: solver = None @pytest.mark.unit @pytest.mark.skipif(not prop_available(), reason="Property lib not available") class TestBasicMix(PropertyTestHarness): def configure(self): self.prop_pack = iapws95.Iapws95ParameterBlock self.param_args = {"phase_presentation": iapws95.PhaseType.MIX} self.prop_args = {} self.has_density_terms = True
def solve(self): opt = pyo.SolverFactory(self.opts.solver_name, solver_io=self.opts.solver_io) opt.options.update(self.opts.solver_opts) self.result = opt.solve(self.model) self.term = self.result.solver.termination_condition self.status = self.result.solver.status
import pytest from idaes.power_generation.costing.power_plant_costing import \ (get_sCO2_unit_cost, get_PP_costing, get_ASU_cost, build_flowsheet_cost_constraint, costing_initialization) from idaes.core.util.model_statistics import (degrees_of_freedom) import pyomo.environ as pyo from idaes.generic_models.properties import iapws95 from idaes.generic_models.properties import swco2 from idaes.core import FlowsheetBlock solver_available = pyo.SolverFactory('ipopt').available() prop_available = iapws95.iapws95_available() prop2_available = swco2.swco2_available() @pytest.mark.component @pytest.mark.solver @pytest.mark.skipif(not prop_available, reason="IAPWS not available") @pytest.mark.skipif(not solver_available, reason="Solver not available") def test_PP_costing(): # Create a Concrete Model as the top level object m = pyo.ConcreteModel() # Add a flowsheet object to the model m.fs = FlowsheetBlock(default={"dynamic": False}) m.fs.get_costing(year='2018')
# @script: import json import pyomo.environ as pyo from warehouse_model import create_wl_model # load the data from a json file with open('warehouse_data.json', 'r') as fd: data = json.load(fd) # call function to create model model = create_wl_model(data, P=2) # create the solver solver = pyo.SolverFactory('glpk') # options can be set directly on the solver solver.options['noscale'] = None solver.options['log'] = 'warehouse.log' solver.solve(model, tee=True) model.y.pprint() # options can also be passed via the solve command myoptions = dict() myoptions['noscale'] = None myoptions['log'] = 'warehouse.log' solver.solve(model, options=myoptions, tee=True) model.y.pprint() # @:script import os os.remove('warehouse.log')
def test_sCO2_costing(): # Create a Concrete Model as the top level object m = pyo.ConcreteModel() # Add a flowsheet object to the model m.fs = FlowsheetBlock(default={"dynamic": False}) m.fs.get_costing(year='2017') # ###################################################### # Primary Heater m.fs.boiler = pyo.Block() m.fs.boiler.heat_duty = pyo.Var(initialize=1461.5e6) m.fs.boiler.heat_duty.fix() m.fs.boiler.temp = pyo.Var(initialize=620) # C m.fs.boiler.temp.fix() get_sCO2_unit_cost(m.fs.boiler, 'Coal-fired heater', m.fs.boiler.heat_duty * (1e-6), temp_C=m.fs.boiler.temp) # ###################################################### # CO2 Turbine m.fs.turbine = pyo.Block() m.fs.turbine.work_isentropic = pyo.Var(initialize=1006.2e6) m.fs.turbine.work_isentropic.fix() m.fs.turbine.temp = pyo.Var(initialize=620) m.fs.turbine.temp.fix() get_sCO2_unit_cost(m.fs.turbine, 'Axial turbine', m.fs.turbine.work_isentropic * (1e-6), temp_C=m.fs.turbine.temp, n_equip=1) # ###################################################### # Generator m.fs.generator = pyo.Block() m.fs.generator.work_isentropic = pyo.Var(initialize=1006.2e6) get_sCO2_unit_cost(m.fs.generator, 'Generator', m.fs.turbine.work_isentropic * (1e-6), n_equip=1) # ###################################################### # High Temperature Recuperator m.fs.HTR = pyo.Block() m.fs.HTR.heat_duty = pyo.Var(initialize=1461e6) # W m.fs.HTR.heat_duty.fix() m.fs.HTR.LMTD = pyo.Var(initialize=21.45) m.fs.HTR.LMTD.fix() m.fs.HTR.temp = pyo.Var(initialize=453) m.fs.HTR.temp.fix() m.fs.HTR.UA = pyo.Var(initialize=1e8) # gives units of W/K @m.fs.Constraint() def HTR_UA_rule(b): return (b.HTR.UA * b.HTR.LMTD == b.HTR.heat_duty) get_sCO2_unit_cost(m.fs.HTR, 'Recuperator', m.fs.HTR.UA, temp_C=m.fs.HTR.temp) # ###################################################### # Low Temperature Recuperator m.fs.LTR = pyo.Block() m.fs.LTR.heat_duty = pyo.Var(initialize=911.7e6) # W m.fs.LTR.heat_duty.fix() m.fs.LTR.LMTD = pyo.Var(initialize=5.21) m.fs.LTR.LMTD.fix() m.fs.LTR.temp = pyo.Var(initialize=216) m.fs.LTR.temp.fix() m.fs.LTR.UA = pyo.Var(initialize=1e8) @m.fs.Constraint() def LTR_UA_rule(b): return (b.LTR.UA * b.LTR.LMTD == b.LTR.heat_duty) get_sCO2_unit_cost(m.fs.LTR, 'Recuperator', m.fs.LTR.UA, temp_C=m.fs.LTR.temp) # ###################################################### # CO2 Cooler, costed using the recouperator not dry cooler m.fs.co2_cooler = pyo.Block() m.fs.co2_cooler.heat_duty = pyo.Var(initialize=739421217) m.fs.co2_cooler.heat_duty.fix() m.fs.co2_cooler.temp = pyo.Var(initialize=81) m.fs.co2_cooler.temp.fix() # Estimating LMTD # Cost from report: $27,780 thousand # Back-calculated UA: 41819213 W/K # Heat duty from report: 2523 MMBTu/hr --> 739421217 W # Estimated LMTD: 17.68 K m.fs.co2_cooler.LMTD = pyo.Var(initialize=5) m.fs.co2_cooler.UA = pyo.Var(initialize=1e5) m.fs.co2_cooler.LMTD.fix(17.68) @m.fs.Constraint() def co2_cooler_UA_rule(b): return (b.co2_cooler.UA * b.co2_cooler.LMTD == b.co2_cooler.heat_duty) get_sCO2_unit_cost(m.fs.co2_cooler, 'Recuperator', m.fs.co2_cooler.UA, temp_C=m.fs.co2_cooler.temp) # ###################################################### # Main Compressor - 5.99 m^3/s in Baseline620 m.fs.main_compressor = pyo.Block() m.fs.main_compressor.flow_vol = pyo.Var(initialize=5.99) m.fs.main_compressor.flow_vol.fix() get_sCO2_unit_cost(m.fs.main_compressor, 'Barrel type compressor', m.fs.main_compressor.flow_vol, n_equip=5.0) # ###################################################### # Main Compressor Motor m.fs.main_compressor_motor = pyo.Block() m.fs.main_compressor_motor.work_isentropic = pyo.Var(initialize=159.7e6) m.fs.main_compressor_motor.work_isentropic.fix() get_sCO2_unit_cost(m.fs.main_compressor_motor, 'Open drip-proof motor', m.fs.main_compressor_motor.work_isentropic * (1e-6), n_equip=5.0) # ###################################################### # Recompressor - 6.89 m^3/s in Baseline620 m.fs.bypass_compressor = pyo.Block() m.fs.bypass_compressor.flow_vol = pyo.Var(initialize=6.89) m.fs.bypass_compressor.flow_vol.fix() get_sCO2_unit_cost(m.fs.bypass_compressor, 'Barrel type compressor', m.fs.bypass_compressor.flow_vol, n_equip=4.0) # ###################################################### # Recompressor Motor m.fs.bypass_compressor_motor = pyo.Block() m.fs.bypass_compressor_motor.work_isentropic = pyo.Var(initialize=124.3e6) m.fs.bypass_compressor_motor.work_isentropic.fix() get_sCO2_unit_cost(m.fs.bypass_compressor_motor, 'Open drip-proof motor', m.fs.bypass_compressor_motor.work_isentropic * (1e-6), n_equip=4.0) # add total cost build_flowsheet_cost_constraint(m) # add initialize costing_initialization(m.fs) # try solving solver = pyo.SolverFactory('ipopt') results = solver.solve(m, tee=True) assert results.solver.termination_condition == \ pyo.TerminationCondition.optimal assert pytest.approx(pyo.value(m.fs.boiler.costing.equipment_cost), abs=1e-1) == 216300 / 1e3 assert pytest.approx(pyo.value(m.fs.turbine.costing.equipment_cost), abs=1e-1) == 13160 / 1e3 assert pytest.approx(pyo.value(m.fs.generator.costing.equipment_cost), abs=1e-1) == 4756 / 1e3 assert pytest.approx(pyo.value(m.fs.HTR.costing.equipment_cost), abs=1e-1) == 40150 / 1e3 assert pytest.approx(pyo.value(m.fs.LTR.costing.equipment_cost), abs=1e-1) == 81860 / 1e3 assert pytest.approx(pyo.value(m.fs.co2_cooler.costing.equipment_cost), abs=1e-1) == 27780 / 1e3 assert pytest.approx(pyo.value( m.fs.main_compressor.costing.equipment_cost), abs=1e-1) == 31640 / 1e3 assert pytest.approx(pyo.value( m.fs.bypass_compressor.costing.equipment_cost), abs=1e-1) == 26360 / 1e3 assert pytest.approx( pyo.value(m.fs.main_compressor_motor.costing.equipment_cost) + pyo.value(m.fs.bypass_compressor_motor.costing.equipment_cost), abs=1e-1) == 29130 / 1e3 assert pytest.approx(pyo.value( m.fs.bypass_compressor.costing.equipment_cost), abs=1e-1) == 26360 / 1e3 return m
from plant_dyn import main_steady import pyomo.environ as pyo import report_steady as rpt import json import data_util as data_module import pandas as pd import idaes.core.util.scaling as iscale if __name__ == "__main__": m = main_steady(load_state="initial_steady.json.gz", save_state="initial_steady.json.gz") solver = pyo.SolverFactory("ipopt") iscale.calculate_scaling_factors(m) solver.solve(m, tee=True) sd = rpt.create_stream_dict(m) sdf = rpt.stream_table(sd, fname="results/streams.csv") tag, tag_format = rpt.create_tags(m, sd) rpt.svg_output(tag, tag_format) rpt.turbine_table(m, fname="results/turbine_table.csv") df, df_meta, bin_stdev = data_module.read_data(model=m) dfs = pd.DataFrame() df.to_csv("binned.csv") for b in bin_stdev: dfs[f"{85+b*5} to {90+b*5} MW"] = bin_stdev[b] dfs.to_csv("stdev.csv")