def oneVarDisj_2pts(): m = ConcreteModel() m.x = Var(bounds=(0, 10)) m.disj1 = Disjunct() m.disj1.xTrue = Constraint(expr=m.x==1) m.disj2 = Disjunct() m.disj2.xFalse = Constraint(expr=m.x==0) m.disjunction = Disjunction(expr=[m.disj1, m.disj2]) m.obj = Objective(expr=m.x) return m
class _DisjunctData(_BlockData): def __init__(self, component): _BlockData.__init__(self, component) self.indicator_var = Var(within=Binary) def pprint(self, ostream=None, verbose=False, prefix=""): _BlockData.pprint(self, ostream=ostream, verbose=verbose, prefix=prefix) def set_value(self, val): _indicator_var = self.indicator_var # Remove everything for k in list(getattr(self, '_decl', {})): self.del_component(k) self._ctypes = {} self._decl = {} self._decl_order = [] # Now copy over everything from the other block. If the other # block has an indicator_var, it should override this block's. # Otherwise restore this block's indicator_var. if val: if 'indicator_var' not in val: self.add_component('indicator_var', _indicator_var) for k in sorted(iterkeys(val)): self.add_component(k, val[k]) else: self.add_component('indicator_var', _indicator_var) def activate(self): super(_DisjunctData, self).activate() self.indicator_var.unfix() def deactivate(self): super(_DisjunctData, self).deactivate() self.indicator_var.fix(0) def _deactivate_without_fixing_indicator(self): super(_DisjunctData, self).deactivate() def _activate_without_unfixing_indicator(self): super(_DisjunctData, self).activate()
def pysp_instance_creation_callback(scenario_name, node_names): global cnt model = ConcreteModel() model.x = Var(bounds=(0, 10)) model.y = Expression(expr=model.x + 1) model.z = Var(bounds=(-10, 10)) model.q = Expression(expr=model.z**2) model.StageCost = Expression([1, 2]) model.StageCost.add(1, model.x) model.StageCost.add(2, -model.z) model.o = Objective(expr=sum_product(model.StageCost)) model.c = ConstraintList() model.c.add(model.x >= cnt) model.c.add(model.z <= cnt**2) cnt += 1 return model
def makeNestedDisjunctions(): m = ConcreteModel() m.x = Var(bounds=(-9, 9)) m.z = Var(bounds=(0, 10)) m.a = Var(bounds=(0, 23)) def disjunct_rule(disjunct, flag): m = disjunct.model() if flag: def innerdisj_rule(disjunct, flag): m = disjunct.model() if flag: disjunct.c = Constraint(expr=m.z >= 5) else: disjunct.c = Constraint(expr=m.z == 0) disjunct.innerdisjunct = Disjunct([0, 1], rule=innerdisj_rule) @disjunct.Disjunction([0]) def innerdisjunction(b, i): return [b.innerdisjunct[0], b.innerdisjunct[1]] disjunct.c = Constraint(expr=m.a <= 2) else: disjunct.c = Constraint(expr=m.x == 2) m.disjunct = Disjunct([0, 1], rule=disjunct_rule) # I want a SimpleDisjunct with a disjunction in it too def simpledisj_rule(disjunct): m = disjunct.model() @disjunct.Disjunct() def innerdisjunct0(disjunct): disjunct.c = Constraint(expr=m.x <= 2) @disjunct.Disjunct() def innerdisjunct1(disjunct): disjunct.c = Constraint(expr=m.x >= 4) disjunct.innerdisjunction = Disjunction( expr=[disjunct.innerdisjunct0, disjunct.innerdisjunct1]) m.simpledisjunct = Disjunct(rule=simpledisj_rule) m.disjunction = Disjunction( expr=[m.simpledisjunct, m.disjunct[0], m.disjunct[1]]) return m
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=sum_product(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 create_var(comp, name, block, index_set=None): if index_set is None: if comp.is_indexed(): index_set = comp.index_set() else: index_set = UnindexedComponent_set new_var = Var(index_set) block.add_component(name, new_var) return new_var
def _get_block_model(self): model = ConcreteModel() model.s = Set(initialize=[1, 2]) b = Block(concrete=True) b.s = Set(initialize=[1, 2]) b.x = Var() b.X = Var(model.s) model.b1 = b.clone() model.b2 = b.clone() model.b3 = b.clone() model.b4 = b.clone() model.B1 = Block(model.s, rule=lambda _, i: b.clone()) model.B2 = Block(model.s, rule=lambda _, i: b.clone()) model.B3 = Block(model.s, rule=lambda _, i: b.clone()) model.B4 = Block(model.s, rule=lambda _, i: b.clone()) model.FirstStageCost = Expression(expr=0.0) model.SecondStageCost = Expression(expr=0.0) model.obj = Objective(expr=0.0) return model
def setUp(self): m = ConcreteModel() m.z = Var(range(3), domain=Reals, initialize=2.) m.x = Var(range(2), initialize=2.) m.x[1] = 1.0 def blackbox(a,b): return sin(a-b) self.bb = ExternalFunction(blackbox) m.obj = Objective( expr=(m.z[0]-1.0)**2 + (m.z[0]-m.z[1])**2 + (m.z[2]-1.0)**2 \ + (m.x[0]-1.0)**4 + (m.x[1]-1.0)**6 # + m.bb(m.x[0],m.x[1]) ) m.c1 = Constraint(expr=m.x[0] * m.z[0]**2 + self.bb(m.x[0],m.x[1]) == 2*sqrt(2.0)) m.c2 = Constraint(expr=m.z[2]**4 * m.z[1]**2 + m.z[1] == 8+sqrt(2.0)) self.m = m.clone()
def _create(self, group=None): """ Parameters ---------- group : list List containing storage objects. e.g. groups=[storage1, storage2,..] """ m = self.parent_block() if group is None: return None I = {n: [i for i in n.inputs][0] for n in group} O = {n: [o for o in n.outputs][0] for n in group} self.STORAGES = Set(initialize=[n for n in group]) def _storage_capacity_bound_rule(block, n, t): """Rule definition for bounds of capacity variable of storage n in timestep t """ bounds = (n.nominal_capacity * n.capacity_min[t], n.nominal_capacity * n.capacity_max[t]) return bounds self.capacity = Var(self.STORAGES, m.TIMESTEPS, bounds=_storage_capacity_bound_rule) # set the initial capacity of the storage for n in group: if n.initial_capacity is not None: self.capacity[n, m.timesteps[-1]] = (n.initial_capacity * n.nominal_capacity) self.capacity[n, m.timesteps[-1]].fix() # storage balance constraint def _storage_balance_rule(block, n, t): """Rule definition for the storage balance of every storage n and timestep t """ expr = 0 expr += block.capacity[n, t] expr += -block.capacity[n, m.previous_timesteps[t]] * ( 1 - n.capacity_loss[t]) expr += (-m.flow[I[n], n, t] * n.inflow_conversion_factor[t]) * m.timeincrement[t] expr += (m.flow[n, O[n], t] / n.outflow_conversion_factor[t]) * m.timeincrement[t] return expr == 0 self.balance = Constraint(self.STORAGES, m.TIMESTEPS, rule=_storage_balance_rule)
def makeDisjunctionsOnIndexedBlock(): """Two disjunctions (one indexed an one not), each on a separate BlockData of an IndexedBlock of length 2 """ m = ConcreteModel() m.s = Set(initialize=[1, 2]) m.a = Var(m.s, bounds=(0, 70)) @m.Disjunct(m.s, [0, 1]) def disjunct1(disjunct, s, flag): m = disjunct.model() if not flag: disjunct.c = Constraint(expr=m.a[s] == 0) else: disjunct.c = Constraint(expr=m.a[s] >= 7) def disjunction1_rule(m, s): return [m.disjunct1[s, flag] for flag in [0, 1]] m.disjunction1 = Disjunction(m.s, rule=disjunction1_rule) m.b = Block([0, 1]) m.b[0].x = Var(bounds=(-2, 2)) def disjunct2_rule(disjunct, flag): if not flag: disjunct.c = Constraint(expr=m.b[0].x <= 0) else: disjunct.c = Constraint(expr=m.b[0].x >= 0) m.b[0].disjunct = Disjunct([0, 1], rule=disjunct2_rule) def disjunction(b, i): return [b.disjunct[0], b.disjunct[1]] m.b[0].disjunction = Disjunction([0], rule=disjunction) m.b[1].y = Var(bounds=(-3, 3)) m.b[1].disjunct0 = Disjunct() m.b[1].disjunct0.c = Constraint(expr=m.b[1].y <= 0) m.b[1].disjunct1 = Disjunct() m.b[1].disjunct1.c = Constraint(expr=m.b[1].y >= 0) m.b[1].disjunction = Disjunction( expr=[m.b[1].disjunct0, m.b[1].disjunct1]) return m
def cc(m: Block, tri: qhull.Delaunay, values: List[float], input: List[SimpleVar] = None, output: SimpleVar = None, bound: str = 'eq', **kw): values = np.array(values).tolist() ndim = len(input) nsimplices = len(tri.simplices) npoints = len(tri.points) pointsT = list(zip(*tri.points)) # create index objects dimensions = list(range(ndim)) simplices = list(range(nsimplices)) # 跟单纯形 数量一致 vertices = list(range(npoints)) bound = bound.lower() m.lmbda = Var(vertices, domain=NonNegativeReals) # 非负 m.y = Var(simplices, domain=Binary) # 二进制 # m.y = Var(simplices, domain=NonNegativeReals, bounds=(0, 1)) # 二进制 m.a0 = Constraint(dimensions, rule=lambda m, d: sum(m.lmbda[v] * pointsT[d][v] for v in vertices) == input[d]) if bound == 'eq': m.a1 = Constraint(expr=output == sum(m.lmbda[v] * values[v] for v in vertices)) elif bound == 'lb': m.a1 = Constraint(expr=output <= sum(m.lmbda[v] * values[v] for v in vertices)) elif bound == 'ub': m.a1 = Constraint(expr=output >= sum(m.lmbda[v] * values[v] for v in vertices)) else: raise RuntimeError("bound值错误!bound=" + bound) m.b = Constraint(expr=sum(m.lmbda[v] for v in vertices) == 1) # generate a map from vertex index to simplex index, # which avoids an n^2 lookup when generating the # constraint vertex_to_simplex = [[] for _ in vertices] for s, simplex in enumerate(tri.simplices): for v in simplex: vertex_to_simplex[v].append(s) m.c0 = Constraint(vertices, rule=lambda m, v: m.lmbda[v] <= sum(m.y[s] for s in vertex_to_simplex[v])) m.c1 = Constraint(expr=sum(m.y[s] for s in simplices) == 1) return m
def makeTwoTermDisj_BlockOnDisj(): m = ConcreteModel() m.x = Var(bounds=(0, 1000)) m.y = Var(bounds=(0, 800)) def disj_rule(d, flag): m = d.model() if flag: d.b = Block() d.b.c = Constraint(expr=m.x == 0) d.add_component('b.c', Constraint(expr=m.y >= 9)) d.b.anotherblock = Block() d.b.anotherblock.c = Constraint(expr=m.y >= 11) d.bb = Block([1]) d.bb[1].c = Constraint(expr=m.x == 0) else: d.c = Constraint(expr=m.x >= 80) m.evil = Disjunct([0, 1], rule=disj_rule) m.disjunction = Disjunction(expr=[m.evil[0], m.evil[1]]) return m
def test_quadratic_objective_is_set(self): model = ConcreteModel() model.X = Var(bounds=(-2, 2)) model.Y = Var(bounds=(-2, 2)) model.O = Objective(expr=model.X ** 2 + model.Y ** 2) model.C1 = Constraint(expr=model.Y >= 2 * model.X - 1) model.C2 = Constraint(expr=model.Y >= -model.X + 2) opt = SolverFactory("cplex_persistent") opt.set_instance(model) opt.solve() self.assertAlmostEqual(model.X.value, 1, places=3) self.assertAlmostEqual(model.Y.value, 1, places=3) del model.O model.O = Objective(expr=model.X ** 2) opt.set_objective(model.O) opt.solve() self.assertAlmostEqual(model.X.value, 0, places=3) self.assertAlmostEqual(model.Y.value, 2, places=3)
def makeNestedNonlinearModel(): """This is actually a disjunction between two points, but it's written as a nested disjunction over four circles!""" m = ConcreteModel() m.x = Var(bounds=(-10, 10)) m.y = Var(bounds=(-10, 10)) m.d1 = Disjunct() m.d1.lower_circle = Constraint(expr=m.x**2 + m.y**2 <= 1) m.disj = Disjunction(expr=[[m.x == 10], [(sqrt(2) - m.x)**2 + (sqrt(2) - m.y)**2 <= 1]]) m.d2 = Disjunct() m.d2.upper_circle = Constraint(expr=(3 - m.x)**2 + (3 - m.y)**2 <= 1) m.d2.inner = Disjunction(expr=[[m.y == 10], [(sqrt(2) - m.x)**2 + (sqrt(2) - m.y)**2 <= 1]]) m.outer = Disjunction(expr=[m.d1, m.d2]) m.obj = Objective(expr=m.x + m.y) return m
def makeDisjunctWithRangeSet(): """Two-term SimpleDisjunction where one of the disjuncts contains a RangeSet""" m = ConcreteModel() m.x = Var(bounds=(0, 1)) m.d1 = Disjunct() m.d1.s = RangeSet(1) m.d1.c = Constraint(rule=lambda _: m.x == 1) m.d2 = Disjunct() m.disj = Disjunction(expr=[m.d1, m.d2]) return m
def makeThreeTermDisjunctionWithOneVarInOneDisjunct(): """This is to make sure hull doesn't create more disaggregated variables than it needs to: Here, x only appears in the first Disjunct, so we only need two copies: one as usual for that disjunct and then one other that is free if either of the second two Disjuncts is active and 0 otherwise. """ m = ConcreteModel() m.x = Var(bounds=(-2,8)) m.y = Var(bounds=(3,4)) m.d1 = Disjunct() m.d1.c1 = Constraint(expr=m.x <= 3) m.d1.c2 = Constraint(expr=m.y >= 3.5) m.d2 = Disjunct() m.d2.c1 = Constraint(expr=m.y >= 3.7) m.d3 = Disjunct() m.d3.c1 = Constraint(expr=m.y >= 3.9) m.disjunction = Disjunction(expr=[m.d1, m.d2, m.d3]) return m
def test_noninteger_coefficients_of_vars_not_being_projected_error(self): m = ConcreteModel() m.x = Var(bounds=(0,9)) m.y = Var(bounds=(-5, 5)) m.c1 = Constraint(expr=2*m.x + 0.5*m.y >= 2) m.c2 = Constraint(expr=0.25*m.y >= 5*m.x) fme = TransformationFactory('contrib.fourier_motzkin_elimination') self.assertRaisesRegex( ValueError, "The do_integer_arithmetic flag was " "set to True, but the coefficient of " "y is non-integer within the specified tolerance, " "with value 0.5. \n" "Please set do_integer_arithmetic=" "False, increase integer_tolerance, or make your data integer.", fme.apply_to, m, vars_to_eliminate=m.x, do_integer_arithmetic=True)
def setUp(self): if not scip_available: self.skipTest("The 'scipampl' command is not available") TempfileManager.push() self.scip = SolverFactory('scip', solver_io='nl') m = self.model = ConcreteModel() m.v = Var() m.o = Objective(expr=m.v) m.c = Constraint(expr=m.v >= 1)
def makeTwoTermDisj_Nonlinear(): """Single two-term disjunction which has all of ==, <=, and >= and one nonlinear constraint. """ m = ConcreteModel() m.w = Var(bounds=(2, 7)) m.x = Var(bounds=(1, 8)) m.y = Var(bounds=(-10, -3)) def d_rule(disjunct, flag): m = disjunct.model() if flag: disjunct.c1 = Constraint(expr=m.x >= 2) disjunct.c2 = Constraint(expr=m.w == 3) disjunct.c3 = Constraint(expr=(1, m.x, 3)) else: disjunct.c = Constraint(expr=m.x + m.y**2 <= 14) m.d = Disjunct([0, 1], rule=d_rule) m.disjunction = Disjunction(expr=[m.d[0], m.d[1]]) return m
def get_mock_model_with_priorities(self): m = ConcreteModel() m.x = Var(domain=Integers) m.s = RangeSet(10) m.y = Var(m.s, domain=Integers) m.o = Objective(expr=m.x + sum(m.y), sense=minimize) m.c = Constraint(expr=m.x >= 1) m.c2 = Constraint(expr=quicksum(m.y[i] for i in m.s) >= 10) m.priority = Suffix(direction=Suffix.EXPORT, datatype=Suffix.INT) m.direction = Suffix(direction=Suffix.EXPORT, datatype=Suffix.INT) m.priority.set_value(m.x, 1) # Ensure tests work for both options of `expand` m.priority.set_value(m.y, 2, expand=False) m.direction.set_value(m.y, BranchDirection.down, expand=True) m.direction.set_value(m.y[10], BranchDirection.up) return m
def test_indexedvar_noindextemplate(self): st_model = CreateConcreteTwoStageScenarioTreeModel(1) st_model.StageVariables['Stage1'].add("x") st_model.StageDerivedVariables['Stage1'].add("y") st_model.NodeVariables['RootNode'].add("z") st_model.NodeDerivedVariables['RootNode'].add("q") st_model.StageCost['Stage1'] = "FirstStageCost" st_model.StageCost['Stage2'] = "SecondStageCost" scenario_tree = ScenarioTree(scenariotreeinstance=st_model) self.assertEqual(len(scenario_tree.stages), 2) self.assertEqual(len(scenario_tree.nodes), 2) self.assertEqual(len(scenario_tree.scenarios), 1) model = ConcreteModel() model.s = Set(initialize=[1, 2, 3]) model.x = Var(model.s) model.y = Var(model.s) model.z = Var(model.s) model.q = Var(model.s) model.FirstStageCost = Expression(expr=0.0) model.SecondStageCost = Expression(expr=0.0) model.obj = Objective(expr=0.0) root = scenario_tree.findRootNode() root_nonant_names = _get_names(_get_nonant_list(model, root)) root_derived_nonant_names = _get_names( _get_derived_nonant_list(model, root)) assert len(root_nonant_names) == 6 assert len(root_derived_nonant_names) == 6 for name in ("x", "z"): indexed_var = model.find_component(name) for index in model.s: var = indexed_var[index] assert var.name in root_nonant_names for name in ("y", "q"): indexed_var = model.find_component(name) for index in model.s: var = indexed_var[index] assert var.name in root_derived_nonant_names
def test_integer_arithmetic_non1_coefficients(self): m = ConcreteModel() m.x = Var(bounds=(0, 9)) m.y = Var(bounds=(-5, 5)) m.c1 = Constraint(expr=4 * m.x + m.y >= 4) m.c2 = Constraint(expr=m.y >= 2 * m.x) fme = TransformationFactory('contrib.fourier_motzkin_elimination') fme.apply_to(m, vars_to_eliminate=m.x, constraint_filtering_callback=None, do_integer_arithmetic=True, verbose=True) constraints = m._pyomo_contrib_fme_transformation.projected_constraints self.assertEqual(len(constraints), 3) cons = constraints[3] self.assertEqual(value(cons.lower), -32) self.assertIs(cons.body, m.y) self.assertIsNone(cons.upper) cons = constraints[2] self.assertEqual(value(cons.lower), 0) self.assertIsNone(cons.upper) repn = generate_standard_repn(cons.body) self.assertTrue(repn.is_linear()) self.assertEqual(len(repn.linear_coefs), 1) self.assertIs(repn.linear_vars[0], m.y) self.assertEqual(repn.linear_coefs[0], 2) cons = constraints[1] self.assertEqual(value(cons.lower), 4) self.assertIsNone(cons.upper) repn = generate_standard_repn(cons.body) self.assertTrue(repn.is_linear()) self.assertEqual(len(repn.linear_coefs), 1) self.assertIs(repn.linear_vars[0], m.y) self.assertEqual(repn.linear_coefs[0], 3)
def optimize(self, solver): model = ConcreteModel() model.Np = RangeSet(0, self.Np - 1) #Parameters model.x_for = Param(model.Np, initialize=self.fore) model.v = Param(model.Np, initialize=self.devi) model.f = Param(model.Np, initialize=self.flex) model.w = Param(model.Np, initialize=self.ref) #Variables model.u = Var(model.Np, domain=pmo.Binary) model.x_real = Var(model.Np) #Constraints def controlRule(model, k): return model.x_real[ k] == model.x_for[k] + model.v[k] + model.f[k] * model.u[k] model.pcc = Constraint(model.Np, rule=controlRule) #Objective def objRule(model): return sum( (model.w[k] - model.x_real[k]) * (model.w[k] - model.x_real[k]) for k in model.Np) model.obj = Objective(rule=objRule) Optresult = solver.solve(model) #Saving the results to the self.result attribute pcc = [] u = [] for k in model.Np: pcc.append(model.x_real[k]()) u.append(0.0 if model.u[k]() == None else model.u[k]()) self.results['pcc'] = np.array(pcc) self.results['u'] = np.array(u)
class _DisjunctData(_BlockData): def __init__(self, component): _BlockData.__init__(self, component) self.indicator_var = Var(within=Binary) def pprint(self, ostream=None, verbose=False, prefix=""): _BlockData.pprint(self, ostream=ostream, verbose=verbose, prefix=prefix) def set_value(self, val): _indicator_var = self.indicator_var # Remove everything for k in list(getattr(self, '_decl', {})): self.del_component(k) self._ctypes = {} self._decl = {} self._decl_order = [] # Now copy over everything from the other block. If the other # block has an indicator_var, it should override this block's. # Otherwise restore this block's indicator_var. if val: if 'indicator_var' not in val: self.add_component('indicator_var', _indicator_var) for k in sorted(iterkeys(val)): self.add_component(k,val[k]) else: self.add_component('indicator_var', _indicator_var) def activate(self): super(_DisjunctData, self).activate() self.indicator_var.unfix() def deactivate(self): super(_DisjunctData, self).deactivate() self.indicator_var.fix(0) def _deactivate_without_fixing_indicator(self): super(_DisjunctData, self).deactivate() def _activate_without_unfixing_indicator(self): super(_DisjunctData, self).activate()
def makeDisjunctWithExpression(): """Two-term SimpleDisjunction where one of the disjuncts contains an Expression. This is used to make sure that we correctly handle types we hit in disjunct.component_objects(active=True)""" m = ConcreteModel() m.x = Var(bounds=(0, 1)) m.d1 = Disjunct() m.d1.e = Expression(expr=m.x**2) m.d1.c = Constraint(rule=lambda _: m.x == 1) m.d2 = Disjunct() m.disj = Disjunction(expr=[m.d1, m.d2]) return m
def makeHierarchicalNested_DeclOrderMatchesInstantationOrder(): """Here, we put the disjunctive components on Blocks, but we do it in the same order that we declared the blocks, that is, on each block, decl order matches instantiation order.""" m = ConcreteModel() m.I = RangeSet(1, 4) m.x = Var(m.I, bounds=(-2, 6)) m.disjunct_block = Block() m.disjunction_block = Block() instantiate_hierarchical_nested_model(m) return m
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 do_setup(self): global tmpdir tmpdir = os.getcwd() os.chdir(currdir) TempfileManager.sequential_files(0) self.scip = SolverFactory('scip', solver_io='nl') m = self.model = ConcreteModel() m.v = Var() m.o = Objective(expr=m.v) m.c = Constraint(expr=m.v >= 1)
class _DisjunctData(_BlockData): _Block_reserved_words = set() def __init__(self, component): _BlockData.__init__(self, component) self.indicator_var = Var(within=Binary) def activate(self): super(_DisjunctData, self).activate() self.indicator_var.unfix() def deactivate(self): super(_DisjunctData, self).deactivate() self.indicator_var.fix(0) def _deactivate_without_fixing_indicator(self): super(_DisjunctData, self).deactivate() def _activate_without_unfixing_indicator(self): super(_DisjunctData, self).activate()
def test_do_not_reactivate_disjuncts_with_abandon(self): m = ConcreteModel() m.x = Var() m.s = RangeSet(4) m.d = Disjunct(m.s) m.d[2].bad_constraint_should_not_be_active = Constraint(expr=m.x >= 1) m.disj1 = Disjunction(expr=[m.d[1], m.d[2]]) m.disj2 = Disjunction(expr=[m.d[3], m.d[4]]) m.d[1].indicator_var.fix(1) m.d[2].deactivate() TransformationFactory('gdp.bigm').apply_to(m) self.assertFalse(m.d[2].active)
def test_EXPORT_suffixes_float(self): model = ConcreteModel() model.junk = Suffix(direction=Suffix.EXPORT, datatype=Suffix.FLOAT) model.junk_inactive = Suffix(direction=Suffix.EXPORT, datatype=Suffix.FLOAT) model.x = Var() model.junk.set_value(model.x, 1) model.junk_inactive.set_value(model.x, 1) model.y = Var([1, 2], dense=True) model.junk.set_value(model.y, 2) model.junk_inactive.set_value(model.y, 2) model.obj = Objective(expr=model.x + sum_product(model.y)) model.junk.set_value(model.obj, 3) model.junk_inactive.set_value(model.obj, 3) model.conx = Constraint(expr=model.x >= 1) model.junk.set_value(model.conx, 4) model.junk_inactive.set_value(model.conx, 4) model.cony = Constraint([1, 2], rule=lambda model, i: model.y[i] >= 1) model.junk.set_value(model.cony, 5) model.junk_inactive.set_value(model.cony, 5) model.junk.set_value(model, 6) model.junk_inactive.set_value(model, 6) # This one should NOT end up in the NL file model.junk_inactive.deactivate() model.write(filename=join(currdir, "EXPORT_suffixes.test.nl"), format=ProblemFormat.nl, io_options={"symbolic_solver_labels": False}) _test, _base = join(currdir, "EXPORT_suffixes.test.nl"), join( currdir, "EXPORT_suffixes_float.baseline.nl") self.assertTrue(cmp(_test, _base), msg="Files %s and %s differ" % (_test, _base))
def __init__(self, component): _BlockData.__init__(self, component) self.indicator_var = Var(within=Binary)