Optimization Modeling Languages

Learning outcomes

  • Explain why an interior-point solver needs the exact Jacobian and Hessian that a modeling language supplies.
  • Write one dynamic model as equations, as a GEKKO model and as the simulation an app runs, and match the three term by term.
  • Compute the degrees of freedom of a GEKKO model and use the count to check a model written by an assistant.

Book chapter: Process Dynamics, Modeling, and Identification (Volume 1), Chapter 2, Gravity-Drained Tank Laboratory for Level Loops With a Moving Time Constant (PDF).
Practice in 15 minutes: 1 · A Physics-Based Model With a Moving Time Constant
Model: Physics-based here (a gravity-drained tank), but the language takes data-driven and combined models the same way.
Decision: The solver chooses every discretized state and input at once, using exact first and second derivatives from the language.
Learning: A trained network or regression written as equations gets the same exact derivatives, so it can sit inside the optimizer.

Two tools used in this course are MATLAB and Python. Python Gekko is a package within Python to provide support for solution of dynamic simulation, estimation, and control.

There are many tools for simulation and optimization of dynamic systems. There are also many factors to consider when selecting the appropriate tool for a particular task. Some of the considerations for a dynamic optimization tool are size (scaling with number equations and degrees of freedom), speed (use in real-time estimation or control), usability (training requirements and ease of adaptation), extensibility (ability to modify for new or complex systems), support (commercial sustainability or open-source community), and portability (ability to embed on a system or communicate with a particular platform).

Here is a list of some of the most popular optimization packages in Matlab:

  • fmincon: This is a built-in function in Matlab that implements a variety of optimization algorithms for constrained nonlinear optimization.
  • fminunc: This is another built-in function in Matlab that implements a variety of optimization algorithms for unconstrained nonlinear optimization.
  • linprog: This is a built-in function in Matlab that implements linear programming algorithms for solving optimization problems with linear constraints.
  • quadprog: This is a built-in function in Matlab that implements quadratic programming algorithms for solving optimization problems with quadratic objective functions and linear constraints.
  • Global Optimization Toolbox: This is a toolbox in Matlab that provides a variety of algorithms for global optimization, including genetic algorithms, particle swarm optimization, and simulated annealing.

Here is a list of some of the most popular optimization packages in Python:

  • scipy.optimize: This is a module in the SciPy library that provides a variety of optimization algorithms for solving nonlinear optimization problems.
  • cvxpy: This is a package that provides a modeling language for convex optimization problems, and it has interfaces to several solvers including CVXOPT, ECOS, and SCS.
  • gekko: This is a package that provides a modeling language for linear, nonlinear, and mixed integer programming problems, and it has interfaces to several solvers including IPOPT, APOPT, and BPOPT.
  • pygmo: This is a package that provides a variety of optimization algorithms for global optimization, including genetic algorithms, particle swarm optimization, and simulated annealing.
  • PyOpt: This is a package that provides a variety of optimization algorithms for solving nonlinear optimization problems, including gradient-based and derivative-free methods.

The objective of this section is to introduce optimization in MATLAB and Python. This is not intended to be a general tutorial but more specifically to cover topics that are relevant for dynamic optimization. Topics of interest for dynamic optimization are listed below.

Introduction to Nonlinear Optimization

This course uses principles from nonlinear programming but does not delve into the details of solution strategies. Instead of detailing how a nonlinear programming solver iterates to find a solution, this course focuses on formulating problems and the use of differential constraints in describing and optimizing dynamic systems. For more background on how nonlinear programming solvers work, refer to the Course on Optimization and the associated online Design Optimization Textbook. A good illustrative example is the Two Bar Truss optimization or the example below.

Why a Modeling Language Gives Exact Derivatives

After discretization in time, a dynamic optimization problem is a large nonlinear program in one vector `z` that holds the states, algebraic variables and inputs at every time point:

$$\min_{z} \; J(z) \quad \text{subject to} \quad c(z) = 0, \qquad z_L \le z \le z_U$$

