相关文章推荐
曾经爱过的松树  ·  批量 kill mysql ...·  3 月前    · 
多情的剪刀  ·  spyder使用教程 - ...·  1 年前    · 

用PulP进行LP优化。使用IF来设置约束条件

1 人关注

想找一种方法,用IF ELSE函数来设置我的优化问题的约束条件。归纳起来就是:如果常数A小于变量B,那么变量D=0,否则D=A-B。下面是 一个明确的表述 .

I get the error

TypeError: '>' not supported between instances of 'int' and 'LpVariable'

有什么办法可以规避这个问题吗?

My python script is shown below:

import pulp
import random
# setting up constants
t_0=1000
for x in range(t_0):
    A.append(random.randint(1,10))
# initializing LP
LP = pulp.LpProblem('LP',pulp.LpMinimize)  
# adding variables
B = pulp.LpVariable("B", cat='Continuous', lowBound=0)  
D = pulp.LpVariable.dicts("D", range(t_0), cat=pulp.LpContinuous, lowBound=0)
# adding constraints
for t in range(t_0):
    if A[t] > B:
        LP += D[t]  == A[t] - B
    else:
        LP += D[t] == 0
LP += pulp.lpSum(D[t] for t in range(t_0)) 
status = LP.solve(pulp.CPLEX_PY(mip=True, msg=True, timeLimit=15,epgap=None))
print( 'LP status: ' + pulp.LpStatus[status] + '')
    
2 个评论
你为什么不用线性规划来解决这个问题?会快得多
LP/MIP models deal with linear equalities and in-equalities (<= and >=). So no if allowed in a constraint, and also no strict inequalities (< and >).
python
mathematical-optimization
linear-programming
cplex
pulp
cheesus
cheesus
发布于 2019-07-26
2 个回答
Daniel Junglas
Daniel Junglas
发布于 2019-07-26
已采纳
0 人赞同

我不知道PULP,但你正在寻找的是CPLEX中的 "指标约束"。检查PULP文档,看它是否支持指标或逻辑约束,以及如何支持。

但也有另一种选择。你的问题是

minimize sum D(t)
D(t) = A(t)-B if A(t) > B
D(t) = 0 if A(t) <= B

由于这试图使D(t)最小化,在任何最优解中,D(t)将尽可能小。因此,你可以用以下方式代替你的约束条件

D(t) >= A(t) - B
D(t) >= 0

如果B >= A(t),那么第一个将被琐碎地满足,第二个与客观意义一起将设置D(t) = 0。同样地,如果B < A(t),那么第二个将被琐碎地满足,而第一个连同客观意义将设置D(t) = A(t) - B

Alex Fleischer
Alex Fleischer
发布于 2019-07-26
0 人赞同

你应该试着找到与docplex API中的 "if_then "等价物。

from docplex.mp.model import Model
mdl = Model(name='buses')
nbbus40 = mdl.integer_var(name='nbBus40')
nbbus30 = mdl.integer_var(name='nbBus30')
mdl.add_constraint(nbbus40*40 + nbbus30*30 >= 300, 'kids')
mdl.minimize(nbbus40*500 + nbbus30*400)
mdl.solve()
for v in mdl.iter_integer_vars():
   print(v," = ",v.solution_value)
print()
print("with if nb buses 40 more than 3  then nbBuses30 more than 7")
mdl.add(mdl.if_then((nbbus40>=3),(nbbus30>=7)))
mdl.minimize(nbbus40*500 + nbbus30*400)
mdl.solve()
for v in mdl.iter_integer_vars():
    print(v," = ",v.solution_value)

gives

nbBus40  =  6.0
nbBus30  =  2.0