Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the optimal optimization variables in Pulp with Python?

Tags:

python

pulp

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?

like image 711
1-approximation Avatar asked Feb 17 '16 18:02

1-approximation


1 Answers

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, ...}
like image 60
Jika Avatar answered Sep 22 '22 08:09

Jika