Intermediate variables are used to decrease the complexity of the model. These variables store temporary calculations with results that are not reported in the final solution reports. In many models, the temporary variables outnumber the regular variables. This model reduction often aides the solver in finding a solution by reducing the problem size.
Intermediate variables are declared in the Intermediates ... End Intermediates section of the model file or with m.Intermediates() in Python Gekko. The intermediate variables may be defined in one section or in multiple declarations throughout the model. Intermediate variables are parsed sequentially, from top to bottom. To avoid inadvertent overwrites, intermediate variable can be defined once. In the case of intermediate variables, the order of declaration is critical. If an intermediate is used before the definition, an error reports that there is an uninitialized value.
An example of intermediates is with the equations z=sqrt(x+y) and w=(x+y)2 that both share a common x+y term. In APMonitor the Intermediates keyword defines this special type of variable.
In Python Gekko, intermediates are defined with the Intermediate function.
The intermediate variables are processed before the implicit equation residuals, every time the solver requests model information. As opposed to implicitly calculated variables, the intermediates are calculated repeatedly and substituted into other intermediate or implicit equations.
When the intermediate variable is solely a function of parameters (not variables), the value may be clipped. This is accomplished by adding inequalities to the expression, separated by a comma. The inequalities may also be a function of other intermediate or regular variables.
APMonitor and Python Gekko are designed to encourage the user to construct well-posed models for numerical solution. Excessive use of intermediate variables may lead to the violation of this limit. If this limit is encountered, the user can remediate this problem by converting an intermediate variable to a regular implicit variable.
$$\max_{T(t)} x_2 \left( t_f \right)$$ $$\mathrm{subject \; to}$$ $$\frac{dx_1}{dt}=-k_1 \, x_1^2$$ $$\frac{dx_2}{dt}=k_1 \, x_1^2 - k_2 \, x_2$$ $$k_1 = 4000 \, \exp{\left(-\frac{2500}{T}\right)}$$ $$k_2 = 6.2e5 \, \exp{\left(-\frac{5000}{T}\right)}$$ $$x(0) = [1 \; 0]^T$$ $$298 \le T \le 398$$ $$t_f=1$$