微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

gurobipy:使用 python API 编写分段线性约束SOS2 约束的最佳方式

如何解决gurobipy:使用 python API 编写分段线性约束SOS2 约束的最佳方式

我通过 gurobipy(能量存储优化)制定了简单的 MILP 问题。我想引入允许进入存储和库存的最大和最小流量之间的非线性关系(存储中已经存储了多少介质)。我是通过以下丑陋的 for 循环来实现的(inventoryflow 是通过 gurobipy.Model.addMVar() 方法获得的一维数组变量,而 m 是我的 gurobipy.Model 类) :

# PWL - injection rate constrain
ir_x = [0.0,8000.0,12500.0]
ir_y = [5000.0,5000.0,2500.0]
for a,b in zip(inventory.tolist(),injection_rate.tolist()):
    m.addGenConstrPWL(a,b,ir_x,ir_y)
m.addConstr(flow <= injection_rate)

是否有一些聪明的方法可以在不实际使用 for 循环的情况下做到这一点?

整个工作示例:

import gurobipy as gp
import numpy as np

LEN = 10 # months
MAXIMAL_CAPACITY = 50000.0 # [MWh]
MINIMAL_CAPACITY = 0.0 # [MWh]
INITIAL_STORAGE = 0.0 # [MWh]
END_STORAGE = 0.0 # [MWh]

# create model
m = gp.Model(name="Simple Energy Storage")

# variables
flow = m.addMVar(LEN,lb=float("-inf"),name="flow")
inventory = m.addMVar(LEN,name="inventory")
injection_rate = m.addMVar(LEN,name="injection rate")
withdrawal_rate = m.addMVar(LEN,name="withdrawal rate")

# create inventory condition (cumulative sum of flow)
mat = np.tril(np.ones(shape=(LEN,LEN)))
m.addConstr(mat @ flow == inventory)

# inventory constrains
m.addConstr(inventory <= MAXIMAL_CAPACITY)
m.addConstr(inventory >= MINIMAL_CAPACITY)
m.addConstr(inventory[0] == INITIAL_STORAGE)
m.addConstr(inventory[-1] == END_STORAGE)

# PWL - injection rate constrain
ir_x = [0.0,ir_y)
m.addConstr(flow <= injection_rate)

# PWL - withdrawal rate constrain
wr_x = [0.0,6000.0,12500.0]
wr_y = [3000.0,6500.0,6500.0]
for a,withdrawal_rate.tolist()):
    m.addGenConstrPWL(a,wr_x,wr_y)
m.addConstr(flow >= -withdrawal_rate)

# objective function
m.setobjective(inventory[5],gp.GRB.MAXIMIZE)

m.optimize()

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。