qqzj
qqzj

Reputation: 21

How to recreate variables using CPLEX or DoCPLEX module?

Suppose I have a lot of variables in mdl1. After saving mdl1 in a .sav and .lp, I read it back into doCPlex.

mdl2 = ModelReader.read(filename)

Now I want to recreate all the variables in mdl2. How to do that? Suppose I know the variables' names are 'variable1', 'variable2', 'variable3'. I would want to do something like

variable1 = mdl_2.get_var_by_name('variable1')

However, there might be hundreds of variables, I cannot afford to hand-tpye them in. So I want to use something like

eval("variable1 = mdl_2.get_var_by_name('variable1')")

But that did not work for me. Any help? Thanks!

Upvotes: 0

Views: 192

Answers (1)

Alex Fleischer
Alex Fleischer

Reputation: 10062

You can use a dictionnary. I will do this with the zoo example

Suppose you have a small lp file

\ENCODING=ISO-8859-1
\Problem name: zoooplwithoutobjective

Minimize
 obj:
Subject To
 c1: 40 nbBus40 + 30 nbBus30 >= 300
Bounds
      nbBus40 >= 0
      nbBus30 >= 0
Generals
 nbBus40  nbBus30 
End

then you can write

from docplex.mp.model import Model
from docplex.mp.model_reader import ModelReader


mdl = ModelReader.read_model('zoowithoutobj.lp', model_name='zoo')

intvars={}
for v in mdl.iter_integer_vars():
    intvars[v.name]=v

print(intvars)

which gives

{'nbBus40': docplex.mp.Var(type=I,name='nbBus40'), 'nbBus30': docplex.mp.Var(type=I,name='nbBus30')}

Upvotes: 0

Related Questions