2

I am working on an optimization problem and I am using gekko with an APOPT solver to solve it, sometimes and when I have a lot of variables, I get the following error "exception: @error: max equation length".
How could I know the "max equation length"?

Ziad
  • 83
  • 5

1 Answers1

2

Variables and equations are written as a text file to the temporary folder before they are compiled into byte-code for efficient calculation of residuals, objective functions, sparse 1st derivatives, and sparse 2nd derivatives with automatic differentiation. Equations are limited to 15,000 characters each in gekko models, not just with the APOPT solver. This limit could be extended, but it is to encourage model building methods that improve compilation and solution speed. A simple gekko model demonstrates the issue with x = sum(p) as a vector of 10,000 values.

from gekko import GEKKO
m = GEKKO(remote=False)
p = m.Array(m.Param,10000,value=1)
x = m.Var(lb=0,integer=True)
m.Equation(x==sum(p))
m.options.SOLVER = 1
m.open_folder()
m.solve()

This gives an error that the maximum equation length is exceeded.

Exception: @error: Max Equation Length
 Error with line number:  10008

The run folder is opened with m.open_folder(). The gekko model is in the file gk_model0.apm that is inspected with an text editor. There are a few ways to reduce the equation length for this problem.

  1. The parameters p can be an ordinary numpy array, instead of gekko parameters. The summation is pre-computed before it is written to the model file.
from gekko import GEKKO
import numpy as np
m = GEKKO(remote=False)
p = np.ones(10000)
x = m.Var(lb=0,integer=True)
m.Equation(x==sum(p))
m.options.SOLVER = 1
m.open_folder()
m.solve()

This gives the following gk_model0.apm model:

Model
Variables
    int_v1 = 0, >= 0
End Variables
Equations
    int_v1=10000.0
End Equations
End Model
  1. If the parameters p need to be gekko parameters or variables, then use the m.sum() function instead of sum(). The use of m.sum() is more efficient than sum() or np.sum() for gekko optimization problems and avoids the problem with maximum equation length. The compilation time is longer than the first option.
from gekko import GEKKO
m = GEKKO(remote=False)
p = m.Array(m.Param,10000,value=1)
x = m.Var(lb=0,integer=True)
m.Equation(x==m.sum(p))
m.options.SOLVER = 1
m.solve()
  1. Use m.Intermediate() when possible to reduce the equation size. This special type of intermediate variable incorporates model reduction principles where a quantity is explicitly calculated once and used in multiple places in the model. There are additional suggestions in questions / answers such as How to fix Python Gekko Max Equation Length error
John Hedengren
  • 12,068
  • 1
  • 21
  • 25