def _generate_model(self): self.model = ConcreteModel() model = self.model model._name = self.description model.f = Var() model.x = Var(bounds=(1,3)) model.fi = Param([1,2,3],mutable=True) model.fi[1] = 1.0 model.fi[2] = 2.0 model.fi[3] = 0.0 model.xi = Param([1,2,3],mutable=True) model.xi[1] = 1.0 model.xi[2] = 2.0 model.xi[3] = 3.0 model.p = Var(within=NonNegativeReals) model.n = Var(within=NonNegativeReals) model.lmbda = Var([1,2,3]) model.obj = Objective(expr=model.p+model.n) model.c1 = ConstraintList() model.c1.add((0.0, model.lmbda[1], 1.0)) model.c1.add((0.0, model.lmbda[2], 1.0)) model.c1.add(0.0 <= model.lmbda[3]) model.c2 = SOSConstraint(var=model.lmbda, index=[1,2,3], sos=2) model.c3 = Constraint(expr=sum_product(model.lmbda) == 1) model.c4 = Constraint(expr=model.f==sum_product(model.fi,model.lmbda)) model.c5 = Constraint(expr=model.x==sum_product(model.xi,model.lmbda)) model.x = 2.75 model.x.fixed = True # Make an empty SOSConstraint model.c6 = SOSConstraint(var=model.lmbda, index=[1,2,3], sos=2) model.c6.set_items([],[]) assert len(list(model.c6.get_items())) == 0
def _generate_model(self): self.model = ConcreteModel() model = self.model model._name = self.description model.a1 = Param(initialize=1.0, mutable=True) model.a2 = Param([1], initialize=1.0, mutable=True) model.a3 = Param(initialize=1.0, mutable=False) model.a4 = Param([1], initialize=1.0, mutable=False) model.x = Var(within=NonNegativeReals) model.y = Var(within=NonNegativeReals) model.z1 = Var(bounds=(float('-inf'), float('inf'))) model.z2 = Var() model.dummy_expr1 = Expression(initialize=model.a1 * model.a2[1]) model.dummy_expr2 = Expression(initialize=model.y / model.a3 * model.a4[1]) model.inactive_obj = Objective(expr=model.x + 3.0 * model.y + 1.0 + model.z1 - model.z2) model.inactive_obj.deactivate() model.p = Param(mutable=True, initialize=0.0) model.obj = Objective(expr=model.p + model.inactive_obj) model.c1 = Constraint(expr=model.dummy_expr1 <= model.dummy_expr2) model.c2 = Constraint(expr=(2.0, model.x / model.a3 - model.y, 10)) model.c3 = Constraint(expr=(0, model.z1 + 1, 10)) model.c4 = Constraint(expr=(-10, model.z2 + 1, 0))
def test_construct(self): model = AbstractModel() model.a = Set(initialize=[1, 2, 3]) model.A = Param(initialize=1) model.B = Param(model.a) model.x = Var(initialize=1, within=Reals, dense=False) model.y = Var(model.a, initialize=1, within=Reals, dense=False) model.obj = Objective(rule=lambda model: model.x + model.y[1]) model.obj2 = Objective(model.a, rule=lambda model, i: i + model.x + model.y[1]) model.con = Constraint(rule=rule1) model.con2 = Constraint(model.a, rule=rule2) instance = model.create_instance() expr = instance.x + 1 OUTPUT = open(currdir + "/display.out", "w") display(instance, ostream=OUTPUT) display(instance.obj, ostream=OUTPUT) display(instance.x, ostream=OUTPUT) display(instance.con, ostream=OUTPUT) OUTPUT.write(expr.to_string()) model = AbstractModel() instance = model.create_instance() display(instance, ostream=OUTPUT) OUTPUT.close() try: display(None) self.fail("test_construct - expected TypeError") except TypeError: pass self.assertFileEqualsBaseline(currdir + "/display.out", currdir + "/display.txt")
def test_construct2(self): model = AbstractModel() model.a = Set(initialize=[1,2,3]) model.A = Param(initialize=1) model.B = Param(model.a) model.x = Var(initialize=1, within=Reals, dense=True) model.y = Var(model.a, initialize=1, within=Reals, dense=True) model.obj = Objective(rule=lambda model: model.x+model.y[1]) model.obj2 = Objective(model.a,rule=lambda model, i: i+model.x+model.y[1]) model.con = Constraint(rule=rule1) model.con2 = Constraint(model.a, rule=rule2) instance = model.create_instance() expr = instance.x + 1 OUTPUT = open(join(currdir, "display2.out"), "w") display(instance,ostream=OUTPUT) display(instance.obj,ostream=OUTPUT) display(instance.x,ostream=OUTPUT) display(instance.con,ostream=OUTPUT) OUTPUT.write(expr.to_string()) model = AbstractModel() instance = model.create_instance() display(instance,ostream=OUTPUT) OUTPUT.close() try: display(None) self.fail("test_construct - expected TypeError") except TypeError: pass _out, _txt = join(currdir, "display2.out"), join(currdir, "display2.txt") self.assertTrue(cmp(_out, _txt), msg="Files %s and %s differ" % (_out, _txt))
def makeTwoTermDisj_IndexedConstraints_BoundedVars(): """Single two-term disjunction with IndexedConstraints on both disjuncts. """ m = ConcreteModel() m.s = Set(initialize=[1, 2]) m.lbs = Param(m.s, initialize={1: 2, 2: 4}) m.ubs = Param(m.s, initialize={1: 7, 2: 6}) def bounds_rule(m, s): return (m.lbs[s], m.ubs[s]) m.a = Var(m.s, bounds=bounds_rule) def d_rule(disjunct, flag): m = disjunct.model() def true_rule(d, s): return m.a[s] == 0 def false_rule(d, s): return m.a[s] >= 5 if flag: disjunct.c = Constraint(m.s, rule=true_rule) else: disjunct.c = Constraint(m.s, rule=false_rule) m.disjunct = Disjunct([0, 1], rule=d_rule) m.disjunction = Disjunction(expr=[m.disjunct[0], m.disjunct[1]]) return m
def EXTERNAL_initialize_for_admm(manager, scenario): if manager.get_option("verbose"): print("Initializing scenario %s for admm algorithm" % (scenario.name)) admm_block = Block(concrete=True) assert not hasattr(scenario._instance, ".admm") scenario._instance.add_component(".admm", admm_block) # Augment the objective with lagrangian and penalty terms # and weight the original objective by the scenario probability. # The langrangian and penalty terms will be computed after # the parameters are created. user_cost_expression = scenario._instance_cost_expression admm_block.cost_expression = Expression(initialize=\ scenario.probability * user_cost_expression) admm_block.lagrangian_expression = Expression(initialize=0.0) admm_block.penalty_expression = Expression(initialize=0.0) # these are used in the objective, they can be toggled # between the expression above or something else (e.g., 0.0) admm_block.cost_term = Expression(initialize=admm_block.cost_expression) admm_block.lagrangian_term = Expression( initialize=admm_block.lagrangian_expression) admm_block.penalty_term = Expression( initialize=admm_block.penalty_expression) objective_direction = 1 if manager.objective_sense == maximize: objective_direction = -1 scenario._instance_objective.expr = \ admm_block.cost_term + \ admm_block.lagrangian_term * objective_direction + \ admm_block.penalty_term * objective_direction # add objective parameters to admm block for tree_node in scenario.node_list[:-1]: assert not tree_node.is_leaf_node() node_block = Block(concrete=True) admm_block.add_component(tree_node.name, node_block) node_block.node_index_set = Set(ordered=True, initialize=sorted( tree_node._standard_variable_ids)) node_block.z = Param(node_block.node_index_set, initialize=0.0, mutable=True) node_block.y = Param(node_block.node_index_set, initialize=0.0, mutable=True) node_block.rho = Param(node_block.node_index_set, initialize=0.0, mutable=True) for id_ in node_block.node_index_set: varname, index = tree_node._variable_ids[id_] var = scenario._instance.find_component(varname)[index] admm_block.lagrangian_expression.expr += \ node_block.y[id_] * (var - node_block.z[id_]) admm_block.penalty_expression.expr += \ (node_block.rho[id_] / 2.0) * (var - node_block.z[id_])**2 # The objective has changed so flag this if necessary. if manager.preprocessor is not None: manager.preprocessor.objective_updated[scenario.name] = True
def create_nodal_ph_parameters(scenario_tree): for stage in scenario_tree._stages[:-1]: for tree_node in stage._tree_nodes: new_nodal_index_set_name = "PHINDEX_" + str(tree_node._name) new_xbar_parameter_name = "PHXBAR_" + str(tree_node._name) new_blend_parameter_name = "PHBLEND_" + str(tree_node._name) # only create nodal index sets for non-derived variables. new_nodal_index_set = Set(name=new_nodal_index_set_name, initialize=list( tree_node._standard_variable_ids)) for scenario in tree_node._scenarios: instance = scenario._instance # avoid the warnings generated by adding Set to # multiple components, and learn to live with the fact # that these Params will point to some arbitrary # instance as their "parent" in the end new_nodal_index_set._parent = None # Add the shared parameter to the instance instance.add_component(new_nodal_index_set_name, new_nodal_index_set) ### dlw Jan 2014 nochecking=True, mutable=True) new_xbar_parameter = Param(new_nodal_index_set, name=new_xbar_parameter_name, default=0.0, mutable=True) ### dlw Jan 2014 nochecking=True, mutable=True) new_blend_parameter = Param(new_nodal_index_set, name=new_blend_parameter_name, within=Binary, default=False, mutable=True) for scenario in tree_node._scenarios: instance = scenario._instance # avoid the warnings generated by adding Param to # multiple components, and learn to live with the fact # that these Params will point to some arbitrary # instance as their "parent" in the end new_xbar_parameter._parent = None new_blend_parameter._parent = None # Add the shared parameter to the instance instance.add_component(new_xbar_parameter_name, new_xbar_parameter) instance.add_component(new_blend_parameter_name, new_blend_parameter) new_xbar_parameter.store_values(0.0) tree_node._xbars.update(dict.fromkeys(tree_node._xbars, 0.0)) new_blend_parameter.store_values(1) tree_node._blend.update(dict.fromkeys(tree_node._blend, 1))
def makeTwoTermDisj_IndexedConstraints_BoundedVars(): # same concept as above, but bounded variables m = ConcreteModel() m.s = Set(initialize=[1, 2]) m.lbs = Param(m.s, initialize={1: 2, 2: 4}) m.ubs = Param(m.s, initialize={1: 7, 2: 6}) def bounds_rule(m, s): return (m.lbs[s], m.ubs[s]) m.a = Var(m.s, bounds=bounds_rule) def d_rule(disjunct, flag): m = disjunct.model() def true_rule(d, s): return m.a[s] == 0 def false_rule(d, s): return m.a[s] >= 5 if flag: disjunct.c = Constraint(m.s, rule=true_rule) else: disjunct.c = Constraint(m.s, rule=false_rule) m.disjunct = Disjunct([0, 1], rule=d_rule) m.disjunction = Disjunction(expr=[m.disjunct[0], m.disjunct[1]]) return m
def _generate_model(self): self.model = None self.model = ConcreteModel() model = self.model model._name = self.description n = 7 m = 7 model.N = RangeSet(1, n) model.M = RangeSet(1, m) model.c = Param(model.N, rule=c_rule) model.b = Param(model.M, rule=b_rule) model.A = Param(model.M, model.N, rule=A_rule) model.x = Var(model.N, within=NonNegativeReals) model.y = Var(model.M, within=NonNegativeReals) model.cost = Objective(expr=sum_product(model.c, model.x)) model.primalcon = Constraint(model.M, rule=primalcon_rule) #model.dual = Suffix(direction=Suffix.IMPORT) #model.rc = Suffix(direction=Suffix.IMPORT) model.slack = Suffix(direction=Suffix.IMPORT) model.urc = Suffix(direction=Suffix.IMPORT) model.lrc = Suffix(direction=Suffix.IMPORT)
def createParam(self): self.TRF.ind_lx = RangeSet(0, self.lx - 1) self.TRF.ind_ly = RangeSet(0, self.ly - 1) self.TRF.ind_lz = RangeSet(0, self.lz - 1) self.TRF.px0 = Param(self.TRF.ind_lx, mutable=True, default=0) self.TRF.py0 = Param(self.TRF.ind_ly, mutable=True, default=0) self.TRF.pz0 = Param(self.TRF.ind_lz, mutable=True, default=0) self.TRF.ppenaltyComp = Param(mutable=True, default=0)
def create_abstract_model(self): """Build the model <b>object</b>.""" if not self.built: def jk_init(m): return [(j, k) for j in m.J for k in m.K[j]] model = AbstractModel() model.J = Set() model.K = Set(model.J) model.JK = Set(initialize=jk_init, dimen=None) model.y_pred = Param() model.epsilon = Param() model.max_cost = Var() model.w = Param(model.J) model.a = Param(model.JK) model.c = Param(model.JK) model.u = Var(model.JK, within=Binary) # Make sure only one action is on at a time. def c1Rule(m, j): return sum([m.u[j, k] for k in m.K[j]]) == 1 # 2.b: Action sets must flip the prediction of a linear classifier. def c2Rule(m): return sum((m.u[j, k] * m.a[j, k] * m.w[j]) for j, k in m.JK) >= -m.y_pred # instantiate max cost def maxcost_rule(m, j, k): return m.max_cost >= (m.u[j, k] * m.c[j, k]) # Set up objective for total sum. def obj_rule_percentile(m): return sum(m.u[j, k] * m.c[j, k] for j, k in m.JK) # Set up objective for max cost. def obj_rule_max(m): return sum(m.epsilon * m.u[j, k] * m.c[j, k] for j, k in m.JK) + (1 - m.epsilon) * m.max_cost ## set up objective function. if self.mip_cost_type == "max": model.g = Objective(rule=obj_rule_max, sense=minimize) model.c3 = Constraint(model.JK, rule=maxcost_rule) else: model.g = Objective(rule=obj_rule_percentile, sense=minimize) ## model.c1 = Constraint(model.J, rule=c1Rule) model.c2 = Constraint(rule=c2Rule) self.model = model self.built = True return self.model
def define_model(**kwds): model = ConcreteModel() model.x = Var(INDEX_SET, bounds=(-5, 4)) # domain variable model.Fx = Var(INDEX_SET) # range variable model.p = Param(INDEX_SET, initialize=1.0) model.obj = Objective(expr=sum_product(model.Fx), sense=kwds.pop('sense', maximize)) model.piecewise = Piecewise(INDEX_SET, model.Fx, model.x, pw_pts=DOMAIN_PTS, f_rule=F, **kwds) #Fix the answer for testing purposes model.set_answer_constraint1 = Constraint(expr=model.x[1] == -5.0) model.set_answer_constraint2 = Constraint(expr=model.x[2] == -3.0) model.set_answer_constraint3 = Constraint(expr=model.x[3] == -2.5) model.set_answer_constraint4 = Constraint(expr=model.x[4] == -1.5) model.set_answer_constraint5 = Constraint(expr=model.x[5] == 2.0) model.set_answer_constraint6 = Constraint(expr=model.x[6] == 3.5) model.set_answer_constraint7 = Constraint(expr=model.x[7] == 4.0) return model
def CreateAbstractScenarioTreeModel(): from pyomo.core import (AbstractModel, Set, Param, Boolean) model = AbstractModel() # all set/parameter values are strings, representing the # names of various entities/variables. model.Stages = Set(ordered=True) model.Nodes = Set(ordered=True) model.NodeStage = Param(model.Nodes, within=model.Stages, mutable=True) model.Children = Set(model.Nodes, within=model.Nodes, initialize=[], ordered=True) model.ConditionalProbability = Param(model.Nodes, mutable=True) model.Scenarios = Set(ordered=True) model.ScenarioLeafNode = Param(model.Scenarios, within=model.Nodes, mutable=True) model.StageVariables = Set(model.Stages, initialize=[], ordered=True) model.NodeVariables = Set(model.Nodes, initialize=[], ordered=True) model.StageCost = Param(model.Stages, mutable=True) # DEPRECATED model.StageCostVariable = Param(model.Stages, mutable=True) # it is often the case that a subset of the stage variables are strictly "derived" # variables, in that their values are computable once the values of other variables # in that stage are known. it generally useful to know which variables these are, # as it is unnecessary to post non-anticipativity constraints for these variables. # further, attempting to force non-anticipativity - either implicitly or explicitly - # on these variables can cause issues with decomposition algorithms. model.StageDerivedVariables = Set(model.Stages, initialize=[], ordered=True) model.NodeDerivedVariables = Set(model.Nodes, initialize=[], ordered=True) # scenario data can be populated in one of two ways. the first is "scenario-based", # in which a single .dat file contains all of the data for each scenario. the .dat # file prefix must correspond to the scenario name. the second is "node-based", # in which a single .dat file contains only the data for each node in the scenario # tree. the node-based method is more compact, but the scenario-based method is # often more natural when parameter data is generated via simulation. the default # is scenario-based. model.ScenarioBasedData = Param(within=Boolean, default=True, mutable=True) # do we bundle, and if so, how? model.Bundling = Param(within=Boolean, default=False, mutable=True) # bundle names model.Bundles = Set(ordered=True) model.BundleScenarios = Set(model.Bundles, ordered=True) return model
def define_model(**kwds): model = ConcreteModel() model.x1 = Var(bounds=(0, 3)) # domain variable model.x2 = Var(bounds=(0, 3)) # domain variable model.x3 = Var(bounds=(0, 3)) # domain variable model.x4 = Var(bounds=(0, 3)) # domain variable model.Fx1 = Var() # range variable model.Fx2 = Var() # range variable model.Fx3 = Var() # range variable model.Fx4 = Var() # range variable model.p = Param(initialize=1.0) model.obj = Objective(expr=model.Fx1 + model.Fx2 + model.Fx3 + model.Fx4 + model.x1 + model.x2 + model.x3 + model.x4, sense=kwds.pop('sense', maximize)) model.piecewise1 = Piecewise(model.Fx1, model.x1, pw_pts=DOMAIN_PTS, f_rule=F, **kwds) model.piecewise2 = Piecewise(model.Fx2, model.x2, pw_pts=DOMAIN_PTS, f_rule=F, **kwds) model.piecewise3 = Piecewise(model.Fx3, model.x3, pw_pts=DOMAIN_PTS, f_rule=F, **kwds) model.piecewise4 = Piecewise(model.Fx4, model.x4, pw_pts=DOMAIN_PTS, f_rule=F, **kwds) #Fix the answer for testing purposes model.set_answer_constraint1 = Constraint( expr=model.x1 == 0.5) # Fx1 should solve to 0 model.set_answer_constraint2 = Constraint(expr=model.x2 == 1.0) # model.set_answer_constraint3 = Constraint(expr=model.Fx2 == 0.5) # model.set_answer_constraint4 = Constraint( expr=model.x3 == 1.5) # Fx3 should solve to 1 model.set_answer_constraint5 = Constraint( expr=model.x4 == 2.5) # Fx4 should solve to 1.5 return model
def _generate_model(self): self.model = ConcreteModel() model = self.model model._name = self.description model.a = Param(initialize=1.0) model.x = Var(within=NonNegativeReals) model.y = Var(within=Binary) model.obj = Objective(expr=model.x + 3.0 * model.y) model.c1 = Constraint(expr=model.a <= model.y) model.c2 = Constraint(expr=2.0 <= model.x / model.a - model.y <= 10)
def create_instance(scenario_name): cnt = d[scenario_name] model = ConcreteModel() # first stage model.x = Var(bounds=(0, 10)) # first stage derived model.y = Expression(expr=model.x + 1) model.fx = Var() # second stage model.z = Var(bounds=(-10, 10)) # second stage derived model.q = Expression(expr=model.z**2) model.fz = Var() model.r = Var() # stage costs model.StageCost = Expression([1, 2]) model.StageCost.add(1, model.fx) model.StageCost.add(2, -model.fz + model.r - cnt) model.o = Objective(expr=sum_product(model.StageCost)) model.ZERO = Param(initialize=0, mutable=True) if cnt == 0: cnt = model.ZERO model.c_first_stage = Constraint(expr=model.x >= 0) # test our handling of intermediate variables that # are created by Piecewise but can not necessarily # be declared on the scenario tree model.p_first_stage = Piecewise(model.fx, model.x, pw_pts=[0., 2., 5., 7., 10.], pw_constr_type='EQ', pw_repn='INC', f_rule=[10., 10., 9., 10., 10.], force_pw=True) model.c_second_stage = Constraint(expr=model.x + model.r * cnt >= -100) model.r_second_stage = Constraint(expr=inequality(-cnt, model.r, 0)) # exercise more of the code by making this an indexed # block model.p_second_stage = Piecewise([1], model.fz, model.z, pw_pts=[-10, -5., 0., 5., 10.], pw_constr_type='EQ', pw_repn='INC', f_rule=[0., 0., -1., 2. + cnt, 1.], force_pw=True) return model
def _generate_model(self): self.model = ConcreteModel() model = self.model model._name = self.description model.neg1 = Param(initialize=-1.0, mutable=True) model.pos1 = Param(initialize=1.0, mutable=True) model.s = RangeSet(1, 12) model.x = Var(model.s) model.x[1].setlb(model.neg1) model.x[1].setub(model.pos1) model.x[2].setlb(model.neg1) model.x[2].setub(model.pos1) model.obj = Objective(expr=sum(model.x[i] * ((-1)**(i)) for i in model.x.index_set()), sense=maximize) model.c = ConstraintList() # to make the variable used in the constraint match the name model.c.add(Constraint.Skip) model.c.add(Constraint.Skip) model.c.add(model.x[3] >= -1.) model.c.add(model.x[4] <= 1.) model.c.add(model.x[5] == -1.) model.c.add(model.x[6] == -1.) model.c.add(model.x[7] == 1.) model.c.add(model.x[8] == 1.) model.c.add((model.neg1, model.x[9], model.neg1)) model.c.add((-1., model.x[10], -1.)) model.c.add((1., model.x[11], 1.)) model.c.add((1., model.x[12], 1.)) model.c_inactive = ConstraintList() # to make the variable used in the constraint match the name model.c_inactive.add(Constraint.Skip) model.c_inactive.add(Constraint.Skip) model.c_inactive.add(model.x[3] >= -2.) model.c_inactive.add(model.x[4] <= 2.)
def createConstraints(self): """ Create the basis constraint y = b(w) (equation 3) and the surrogate model constraint y = r_k(w) (equation 5) Both constraints are immediately deactivated after creation and are activated later as necessary. """ b = self.data # This implements: y = b(w) from Yoshio/Biegler (2020) @b.Constraint(b.ef_outputs.index_set()) def basis_constraint(b, i): ef_output_var = b.ef_outputs[i] return ef_output_var == b.basis_expressions[ef_output_var] b.basis_constraint.deactivate() b.INPUT_OUTPUT = Set(initialize=((i, j) for i in b.ef_outputs.index_set() for j in range(len(b.ef_inputs[i])))) b.basis_model_output = Param(b.ef_outputs.index_set(), mutable=True) b.grad_basis_model_output = Param(b.INPUT_OUTPUT, mutable=True) b.truth_model_output = Param(b.ef_outputs.index_set(), mutable=True) b.grad_truth_model_output = Param(b.INPUT_OUTPUT, mutable=True) b.value_of_ef_inputs = Param(b.INPUT_OUTPUT, mutable=True) # This implements: y = r_k(w) @b.Constraint(b.ef_outputs.index_set()) def sm_constraint_basis(b, i): ef_output_var = b.ef_outputs[i] return ef_output_var == b.basis_expressions[ef_output_var] + \ b.truth_model_output[i] - b.basis_model_output[i] + \ sum((b.grad_truth_model_output[i, j] - b.grad_basis_model_output[i, j]) * (w - b.value_of_ef_inputs[i, j]) for j, w in enumerate(b.ef_inputs[i])) b.sm_constraint_basis.deactivate()
def createParam(self): self.TRF.ind_lx=RangeSet(0,self.lx-1) self.TRF.ind_ly=RangeSet(0,self.ly-1) self.TRF.ind_lz=RangeSet(0,self.lz-1) self.TRF.px0 = Param(self.TRF.ind_lx,mutable=True,default=0) self.TRF.py0 = Param(self.TRF.ind_ly,mutable=True,default=0) self.TRF.pz0 = Param(self.TRF.ind_lz,mutable=True,default=0) self.TRF.plrom = Param(self.TRF.ind_ly,range(self.lx+1),mutable=True,default=0) self.TRF.pqrom = Param(self.TRF.ind_ly,range(int((self.lx*self.lx+self.lx*3)/2. + 1)),mutable=True,default=0) self.TRF.ppenaltyComp = Param(mutable=True,default=0)
def _generate_model(self): self.model = ConcreteModel() model = self.model model._name = self.description model.b = Block() model.B = Block([1,2,3]) model.a = Param(initialize=1.0, mutable=True) model.b.x = Var(within=NonNegativeReals) model.B[1].x = Var(within=NonNegativeReals) model.obj = Objective(expr=model.b.x + 3.0*model.B[1].x) model.obj.deactivate() model.B[2].c = Constraint(expr=-model.B[1].x <= -model.a) model.B[2].obj = Objective(expr=model.b.x + 3.0*model.B[1].x + 2) model.B[3].c = Constraint(expr=2.0 <= model.b.x/model.a - model.B[1].x <= 10)
def _generate_model(self): self.model = None self.model = ConcreteModel() model = self.model model._name = self.description model.a = Param(initialize=1.0) model.x = Var(within=NonNegativeReals) model.y = Var(within=NonNegativeReals) model.inactive_obj = Objective(expr=model.y) model.inactive_obj.deactivate() model.obj = Objective(expr=model.x**2 + 3.0 * model.inactive_obj**2 + 1.0) model.c1 = Constraint(expr=model.a <= model.y) model.c2 = Constraint(expr=(2.0, model.x / model.a - model.y, 10))
def test_divide_by_mutable(self): # # Test from https://github.com/Pyomo/pyomo/issues/153 # m = ConcreteModel() m.x = Var(bounds=(1,5)) m.p = Param(initialize=100, mutable=True) m.con = Constraint(expr=exp(5*(1/m.x - 1/m.p))<=10) m.obj = Objective(expr=m.x**2) test = gar(m.con.body) self.assertEqual(test.constant, 0) self.assertEqual(test.linear_vars, tuple()) self.assertEqual(test.linear_coefs, tuple()) self.assertEqual(set(id(v) for v in test.nonlinear_vars), set([id(m.x)])) self.assertIs(test.nonlinear_expr, m.con.body)
def do_setup(self): global tmpdir tmpdir = os.getcwd() os.chdir(currdir) TempfileManager.sequential_files(0) self.asl = pyomo.opt.SolverFactory('asl:ipopt', keepfiles=True) self.ipopt = pyomo.opt.SolverFactory('ipopt', keepfiles=True) # The sisser CUTEr instance # Formulated in Pyomo by Carl D. Laird, Daniel P. Word, Brandon C. Barrera and Saumyajyoti Chaudhuri # Taken from: # Source: # F.S. Sisser, # "Elimination of bounds in optimization problems by transforming # variables", # Mathematical Programming 20:110-121, 1981. # See also Buckley#216 (p. 91) # SIF input: Ph. Toint, Dec 1989. # classification OUR2-AN-2-0 sisser_instance = ConcreteModel() sisser_instance.N = RangeSet(1, 2) sisser_instance.xinit = Param(sisser_instance.N, initialize={ 1: 1.0, 2: 0.1 }) def fa(model, i): return value(model.xinit[i]) sisser_instance.x = Var(sisser_instance.N, initialize=fa) def f(model): return 3 * model.x[1]**4 - 2 * (model.x[1] * model.x[2])**2 + 3 * model.x[2]**4 sisser_instance.f = Objective(rule=f, sense=minimize) self.sisser_instance = sisser_instance
def _generate_model(self): self.model = ConcreteModel() model = self.model model._name = self.description model.a = Param(initialize=0.1) model.x = Var(within=NonNegativeReals) model.y = Var([1, 2], within=NonNegativeReals) model.obj = Objective(expr=model.x + model.y[1] + 2 * model.y[2]) model.c1 = Constraint(expr=model.a <= model.y[2]) model.c2 = Constraint(expr=2.0 <= model.x <= 10.0) model.c3 = SOSConstraint(var=model.y, index=[1, 2], sos=1) model.c4 = Constraint(expr=summation(model.y) == 1) # Make an empty SOSConstraint model.c5 = SOSConstraint(var=model.y, index=[1, 2], sos=1) model.c5.set_items([], []) assert len(list(model.c5.get_items())) == 0
def get_feature_vector(self): """ ===================================================================================================================== The get_feature_vector method generates the list of features from the column headers of the input dataset. :returns p(<IndexedParam>): An indexed parameter list of the variables supplied in the original data ===================================================================================================================== """ p = Param(self.x_data_columns, mutable=True, initialize=0) p.index_set().construct() p.construct() self.feature_list = p return p
def get_feature_vector(self): """ The ``get_feature_vector`` method generates the list of regression features from the column headers of the input dataset. Returns: Pyomo IndexedParam : An indexed parameter list of the variables supplied in the original data """ p = Param(self.x_data_columns, mutable=True, initialize=0) p.index_set().construct() p.construct() self.feature_list = p return p
def define_model(**kwds): model = ConcreteModel() model.x = Var(INDEX_SET1, INDEX_SET2, bounds=(0,6)) # domain variable model.Fx = Var(INDEX_SET1, INDEX_SET2) # range variable model.p = Param(INDEX_SET1, INDEX_SET2, initialize=1.0) model.obj = Objective(expr=sum_product(model.Fx), sense=kwds.pop('sense',maximize)) model.piecewise = Piecewise(INDEX_SET1,INDEX_SET2,model.Fx,model.x, pw_pts=DOMAIN_PTS, f_rule=F, **kwds) #Fix the answer for testing purposes model.set_answer_constraint1 = Constraint(INDEX_SET2,rule= lambda model,t2,t3: model.x['1',t2,t3] == 0.0) model.set_answer_constraint2 = Constraint(INDEX_SET2,rule= lambda model,t2,t3: model.x['2',t2,t3] == 3.0) model.set_answer_constraint3 = Constraint(INDEX_SET2,rule= lambda model,t2,t3: model.x['3',t2,t3] == 5.5) model.set_answer_constraint4 = Constraint(INDEX_SET2,rule= lambda model,t2,t3: model.x['40',t2,t3] == 6.0) return model
def makeModel(): """ This is a single-level reformulation of a bilevel model. We project out the dual variables to recover the reformulation in the original space. """ m = ConcreteModel() m.x = Var(bounds=(0, 2)) m.y = Var(domain=NonNegativeReals) m.lamb = Var([1, 2], domain=NonNegativeReals) m.M = Param([1, 2], mutable=True, default=100) m.u = Var([1, 2], domain=Binary) m.primal1 = Constraint(expr=m.x - 0.01 * m.y <= 1) m.dual1 = Constraint(expr=1 - m.lamb[1] - 0.01 * m.lamb[2] == 0) @m.Constraint([1, 2]) def bound_lambdas(m, i): return m.lamb[i] <= m.u[i] * m.M[i] m.bound_y = Constraint(expr=m.y <= 1000 * (1 - m.u[1])) m.dual2 = Constraint(expr=-m.x + 0.01 * m.y + 1 <= (1 - m.u[2]) * 1000) return m
def _setup_subproblems(self, instance, bigM): # create transformation block transBlockName, transBlock = self._add_relaxation_block( instance, '_pyomo_gdp_cuttingplane_relaxation') # We store a list of all vars so that we can efficiently # generate maps among the subproblems transBlock.all_vars = list(v for v in instance.component_data_objects( Var, descend_into=(Block, Disjunct), sort=SortComponents.deterministic) if not v.is_fixed()) # we'll store all the cuts we add together transBlock.cuts = Constraint(Any) # get bigM and chull relaxations bigMRelaxation = TransformationFactory('gdp.bigm') chullRelaxation = TransformationFactory('gdp.chull') relaxIntegrality = TransformationFactory('core.relax_integrality') # HACK: for the current writers, we need to also apply gdp.reclassify so # that the indicator variables stay where they are in the big M model # (since that is what we are eventually going to solve after we add our # cuts). reclassify = TransformationFactory('gdp.reclassify') # # Generalte the CHull relaxation (used for the separation # problem to generate cutting planes # instance_rCHull = chullRelaxation.create_using(instance) # This relies on relaxIntegrality relaxing variables on deactivated # blocks, which should be fine. reclassify.apply_to(instance_rCHull) relaxIntegrality.apply_to(instance_rCHull) # # Reformulate the instance using the BigM relaxation (this will # be the final instance returned to the user) # bigMRelaxation.apply_to(instance, bigM=bigM) reclassify.apply_to(instance) # # Generate the continuous relaxation of the BigM transformation # instance_rBigM = relaxIntegrality.create_using(instance) # # Add the xstar parameter for the CHull problem # transBlock_rCHull = instance_rCHull.component(transBlockName) # # this will hold the solution to rbigm each time we solve it. We # add it to the transformation block so that we don't have to # worry about name conflicts. transBlock_rCHull.xstar = Param(range(len(transBlock.all_vars)), mutable=True, default=None) transBlock_rBigM = instance_rBigM.component(transBlockName) # # Generate the mapping between the variables on all the # instances and the xstar parameter # var_info = tuple( (v, transBlock_rBigM.all_vars[i], transBlock_rCHull.all_vars[i], transBlock_rCHull.xstar[i]) for i, v in enumerate(transBlock.all_vars)) # # Add the separation objective to the chull subproblem # self._add_separation_objective(var_info, transBlock_rCHull) return instance_rBigM, instance_rCHull, var_info, transBlockName
###NOTE: as of May 16, this will not even come close to running. DLW ### and it is "wrong" in a lot of places. ### Someone should edit this file, then delete these comment lines. DLW may 16 """ David L. Woodruff and Mingye Yang, Spring 2018 Code snippets for scripts.rst in testable form """ from pyomo.environ import * instance = ConcreteModel() instance.I = Set(initialize=[1, 2, 3]) instance.sigma = Param(mutable=True, initialize=2.3) instance.Theta = Param(instance.I, mutable=True) for i in instance.I: instance.Theta[i] = i ParamName = "Theta" idx = 1 NewVal = 1134 # @Assign_value_to_indexed_parametername getattr(instance, ParamName)[idx] = NewVal # @Assign_value_to_indexed_parametername ParamName = "sigma" # @Assign_value_to_unindexed_parametername_1 getattr(instance, ParamName)[None] = NewVal # @Assign_value_to_unindexed_parametername_1 # @Assign_value_to_unindexed_parametername_2 getattr(instance, ParamName).set_value(NewVal) # @Assign_value_to_unindexed_parametername_2