0

I am using an integer variable in DOCPLEX using Python API. I know how to give a range of possible values to these variables using upper bound and lower bound, but how to make sure that the variables take values from only a set of integers?

For eg. I want a variable 'var' to take up values from only the set {-2, -1, 5, 10}. How do I do this?

Mario
  • 17
  • 3

1 Answers1

0

In https://www.linkedin.com/pulse/making-optimization-simple-python-alex-fleischer/

decision variable in a domain with cplex and cpo

from docplex.mp.model import Model

# Now suppose we can rent only 0,1,3,4 or 5 buses of 40 seats buses

mdl = Model(name='buses')
nbbus40 = mdl.integer_var(name='nbBus40')
nbbus30 = mdl.integer_var(name='nbBus30')
mdl.add_constraint(nbbus40*40 + nbbus30*30 >= 300, 'kids')
mdl.minimize(nbbus40*500 + nbbus30*400)

allowedQuantities=[0,1,3,4,5];
mdl.add_constraint(1==sum((a==nbbus40) for a in allowedQuantities))

mdl.solve()

for v in mdl.iter_integer_vars():
    print(v," = ",v.solution_value)


"""
which gives
nbBus40  =  3.0
nbBus30  =  6.0
"""

or with cpoptimizer

#Now suppose we can rent only 0,1,3,4 or 5 buses of 40 seats bu

from docplex.cp.model import CpoModel

mdl = CpoModel(name='buses')
nbbus40 = mdl.integer_var(0,1000,name='nbBus40')
nbbus30 = mdl.integer_var(0,1000,name='nbBus30')
mdl.add(nbbus40*40 + nbbus30*30 >= 300)
mdl.minimize(nbbus40*500 + nbbus30*400)

allowedQuantities=[0,1,3,4,5];
nbbus40.set_domain(allowedQuantities)

msol=mdl.solve()

print(msol[nbbus40]," buses 40 seats")
print(msol[nbbus30]," buses 30 seats") 


"""
which gives
3  buses 40 seats
6  buses 30 seats
"""
Alex Fleischer
  • 9,276
  • 2
  • 12
  • 15