The constraints `c(z) = 0` are the model equations at every time point. An interior-point solver such as IPOPT takes Newton steps on the optimality conditions. Each step solves this linear system, which needs the constraint Jacobian `\nabla c` and the Hessian of the Lagrangian `W`:

$$\begin{gathered} \begin{bmatrix} W_k + \Sigma_k & \nabla c(z_k) \\ \nabla c(z_k)^T & 0 \end{bmatrix} \begin{bmatrix} \Delta z \\ \Delta \lambda \end{bmatrix} = -\begin{bmatrix} \nabla \varphi_\mu(z_k) + \nabla c(z_k)\, \lambda_k \\ c(z_k) \end{bmatrix}, \\ W_k = \nabla^2_{zz}\left(J + c^T \lambda\right) \end{gathered}$$

Here `\lambda` are the multipliers of the equations, `\varphi_\mu` is the objective plus the log-barrier terms for the bounds with barrier parameter `\mu`, and `\Sigma_k` is the diagonal matrix those barrier terms contribute. A modeling language builds `\nabla c` and `W` exactly by automatic differentiation and passes their sparsity pattern, so the matrix above can have hundreds of thousands of rows and still factor quickly. Finite differences through a simulator would need one model run per variable for `\nabla c` and give only approximate second derivatives.

One Model Three Ways

A gravity-drained tank with cross-section `A_c`, inlet flow `q_{in}` and outlet coefficient `c_v`:

$$A_c \frac{dh}{dt} = q_{in} - c_v \sqrt{h}$$

The same model in GEKKO, simulated for a step in inlet flow:

import numpy as np
from gekko import GEKKO
m = GEKKO(remote=False)
m.time = np.linspace(0, 60, 61)          # s
Ac, cv = 0.5, 0.05                       # m^2, m^2.5/s
qin = m.Param(value=0.02)                # m^3/s
h = m.Var(value=0.10, lb=0)              # m
m.Equation(Ac*h.dt() == qin - cv*m.sqrt(h))
m.options.IMODE = 4                      # dynamic simulation
m.solve(disp=True)                       # the summary lists variables, equations and degrees of freedom

The Tank Level Control Studio app integrates a tank of this kind, with the outlet coefficient scaled by a valve opening, in the browser. Matching the three term by term (the area, the square-root outflow and the units of `c_v`) is the first check on any model.

An assistant writes GEKKO fluently. The degrees of freedom are how to check what it wrote: the number of variables less the number of equations. A simulation (IMODE 4) must have zero. An optimization must have one free value for each decision the problem is meant to have. GEKKO prints the count in its solver summary when `disp=True`.

GEKKO (Python)

GEKKO Python is designed for large-scale optimization and accesses solvers of constrained, unconstrained, continuous, and discrete problems. Problems in linear programming, quadratic programming, integer programming, nonlinear optimization, systems of dynamic nonlinear equations, and multi-objective optimization can be solved. The platform can find optimal solutions, perform tradeoff analyses, balance multiple design alternatives, and incorporate optimization methods into external modeling and analysis software. It is free for academic and commercial use under the MIT license.

Gekko Documentation

The GEKKO package is available through the package manager pip in Python.

python -m pip install gekko

View Source for 18 GEKKO Example Solutions

APMonitor (MATLAB and Python)

APMonitor is a tool for nonlinear optimization and dynamic optimization. Source files are available for Julia, Python, and MATLAB. Users can select either a public server or a local host if the APMonitor Server is installed locally. The user must also specify an application name.

 server = 'https://127.0.0.1'         # for local server
 server = 'https://byu.apmonitor.com' # for public server
 app = myApp                         # application name

