我正在尝试解决非线性优化问题。我通过创建下面的代码复制了我的问题。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()
-
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)
-
我希望 GEKKO 在约束中使用 IF 语句运行,我不关心代码中的优化问题是否有解决方案。先感谢您。