简体   繁体   English

使用 Gekko 进行楼层划分

[英]Floor division using Gekko

In this optimization problem (a single variable simplified version of mine) I have one variable and I am trying to maximize the objective.在这个优化问题(我的单变量简化版本)中,我有一个变量,我试图最大化目标。 The answer should be x = 4 with an objfcnval equal to 2 since as x increases these will be the calculations 0 - 0 = 0, 1 - 2 = -1, 2 - 2 = 0, 3 - 2 = 1, 4 - 2 = 2 , 5 - 4 = 1.答案应该是 x = 4,objfcnval 等于 2,因为随着 x 的增加,这些将是计算0 - 0 = 0, 1 - 2 = -1, 2 - 2 = 0, 3 - 2 = 1, 4 - 2 = 2 , 5 - 4 = 1。

Here is the code:这是代码:

def my_ceiling(elem1, elem2):
    if (elem1 // elem2) == (elem1 / elem2):
        return elem1 / elem2
    else:
        return (elem1 // elem2) + 1


m = gekko.GEKKO(remote=False)
m.options.SOLVER = 1

x = m.Var(value=0, lb=0, ub=5, integer=True)

m.Obj((-1) * (x - 2 * my_ceiling(x, 4)))

m.solve(disp=False)

print('Objective: ' + str((-1) * m.options.objfcnval))
    if (elem1 // elem2) == (elem1 / elem2):
TypeError: unsupported operand type(s) for //: 'GKVariable' and 'int'

The problem is that apparently this kind of operation is not supported.问题是显然不支持这种操作。 How would I go about using Gekko for problems like these?我将如何使用 Gekko 解决此类问题?

Taking inspiration from another discussion , one way to implement the floor function is to create a new integer variable y that is bounded by x/4 > y >= x/4 + 1e-8 .另一个讨论中获得灵感,实现地板 function 的一种方法是创建一个新的 integer 变量y ,其边界为x/4 > y >= x/4 + 1e-8

import gekko
m = gekko.GEKKO(remote=False)
m.options.SOLVER = 1

x = m.Var(value=0, lb=0,ub=5,integer=True)
y = m.Var(lb=0,ub=5,integer=True)

m.Equations([y<x/4,y>=x/4+1e-8])
m.Maximize((x - 2*y))

m.solve(disp=False)

print(x.value[0],y.value[0])
print('Objective: ' + str((-1)*m.options.objfcnval))

This produces a solution for x , y , and the objective function:这产生了xy和目标 function 的解:

4.0 1.0
Objective: 2.0

This strategy also works if x is not an integer variable but Gekko gives a slightly different answer:如果x不是 integer 变量,此策略也适用,但 Gekko 给出的答案略有不同:

3.99999996 1.0
Objective: 1.99999996

If there is a reliable method, perhaps we should add a floor or ceil function in gekko that is similar to some of the other functions in the model building documentation .如果有可靠的方法,也许我们应该在gekko中添加一个floor或天花板ceil ,它类似于model建筑文档中的其他一些功能。 Could you keep us updated on your testing and what approach works best?您能否让我们了解您的测试以及哪种方法最有效?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM