简体   繁体   English

通过 m.if3 为 GEKKO 优化问题中的二元变量设置方程

[英]set equation for binary variable in GEKKO optimization problem by m.if3

I am trying to have a array with size 52*6 as my changing variable.我正在尝试将大小为 52*6 的数组作为我的更改变量。 Also, I would like to define x[:,0] as [0,1] binary variable.另外,我想将 x[:,0] 定义为 [0,1] 二进制变量。 I would like to have a constraint such that for any x[i,0] =1, a = 5;我想有一个约束,使得对于任何 x[i,0] =1, a = 5; otherwise a = 0. The following is part of my code, it turns into a meaningless trivial solution.否则a = 0。以下是我的代码的一部分,它变成了一个毫无意义的琐碎解决方案。 I am guessing I am not using m.if3 correctly, please help me for checking, thank you so much.我猜我没有正确使用 m.if3,请帮我检查一下,非常感谢。

x = m.Array(m.Var,[52,6])
x[:,0]= m.Var(integer=True,lb=0,ub=1)
x[:,1:6] = m.Var(integer=True,lb=0,ub=30)

for i in range(0,52):
    a = m.if3(-x[i,0],5,0)
    m.Equation(sum(x[i,1:6]) == a)

The a = m.if3(-x[i,0],5,0) function should have a switching point that is away from the solution. a = m.if3(-x[i,0],5,0) function 应该有一个远离解决方案的切换点。 The numerical solvers treat x[i,0]=1e-8 the same as x[i,0]=-1e-8 so it may be on one side or the other of the switch point.数值求解器将x[i,0]=1e-8视为与x[i,0]=-1e-8相同,因此它可能位于切换点的一侧或另一侧。 If you need to use m.if3() then set the switch point away from the one solution such as a = m.if3(-x[i,0]+0.5,5,0) so that the values of -x[i,0]+0.5 are between -0.5 and 0.5 .如果您需要使用m.if3()然后将开关点设置为远离一个解决方案,例如a = m.if3(-x[i,0]+0.5,5,0)以便-x[i,0]+0.5-0.50.5之间。

A better way to formulate this problem is to use the x[i,0] value as the binary switch that defines a such as:表述此问题的更好方法是使用x[i,0]值作为定义如下a二进制开关:

a = [None]*n
for i in range(n):
    b = x[i,0] # renaming to b
    # simplified: a[i] = m.Intermediate(b*5)
    a[i] = m.Intermediate(b*5+(1-b)*0)
    m.Equation(sum(x[i,1:])==a[i])

Here is a complete version that demonstrates the switching.这是演示切换的完整版本。

from gekko import GEKKO
m = GEKKO(remote=False)
# define array of integer variables (nx6)
n = 3 # for testing, change to 52 otherwise
x = m.Array(m.Var,(n,6),lb=0,ub=5,integer=True)
# change upper bound to 1 for binary variables
for xi in x[:,0]:
    xi.upper = 1
a = [None]*n
for i in range(n):
    b = x[i,0]
    a[i] = m.Intermediate(b*5+(1-b)*0)
    m.Equation(sum(x[i,1:])==a[i])
m.Equation(sum(a)==5*2)
m.options.SOLVER=1
m.solve()
print('a')
print(a)
print('x')
print(x)

With a Solution:有一个解决方案:

 ---------------------------------------------------
 Solver         :  APOPT (v1.0)
 Solution time  :   1.339999999618158E-002 sec
 Objective      :   0.000000000000000E+000
 Successful solution
 ---------------------------------------------------
 

a
[[5.0], [0.0], [5.0]]
x
[[[1.0] [1.0] [1.0] [1.0] [1.0] [1.0]]
 [[0.0] [0.0] [0.0] [0.0] [0.0] [0.0]]
 [[1.0] [0.0] [2.0] [0.0] [1.0] [2.0]]]

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

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