python - GEKKO:将数组中的出现计数为条件
问题描述
我将gekko 用于INLP,即整数非线性规划。我有一个整数变量数组;但是,我的条件是任何值都不能出现多次,即
代码:
from gekko import GEKKO
model = GEKKO()
model.options.SOLVER = 1
x = model.Array(model.Var, 2, lb=0, ub=10, integer=True)
for m in range(11):
model.Equation(x.count(m) <= 1)
model.Obj(sum(x))
model.solve()
给出错误:TypeError:“int”类型的对象没有 len()
为什么我不能那样做?
解决方案
Numpycount
函数不为求解器提供梯度,因此在 gekko 方程中不受支持。解决该问题的另一种方法是使用二进制变量b
来确定在 0 和 10 之间选择哪 2 个数字。
from gekko import GEKKO
model = GEKKO()
model.options.SOLVER = 1
n = 10
b = model.Array(model.Var, 11, lb=0, ub=1, integer=True)
y = [model.Intermediate(b[i]*i) for i in range(11)]
model.Equation(model.sum(b)==2)
model.Minimize(model.sum(y))
model.solve()
print('b: ' + str(b))
print('y: ' + str(y))
解决方案是:
b: [[1.0] [1.0] [0.0] [0.0] [0.0] [0.0] [0.0] [0.0] [0.0] [0.0] [0.0]]
y: [[0.0], [1.0], [0.0], [0.0], [0.0], [0.0], [0.0], [0.0], [0.0], [0.0], [0.0]]
这是正确的,因为选择了 0 和 1 以最小化总和。如果切换到m.Maximize(model.sum(y))
则求解器选择 9 和 10。
b: [[0.0] [0.0] [0.0] [0.0] [0.0] [0.0] [0.0] [0.0] [0.0] [1.0] [1.0]]
y: [[0.0], [0.0], [0.0], [0.0], [0.0], [0.0], [0.0], [0.0], [0.0], [9.0], [10.0]]
这并没有给出x
仅包含 2 个数字的数组的解决方案。您也可以y
在您的应用程序中使用。
这是一种浓缩y
到的方法x
:
from gekko import GEKKO
model = GEKKO()
model.options.SOLVER = 1
b = model.Array(model.Var, (11,2), lb=0, ub=1, integer=True)
x = [None]*2
for j in range(2):
x[j] = model.sum([model.Intermediate(b[i,j]*i) for i in range(11)])
model.Equations([model.sum(b[:,j])==1 for j in range(2)])
model.Equations([model.sum(b[i,:])<=1 for i in range(11)])
model.Minimize(model.sum(x))
model.solve()
print('b: ' + str(b))
print('x: ' + str(x))
这给出了解决方案:
b: [[[0.0] [1.0]]
[[1.0] [0.0]]
[[0.0] [0.0]]
[[0.0] [0.0]]
[[0.0] [0.0]]
[[0.0] [0.0]]
[[0.0] [0.0]]
[[0.0] [0.0]]
[[0.0] [0.0]]
[[0.0] [0.0]]
[[0.0] [0.0]]]
x: [[1.0], [0.0]]
这种方法需要更多的二进制变量,但解决方案仍然很快。
推荐阅读
- python - 如何在后台使用颤振应用程序截取屏幕截图
- vuejs2 - Sortable 的 VueDraggable 无法正常工作,并将所选项目发送到初始化时的第一个
- python - DBSCAN - 查找地理空间数据(坐标)的 Eps 和 MinPts 的最佳方法
- vue.js - Vue Storefront 入门
- wordpress - 如何访问循环内的 WordPress 帖子管理数据?
- python - if语句在python中被忽略
- php - max_user_connections - 查找原因/打开连接
- php - mysql json中的字符集
- c# - 如何使用 Windows Server 2016 上的本地帐户获得对安全事件日志的完全读取权限
- r - 连续保持前 3 个值,将其他所有值更改为 NA