0

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!

qqzj
  • 21
  • 1
  • 6

1 Answers1

0

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')}
Alex Fleischer
  • 9,276
  • 2
  • 12
  • 15
  • Hi Alex, Thanks a lot for the help! I combined your code with the answer from this link. Combined, they solved my issue perfectly. That is really great! https://stackoverflow.com/questions/18090672/convert-dictionary-entries-into-variables – qqzj Sep 06 '22 at 16:40