Gekko非线性优化,约束函数评估if语句中的对象类型错误

div*_*ck1 5 python optimization ipopt gekko

我正在尝试解决非线性优化问题。我通过创建下面的代码来复制我的问题。Python返回TypeError: object of type 'int' has no len()。如何在约束函数中包含IF语句?

控制台将打印以下内容:

  File "<ipython-input-196-8d29d410dcea>", line 1, in <module>
    runfile('C:/Users/***/Documents/***/Project/untitled.py', wdir='C:/Users/***/Documents/***/***/Project')

  File "C:\Users\***\Anaconda3\lib\site-packages\spyder_kernels\customize\spydercustomize.py", line 704, in runfile
    execfile(filename, namespace)

  File "C:\Users\***\Anaconda3\lib\site-packages\spyder_kernels\customize\spydercustomize.py", line 108, in execfile
    exec(compile(f.read(), filename, 'exec'), namespace)

  File "C:/Users/***/Documents/***/***/Project/untitled.py", line 27, in <module>
    m.Equation(Cx(x1,x2,x3,x4) < 0)

  File "C:/Users/***/Documents/***/***/Project/untitled.py", line 17, in Cx
    if K > 15:

  File "C:\Users\***\Anaconda3\lib\site-packages\gekko\gk_operators.py", line 25, in __len__
    return len(self.value)

  File "C:\Users\***\Anaconda3\lib\site-packages\gekko\gk_operators.py", line 134, in __len__
    return len(self.value)

TypeError: object of type 'int' has no len()
Run Code Online (Sandbox Code Playgroud)

--

from gekko import GEKKO
m = GEKKO()


def Cr(x1,x2,x3,x4):
    return (x1*x4*(x1+x2+x3)+x3**2)

def Cw(x1,x2,x3,x4):
    return x1*x2*x3*x4

def Ck(x1,x2,x3,x4):
    return x1*x2*x3*x4+1

def Cx(x1,x2,x3,x4):
    K = Ck(x1,x2,x3,x4)
    if K > 15:  #Issue here
        K = 15
    return x1**2+x2**2+x3**2+x4**2 - K

x1 = m.Var(value=1,lb=-5000,ub=5000)
x2 = m.Var(value=1,lb=-5000,ub=5000)
x3 = m.Var(value=1,lb=-5000,ub=5000)
x4 = m.Var(value=1,lb=-5000,ub=5000)

m.Equation(Cw(x1,x2,x3,x4) >= 14)
m.Equation(Cx(x1,x2,x3,x4) < 0)

m.Obj(Cr(x1,x2,x3,x4))

m.solve(disp=False)
print(x1.value)
print(x2.value)
print(x3.value)
print(x4.value)
Run Code Online (Sandbox Code Playgroud)

--

我希望让GEKKO在约束中使用IF语句运行,我不关心代码中的优化问题是否有解决方案。先感谢您。

sas*_*cha 2

(免责声明:我不知道这个库或者它能为你做什么)

if 语句使得这个问题不可微,这使得 NLP 求解器(如 Ipopt)的假设无效。

就 MINLP 求解器(Bonmin、Couenne)而言,这可以通过重新表述来实现(并且当所需的辅助二进制变量被放松时,所产生的问题是可微分的)。毫无疑问,期望库会为你做这件事。

因此,您似乎需要遵循某些 MINLP 模型的规则,例如 Bonmin在此描述的示例。没有“基于 if 的分支”的概念。

要么引入一个指示变量,就像 MIP 世界中常见的那样,请参阅此处。忽略开销,这个想法将是这样的:

K_ = Ck(x1,x2,x3,x4)
I = K_ > 15 (binary variable; see link for formulation idea)

return x1**2+x2**2+x3**2+x4**2 - I*15 - (1-I) * K_
Run Code Online (Sandbox Code Playgroud)

这就是一个MINLP

在解释您的方程时,您可能无需使用额外的二进制变量(并接触 MINLP),如下所示:

return x1**2+x2**2+x3**2+x4**2 - min(Ck(x1,x2,x3,x4), 15)
Run Code Online (Sandbox Code Playgroud)

这也是不可微分的,但可以很容易地重新表述(有一个怪癖),例如:

return x1**2+x2**2+x3**2+x4**2 - A

# extra constraints
A <= Ck(x1,x2,x3,x4)
A <= 15
Run Code Online (Sandbox Code Playgroud)

如果我们能够强制朝着最大的 A 前进。这意味着,它必须是目标的一部分:

m.Obj(Cr(x1,x2,x3,x4) + c * A) (if it's a maximization problem)
Run Code Online (Sandbox Code Playgroud)

那么这将是一个NLP ,但是c的值需要一些注意(它必须足够大)。