pythonpython-3.xoptimizationpyomostochastic

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


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?


Solution

  • 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()