9
$\begingroup$

In Python's PuLP package, how can I get the value of a decision variable?

For example, if I declare a variable—

x = LpVariable('x_var', cat=LpContinuous)

—then solve the problem, then use

print(x)

Python just outputs:

x_var

How can I get the value of the variable, not its name?

$\endgroup$
1
  • $\begingroup$ This is another question that I've answered a few times on SO and other sites, so I figured I'd post a Q&A here. $\endgroup$
    – LarrySnyder610
    Jun 25 '19 at 21:48
12
$\begingroup$

To get the value of the decision variable, you need to use the varValue property of the LpVariable, so:

print(x.varValue)

You can also use:

print(x.value())

The explanation is that the Python variable x is not the decision variable itself, it is a PuLP object of type LpVariable:

In[5]: type(x)
Out[5]: pulp.pulp.LpVariable

Therefore, just using print(x) does not give you the value of the decision variable, it gives you the variable name that you supplied in the name argument when you declared your LpVariable. (In particular, Python is printing the string returned by the LpVariable's __repr__ function, which is just the name.)


You can also access the name of a variable using the name property. This is also convenient for listing all of the variables at once:

for v in prob.variables():
    print(v.name, "=", v.varValue)

Here's a more complete example, using Hillier and Lieberman's (in)famous "Wyndor Glass" model:

from pulp import *

prob = LpProblem('glass', LpMaximize)

# Declare variables.
x1 = LpVariable('x1_var', lowBound=0, upBound=None, cat=LpContinuous)
x2 = LpVariable('x2_var', lowBound=0, upBound=None, cat=LpContinuous)

# Build objective function.
prob += 3 * x1 + 5 * x2

# Add constraints.    
prob += x1 <= 4
prob += 2 * x2 <= 12
prob += 3 * x1 + 2 * x2 <= 18

# Solve problem.
prob.solve()

# Print status.
print("Status:", LpStatus[prob.status], "\n")

print("The value of x1 = {}. (Not what we want.)".format(x1))
print("The values of x1.value() and x1.varValue = {} and {}. (That's what we want.)\n".format(x1.value(), x1.varValue))

# Print optimal values of decision variables.
print("All variables:")
for v in prob.variables():
    print(v.name, "=", v.varValue)

The output is:

Status: Optimal 

The value of x1 = x1_var. (Not what we want.)
The values of x1.value() and x1.varValue = 2.0 and 2.0. (That's what we want.)

All variables:
x1_var = 2.0
x2_var = 6.0

Note that the idea is the same if we declare the variables using LpVariable.dicts, e.g.:

x = LpVariable.dicts('x_var', range(1, 3), lowBound=0, upBound=None, cat=LpContinuous)

prob += 3 * x[1] + 5 * x[2]

(etc.)

Then print(x[1]) gives

x_var_1

and print(x[1].varValue) gives

2.0
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.