Once the server and application name are defined, the following is a list of available commands in each package.

  • apm(server,app,aline) - Send commands to the server
    • Typical commands are 'clear all', 'clear csv', 'clear apm', 'solve'.
    • 'clear all': Clear the prior application
    • 'clear csv': Clear just the data file (CSV)
    • 'clear apm': Clear just the model file (APM)
    • 'solve': Solve the problem
  • apm_get(server,app,filename) - Retrieve a file from the server
  • apm_info(server,app,type,aline) - Classify a parameter or variable]]
    • More information about FV, MV, SV, and CV types
    • Type FV: Fixed value, one decision or fixed value over the time horizon
    • Type MV: Manipulated variable, multiple decision values over the horizon
    • Type SV: State variable, view in web-viewer but don't control
    • Type CV: Controlled variable with target variable
  • apm_ip(server) - Retrieve the client IP address
  • apm_load(server,app,filename) - Load model file
  • apm_meas(server,app,name,value) - Specify a measurement
  • apm_option(server,app,name,value) - Set an option
  • apm_sol(server,app) - Retrieve the solution
  • apm_tag(server,app,name) - Retrieve an NLC, FV, MV, SV, or CV option
  • apm_web(server,app) - Open a web interface to the dashboard
  • apm_web_var(server,app) - Open a web interface to the variable values
  • csv_load(server,app,filename) - Load data file

An example script is below. The same commands are used in Python, MATLAB, and Julia with minor modifications such as the ';' in MATLAB to suppress console output or change in the comment characters.

# import apm.py, available from
#   https://apmonitor.com/wiki/index.php/Main/PythonApp
from apm import *
# for MATLAB use: addpath('apm')

s = 'https://byu.apmonitor.com'
a = 'myApp'

# clear prior application
apm(s,a,'clear all')

# load model and data
apm_load(s,a,'model.apm')
csv_load(s,a,'data.csv')

# specify FV, MV, SV, CV
apm_info(s,a,'FV','K')
apm_info(s,a,'MV','u')
apm_info(s,a,'SV','x')
apm_info(s,a,'CV','y')

# configuration parameters
apm_option(s,a,'nlc.imode',6)
apm_option(s,a,'nlc.nodes',3)

# turn on MV as a degree of freedom
apm_option(s,a,'u.status',1)
# turn on CV to add terms to objective function
apm_option(s,a,'y.status',1)

# tune MV in the controller
apm_option(s,a,'u.lower',0)
apm_option(s,a,'u.upper',100)
apm_option(s,a,'u.dcost',0.1)

# tune CV in the controller
apm_option(s,a,'y.tau',5)
apm_option(s,a,'y.sphi',26)
apm_option(s,a,'y.splo',24)

# solve and retrieve results
output = apm(s,a,'solve')
print(output)

# open web-viewer
apm_web(s,a)

# retrieve solution
z = apm_sol(s,a)

Generative AI Learning

"Here is a gravity-drained tank, Ac dh/dt = qin - cv sqrt(h). Write it in GEKKO twice: once as a simulation with qin fixed, and once as a control problem where qin is a manipulated variable chosen to reach h = 0.3 m. For each version, tell me the number of variables, equations and degrees of freedom the solver will report."

Check the answer: Run both with disp=True and read the degrees of freedom from the summary. The simulation must report zero and the control version a positive count. If the assistant's counts differ from the solver's, or the simulation is not zero, a quantity was declared with the wrong type or an equation is missing.

Discussion Questions

  1. A modeling language (GEKKO, APMonitor) and a solver (IPOPT, APOPT) are different tools. Which failures belong to the formulation and which to the solver - and why does exact first and second derivative information (automatic differentiation) matter so much compared with finite differences through an ODE integrator?
  2. scipy.optimize.minimize can, in principle, solve a discretized optimal control problem. What does it lack (sparsity exploitation, constraint handling, AD) that makes it collapse at a few hundred variables where a modeling language handles hundreds of thousands?
  3. Declaring a quantity as an FV, MV, SV, or CV changes nothing about the physics. What does it change about the optimization problem that gets built?
  4. AI assistants now write GEKKO models on request. The syntax is usually right; what still has to be audited by an engineer (variable classification, degrees of freedom, units, bounds, objective sign), and which of those errors would run without any warning and return a confidently wrong answer?

Tip: Try it: ask an AI to write a GEKKO model for a system you already solved, then diff its formulation against yours - classification, bounds, and objective - before ever running it. The audit is faster than the debug.

Course Information

TCLab

Project

Applications

Advanced Control Exercises

Exams

Modeling

Machine Learning

Estimation

Control

Reinforcement Learning

Related Courses

Admin