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

2023-12-28

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

蓝色单元格是“变化的单元格”,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

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


作为 Scipy.minimize.optimize 的替代方案,这里有一个解决方案蟒蛇壁虎 https://gekko.readthedocs.io/en/latest/.

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]]]
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

SCIPY - 构建约束而不单独列出每个变量 的相关文章

随机推荐