简体   繁体   中英

Python pulp adding a penalty

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 variable X=-5 and the penalty should be Penalty = 5

Could somebody help me with this?

Many thanks in advance.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM