I'm trying to solve an optimal control problem using Gekko. When I try to call m.solve()
, it gives me TypeError: object of type 'int' has no len()
, details below. I get this error regardless of my choice of objective function; however, the only similar issue I've found had an issue with non-differentiable constraints, and I'm pretty sure my constraints are differentiable. Is there another reason I might get this type of error with 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()
I do call an external (but differentiable) function in my constraints. However, removing it and just doing the work without the function didn't solve the issue. I'd really appreciate any input y'all might be able to offer. Thank you!
This error may be because you are using a Numpy array or Python list inside a Gekko expression.
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
You can avoid this error by switching to a Gekko parameter or variable. Gekko can initialize with a Python list or Numpy array.
xg = m.Param(x)
yg = m.Var(y)
m.Minimize(xg)
m.Equation(m.sum(yg)==5)
m.solve()