简体   繁体   中英

Absolute Value with Pulp Objective

I'm working on a fairly simple problem with pulp where I have a single variable that affects every entry in my dataset. I want to get as minimize the absolute difference between the target metric for each entry and the affect caused by the single variable in order to ensure I'm hitting the targets as closely as possible. So far I have:

import pulp
import math

prob = pulp.LpProblem(
    "Example", 
    pulp.LpMinimize
)

mRHT = pulp.LpVariable("MRExHT")

pcnts = df['Affect %'].tolist()
gaps = df['Target Metric'].tolist()

prob += pulp.lpSum(
    gaps[i] - (mRHT * pcnts[i]) for i in range(len(df))
)
prob.solve()

Except I can't get the absolute difference to work so the problem is unbounded. Ideally I'd like the last part to be something like:

prob += pulp.lpSum(
        abs(gaps[i] - (mRHT * pcnts[i])) for i in range(len(df))
    )

but I can't use abs or math.abs with pulp. Any suggestions on how to do this?

You need to add a new variable that uses two constraints to find the max of a - b and b - a, which is also the absolute value. should look something like

abs_gap = [pulp.LpVariable("abs_gap_" + str(i)) for i in range(len(df))]
for i in range(len(df)):
    prob += abs_gap[i] >= gaps[i] - (mRHT * pcnts[i])
    prob += abs_gap[i] >= (mRHT * pcnts[i]) - gaps[i]

prob += pulp.lpSum(abs_gap)

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