TypeError: object of type 'int' has no len() in Objective function nonlinear optimization Gekko

839 views Asked by At

I am to maximize my non-linear function and trying to do that with GEKKO

m=GEKKO()
x=m.Var(value=1,lb=0, ub=50)
y=m.Var(value=1, lb=0, ub=50)
m.Equation(puree*x+cutlet*y==1500)
m.Obj(-min(x,y))
m.solve(disp=False)
x.value
y.value

but I get TypeError: object of type 'int' has no len() in this string m.Obj(-min(x,y)) and I don't know what to change to make it work...

2

There are 2 answers

2
tclarke13 On BEST ANSWER

Your x and y are specific Gekko variable types, even though when you display them they display as integers. There is no min function defined on that specific type. So when you call min, the Python builtin min function depends on len, and the Gekko specific len function takes as its argument the value of the variable, so effectively min calls len(x.value), which does not work because x.value is an int (equivalently for y). If you want to set your objective function to be some function of x and y, then you need to do it as such:

m.Obj(<f(x,y)>)

and Gekko will try to minimize f. So if you just want to minimize x+y, then all you need is m.Obj(x+y).

0
John Hedengren On

As tclarke13 correctly points out, you need to use the m.min2() or m.min3() functions to create a continuously differentiable version of the minimum function.

from gekko import GEKKO
m=GEKKO()
x,y = m.Array(m.Var,2,value=1,lb=0,ub=50)
puree=100; cutlet=120
m.Equation(puree*x+cutlet*y==1500)
m.Maximize(m.min3(x,y))
m.solve(disp=False)
print(x.value[0],y.value[0])

The m.min2() function uses complementarity constraints while the m.min3() function uses a binary variable. The binary variable requires that this problem is solved with either a Mixed Integer Linear Programming (MILP) solver or Mixed Integer Nonlinear Programming (MINLP) solver. Gekko automatically selects m.options.SOLVER=1 when you use m.min3(). This produces the solution:

6.8181818182
6.8181818182

More information on m.min2() is available here.