提问人:Kelly Yang 提问时间:8/25/2023 更新时间:8/25/2023 访问量:77
使用 Pulp 求解线性规划,但具有非线性约束
Solving linear programs using Pulp but with nonlinear constraint
问:
我目前正在使用 Pulp 解决一个优化问题(我必须使用 Pulp)。但是,该问题要求变量的答案是完美的平方。谁能帮我如何处理这个限制?
我试图用 B^2 替换我的变量 A,但显然纸浆只支持线性方程。我还能尝试哪些其他方法?
答:
0赞
AirSquid
8/25/2023
#1
这是一种可能的方法。您可以使用二叉指标值来指示要选择的一组可能值中的哪个值。在您的例子中,可能值的集合是完美正方形的集合,但它可以是任何东西。
这样做的并发症是:
- 您正在制作一个混合整数程序,根据问题的范围,该程序可能更难解决。
- 每当你想捕获平方变量的值时,你都需要做我在约束中显示的求和“事情”,因为你需要将二元选择变量乘以值来捕获它。
x
题外话:你可能不需要像我在这里那样修改CBC_CMD......我只需要指向特定的安装
法典
# perfect square selector
import pulp
val_index = list(range(10))
square_vals = {t : t**2 for t in val_index}
prob = pulp.LpProblem('picker', sense=pulp.LpMaximize)
x = {t: pulp.LpVariable(f'x_{t}', cat=pulp.LpBinary) for t in val_index}
y = {t: pulp.LpVariable(f'y_{t}', cat=pulp.LpBinary) for t in val_index}
# OBJ: maximize x^2 + y^2
prob += sum(square_vals[i] * x[i] + square_vals[i] * y[i] for i in val_index)
# CONSTRAINTS
# must select one of the values for x, y
prob += pulp.lpSum(x) == 1
prob += pulp.lpSum(y) == 1
# x^2 <= 50
prob += sum(square_vals[i] * x[i] for i in val_index) <= 50
print(prob)
cbc_path = '/opt/homebrew/opt/cbc/bin/cbc'
solver = pulp.COIN_CMD(path=cbc_path)
solution = prob.solve(solver)
for i in val_index:
if x[i].varValue >= 0.1:
print(f'x^2 = {square_vals[i]}')
for i in val_index:
if y[i].varValue >= 0.1:
print(f'y^2 = {square_vals[i]}')
输出(截断):
Result - Optimal solution found
Objective value: 130.00000000
Enumerated nodes: 0
Total iterations: 0
Time (CPU seconds): 0.00
Time (Wallclock seconds): 0.00
Option for printingOptions changed from normal to all
Total time (CPU seconds): 0.00 (Wallclock seconds): 0.00
x^2 = 49
y^2 = 81
评论