Home > other >  How to define a binary variable for each value of i using Pyomo in Python?
How to define a binary variable for each value of i using Pyomo in Python?

Time:07-03

I have a variable bi. b is a binary variable which indicates whether to buy a product i or not. i has a value ranging from 1 to 3.

In mathematical format, the binary variable I want to declare looks like follows:

bi ∈ {0, 1} i = 1, 2, 3

I know variable can be declared using following code in Pyomo

from pyomo.environ import *
b = Var(domain = Binary)

But I am not sure how I can show that b is binary only for given values of i. How can I represent the above binary variable for given values using Pyomo in Python?

CodePudding user response:

You simply need to declare the index set and then the index set (or multiple sets, if multi-indexed) reference is the first argument to the variable creation. There are several examples in the dox and this section on Sets.

import pyomo.environ as pyo

m = pyo.ConcreteModel('example')

m.I = pyo.Set(initialize=[1, 2, 3])
m.b = pyo.Var(m.I, domain=pyo.Binary)

# some nonsense objective...
m.obj = pyo.Objective(expr=sum(m.b[i] for i in m.I))

m.pprint()

CodePudding user response:

Alternative way to do it seems to be as follows:

from pyomo.environ import *

model = ConcreteModel()
    
model.i = RangeSet(1,3)
model.b = Var(model.i, domain = Binary)
  • Related