Reputation: 539
Currently I am working on a pulp lineair minimization problem. The variable X
is equal to the sum of a list of numbers in this problem. If X positive, no penalty should be added to the objective. However, if X
is negative, this should be added to the as penalty to the objective. This means that the Penalty
should be equal to -X
in that case.
For instance:
X = lpvariable('X'-1000,1000,cat='Integer')
Penalty =lpvariable('Penalty', 0,1000,cat='Integer')
prob += Penalty # Objective
prob += 10 + 11 + -2 + -4 == X
In this case X=15
and Penalty=0
However when the sum would be
prob += -10+11-2-4 ==X
The variableX=-5
and the penalty should be Penalty = 5
Could somebody help me with this?
Many thanks in advance.
Upvotes: 0
Views: 672
Reputation: 5419
What you are missing is the constraint on Penalty
. You pretty much say what this needs to be in your question.
You want to force Penalty
to be >=
to -X
.
When X
is positive this will have no effect - the lower bound on Penalty
is already zero so adding another lower bound of -X
where X
is a positive number does nothing.
When X
is negative it does just what you want:
from pulp import *
X = LpVariable('X',-1000,1000,cat='Integer')
Penalty =LpVariable('Penalty', 0,1000,cat='Integer')
prob = LpProblem ("MinimisePenaltye", LpMinimize)
prob += Penalty # Objective
prob += Penalty >= -X
prob += X == -15
prob.solve()
# Dislay the optimums of each var
for v in prob.variables ():
print (v.name, "=", v.varValue)
Returns
Penalty = 15.0
X = -15.0
Upvotes: 1