调用Gekko solve会产生TypeError:类型为“int”的对象没有len()

2024-03-29 01:45:43 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图用Gekko解决一个最优控制问题。当我尝试调用m.solve()时,它会给我TypeError: object of type 'int' has no len(),详细信息如下。不管我选择了什么样的目标函数,我都会得到这个错误;然而,only similar issue I've found有一个不可微约束的问题,我很确定我的约束是可微的。我可能会因为Gekko而犯这种错误,还有其他原因吗

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-25-9f7b73717b27> in <module>
      1 from gekko import GEKKO
----> 2 solve_system()

<ipython-input-24-f224d4cff3fc> in solve_system(theta, alpha, rho, chi, L_bar, n, w, delta_inc, xi, phi, tau, kappa, GAMMA, T, SIGMA, BETA, s_init, i_init, r_init)
    257     ##### solve model #####
    258     m.options.IMODE = 6
--> 259     m.solve()

~\Anaconda3\lib\site-packages\gekko\gekko.py in solve(self, disp, debug, GUI, **kwargs)
   1955         # Build the model
   1956         if self._model != 'provided': #no model was provided
-> 1957             self._build_model()
   1958         if timing == True:
   1959             print('build model', time.time() - t)

~\Anaconda3\lib\site-packages\gekko\gk_write_files.py in _build_model(self)
     54             model += '\t%s' % variable
     55             if not isinstance(variable.VALUE.value, (list,np.ndarray)):
---> 56                 if not (variable.VALUE==None):
     57                     i = 1
     58                     model += ' = %s' % variable.VALUE

~\Anaconda3\lib\site-packages\gekko\gk_operators.py in __len__(self)
     23         return self.name
     24     def __len__(self):
---> 25         return len(self.value)
     26     def __getitem__(self,key):
     27         return self.value[key]

~\Anaconda3\lib\site-packages\gekko\gk_operators.py in __len__(self)
    142 
    143     def __len__(self):
--> 144         return len(self.value)
    145 
    146     def __getitem__(self,key):

TypeError: object of type 'int' has no len()

我确实在约束中调用了一个外部(但可微)函数。然而,删除它并只是在没有函数的情况下进行工作并不能解决问题。我非常感谢你们能提供的任何意见。谢谢大家!


Tags: inpyselfmodellenreturnifvalue
1条回答
网友
1楼 · 发布于 2024-03-29 01:45:43

此错误可能是因为您正在Gekko表达式中使用Numpy数组或Python列表

import numpy as np
x = np.array([0,1,2,3])  # numpy array
y = [2,3,4,5]            # python list

from gekko import GEKKO
m = GEKKO()
m.Minimize(x)            # error, use Gekko Param or Var
m.Equation(m.sum(x)==5)  # error, use Gekko Param or Var

可以通过切换到Gekko参数或变量来避免此错误。Gekko可以使用Python列表或Numpy数组进行初始化

xg = m.Param(x)
yg = m.Var(y)

m.Minimize(xg)           
m.Equation(m.sum(yg)==5)
m.solve()

相关问题 更多 >