6

I am using Pulp with Python to solve an optimization problem.

I am using

import pulp
# code
pulp.prob.objective.value()

Now, I would like to access the optimization variables. How to do this?

In the documentation of Pulp, I found something like use_vars[i].varValue but I should loop to get the whole vector. Can I get it directly like in the objective value? Anyone familiar with Pulp?

1-approximation
  • 321
  • 3
  • 12

1 Answers1

7

To get the whole optimization vector you can do

pulp.prob.variables()

which will return a list of all your variables. To access the i-th element of your list, or the i-th variables, you have to do

pulp.prob.variables()[i].varValue

You can return the objective value and the variables in a function like

return pulp.prob.objective.value(), pulp.prob.variables()

and then access your variables using a for loop like

varsdict = {}
for v in prob.variables():
    varsdict[v.name] = v.varValue

Final results will be a dictionary varsdict that looks like

varsdict = {'x_10': 0.0, 'x_0': 1.0, ...}
Jika
  • 1,207
  • 3
  • 14
  • 26