gpt4 book ai didi

python - SCIPY - 构建约束而不单独列出每个变量

转载 作者:行者123 更新时间:2023-12-04 04:11:39 25 4
gpt4 key购买 nike

我正在使用 SCIPY 优化一个存储设施,该设施使用 1 年交易期限的远期价格。根据每月价差(例如 3 月 21 日与 5 月 20 日的价差)是否足够高以支付可变运营成本,可以从该设施注入(inject)和提取天然气。附图代表问题(这里的值是任意的,与代码中的值不匹配;图片只是为了概念)

enter image description here

蓝色的单元格是“变化的单元格”,SCIPY 将调整以实现利润最大化的数量。需要为每个月单独设置约束。当我尝试在 SCIPY 中设置这些约束时出现错误。这是问题的可重现版本:

 import numpy as np
import scipy.optimize as opt

p= np.array([4, 5, 6.65, 12]) #p = prices
pmx = np.triu(p - p[:, np.newaxis]) #pmx = price matrix, upper triangular

q =np.triu(np.ones((4,4))) # q = quantity, upper triangular

def profit(q):
profit = -np.sum(q.flatten() * pmx.flatten())
return profit

bnds = (0,10)
bnds = [bnds for i in q.flatten()]

def cons1(q):
np.sum(q,axis=1) - 10

#def cons2(q):
# np.sum(q,axis=0) - 8

#con1 = {'type':'ineq','fun':cons1}
#con2 = {'type':'ineq','fun':cons2}
cons = [con1] # using only 1 constraint (con1) to test the model

#sol = opt.minimize(profit,q,method='SLSQP', bounds= bnds,constraints = cons)
sol = opt.minimize(profit,q,method='SLSQP', bounds= bnds)
sol

当我排除约束时,模型运行良好。当我添加其中一个约束时,我得到的错误是:

AxisError: axis 1 is out of bounds for array of dimension 1

我认为这与我指定约束的方式有关……不过我不确定。对于约束,我确实需要识别注入(inject)和取款并设置约束,如图所示。帮助将不胜感激。谢谢!

最佳答案

作为 Scipy.minimize.optimize 的替代方案,这里有一个 Python gekko 的解决方案.

import numpy as np
import scipy.optimize as opt
from gekko import GEKKO

p= np.array([4, 5, 6.65, 12]) #p = prices
pmx = np.triu(p - p[:, np.newaxis]) #pmx = price matrix, upper triangular

m = GEKKO(remote=False)
q = m.Array(m.Var,(4,4),lb=0,ub=10)
# only upper triangular can change
for i in range(4):
for j in range(4):
if j<=i:
q[i,j].upper=0 # set upper bound = 0

def profit(q):
profit = np.sum(q.flatten() * pmx.flatten())
return profit

for i in range(4):
m.Equation(np.sum(q[i,:])<=10)
m.Equation(np.sum(q[:,i])<=8)
m.Maximize(profit(q))

m.solve()

print(q)

这给出了解决方案:

[[[0.0] [2.5432017412] [3.7228765674] [3.7339217013]]
[[0.0] [0.0] [4.2771234426] [4.2660783187]]
[[0.0] [0.0] [0.0] [0.0]]
[[0.0] [0.0] [0.0] [0.0]]]

关于python - SCIPY - 构建约束而不单独列出每个变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61623986/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com