4

I'm working in Python 2.7 and using the PuLP library to setup a problem. Once the variables, objective and constraints are defined, I pickle my LpProblem object to send off to a Solver elsewhere. Upon un-pickling my problem, I notice that all of the variables are duplicated:

import pulp
import pickle

prob = pulp.LpProblem('test problem', pulp.LpMaximize)
x = pulp.LpVariable('x', 0, 10)
y = pulp.LpVariable('y', 3, 6)
prob += x + y
prob += x <= 5

print prob
print pickle.loads(pickle.dumps(prob))

The first print statement outputs:

>>> print prob
test problem:
MAXIMIZE
1*x + 1*y + 0
SUBJECT TO
_C1: x <= 5

VARIABLES
x <= 10 Continuous
3 <= y <= 6 Continuous

while the second prints:

>>> print pickle.loads(pickle.dumps(prob))
test problem:
MAXIMIZE
1*x + 1*y + 0
SUBJECT TO
_C1: x <= 5

VARIABLES
x <= 10 Continuous
x <= 10 Continuous
3 <= y <= 6 Continuous
3 <= y <= 6 Continuous

As you can see, the objective and constraints are fine, but all of the variables are duplicated. What causes this behavior, and how can I prevent this from happening?

Mike
  • 6,813
  • 4
  • 29
  • 50

1 Answers1

2

So I haven't figured out exactly why this happens but I do have a way around it for anyone stuck in the same situation:

def UnpicklePulpProblem(pickled_problem):
    wrong_result = pickle.loads(pickled_problem)
    result = pulp.LpProblem(wrong_result.name, wrong_result.sense)
    result += wrong_result.objective
    for i in wrong_result.constraints: result += wrong_result.constraints[i], i
    return result

Adding the objective and constraint in this way makes sure that the variables are only defined once within the problem, since you are basically rebuilding the problem from scratch this way.

Mike
  • 6,813
  • 4
  • 29
  • 50
  • When following this approach I find that I cannot add further constraints to the problem? When adding more constraints and then saving the LP problem I get the "duplicate names" error again. So, I try repeating the above process with the newly added constraints but this does not work for some reason. – Jesper - jtk.eth Mar 22 '15 at 19:13
  • The workaround to the comment I posted is this: Load in the pickled LP problem but do NOT add the constraints. Then, you get a new set of constraints and finally you merge the constraints (using update on OrderedDict) and THEN add them in one big go. – Jesper - jtk.eth Mar 23 '15 at 04:38