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

2024-10-06 11:42:31 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

我认为这和我指定约束的方式有关……但我不确定。对于约束,我确实需要识别注入和提取,并设置约束,如图所示。我们将不胜感激。谢谢


Tags: defnpscipysumoptbounds设施profit
1条回答
网友
1楼 · 发布于 2024-10-06 11:42:31

作为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]]]

相关问题 更多 >