Logical Conditions in Optimization
Main.LogicalConditions History
Hide minor edits - Show changes to markup
(:toggle hide gekko7 button show='Show Python GEKKO Code':)
(:toggle hide gekko7 button show='Show Python GEKKO Code (Simulate)':)
(:toggle hide gekko8 button show='Show Python GEKKO Code (Optimize)':) (:div id=gekko8:) (:source lang=python:) from gekko import GEKKO m = GEKKO() x = m.Var(0.5) y = m.if3(x-3,6*m.exp(-x)+1,x) m.Minimize(y) m.solve() print(x.value[0],y.value[0]) (:sourceend:) (:divend:)
(:toggle hide gekko7 button show='Show Python GEKKO Code':) (:div id=gekko7:) (:source lang=python:) from gekko import GEKKO m = GEKKO() x = m.Param(0.5) y = m.Var() m.Equation(y==m.if3(x-3,6*m.exp(-x)+1,x)) m.solve() print(x.value[0],y.value[0]) (:sourceend:) (:divend:)
m.Obj((y+3)**2)
m.Minimize((y+3)**2)
m.Obj((y+3)**2)
m.Minimize((y+3)**2)
(:html:)
<div id="disqus_thread"></div> <script type="text/javascript"> /* * * CONFIGURATION VARIABLES: EDIT BEFORE PASTING INTO YOUR WEBPAGE * * */ var disqus_shortname = 'apmonitor'; // required: replace example with your forum shortname /* * * DON'T EDIT BELOW THIS LINE * * */ (function() { var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true; dsq.src = 'https://' + disqus_shortname + '.disqus.com/embed.js'; (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq); })(); </script> <noscript>Please enable JavaScript to view the <a href="https://disqus.com/?ref_noscript">comments powered by Disqus.</a></noscript> <a href="https://disqus.com" class="dsq-brlink">comments powered by <span class="logo-disqus">Disqus</span></a>
(:htmlend:)
plt.ylabel('y') plt.show() (:sourceend:) (:divend:)
(:toggle hide gekko6 button show='Show Python GEKKO if3 example':) (:div id=gekko6:)

(:source lang=python:) import numpy as np import matplotlib.pyplot as plt from gekko import GEKKO m = GEKKO(remote=False) p = m.Param(value=np.linspace(0,10,41))
- conditional statement
y = m.if3(p-4,p**2,-0.2*(p-4)+7) m.options.IMODE = 2 m.solve() lbl = r'$y=\mathrm{if3}(p-4,p^2,-0.2(p-4)+7)$' plt.plot(p,y,'bo',label=lbl) plt.text(1,5,r'$p^2$') plt.text(5,10,r'$-0.2 (p-4)+7$') plt.legend(loc=4)
(:toggle hide gekko5 button show='Show Python GEKKO min2 and max3 examples':) (:div id=gekko5:)

(:source lang=python:) import numpy as np import matplotlib.pyplot as plt from gekko import GEKKO m = GEKKO(remote=False) p = m.Param(value=np.linspace(10,20,21)) x = m.Var() m.Equation(x==p)
- with MPCCs
y2 = m.min2(p,15)
- with integer variables
y3 = m.max3(p,16) m.options.IMODE = 2 m.solve() plt.plot(p,x,'b-',label='x') plt.plot(p,y2,'g:',label='MPCC') plt.plot(p,y3,'r--',label='Integer Switch') plt.legend() plt.xlabel('x') plt.ylabel('y') plt.show() (:sourceend:) (:divend:)
- Max Function
- Min Function
- Max Function (see Python GEKKO max2 and max3 functions)
- Min Function (see Python GEKKO min2 and min3 functions)
- Piece-wise Linear Functions
- Piece-wise Linear Functions (see Python GEKKO pwl function)
- calculate x to minimize objective
- parameter
(:divend:)
- Example 4: Absolute Value at the Discontinuity
(:toggle hide gekko4 button show='Show Example 4 with Python GEKKO Binary Variable':) (:div id=gekko4:)
Python GEKKO binary variable in optimization (Success)
- with abs3 object
- calculate x to minimize objective
x = m.Var(1.0)
- define new binary variable
intb = m.Var(0,lb=0,ub=1,integer=True)
- define y
y = m.Var()
- define equations
m.Equation((1-intb)*x <= 0) m.Equation(intb * (-x) <= 0)
- output
m.Equation(y==(1-intb)*(-x) + intb*x)
- parameter
x = m.Param(-0.5)
- calculate y=abs(x) with abs3
y = m.abs3(x)
m.options.SOLVER=1
print('y: ' + str(y.value)) (:sourceend:) (:divend:)
- Example 4: Absolute Value at the Discontinuity
(:toggle hide gekko4 button show='Show Example 4 with Python GEKKO Binary Variable':) (:div id=gekko4:)
Python GEKKO binary variable in optimization (Success)
(:source lang=python:) from gekko import GEKKO
- define new GEKKO model
m = GEKKO()
- calculate x to minimize objective
x = m.Var(1.0)
- define new binary variable
intb = m.Var(0,lb=0,ub=1,integer=True)
- define y
y = m.Var()
- define equations
m.Equation((1-intb)*x <= 0) m.Equation(intb * (-x) <= 0)
- output
m.Equation(y==(1-intb)*(-x) + intb*x)
- solve with APOPT (MINLP solver)
m.options.SOLVER=1 m.solve()
- print solution
print('x: ' + str(x.value))
print('y: ' + str(y.value)) (:sourceend:)
(:source lang=python:)
- with abs3 object
from gekko import GEKKO
- define new GEKKO model
m = GEKKO()
- variable
x = m.Var(-0.5)
- calculate y=abs(x) with abs3
y = m.abs3(x)
- solve with APOPT (MINLP solver)
m.solve()
- print solution
print('x: ' + str(x.value))
Python GEKKO binary variable in simulation (Success)
Python GEKKO binary variable in optimization (Success)
(:toggle hide gekko2 button show='Show Example 2 with Python GEKKO ABS (Failure)':) (:div id=gekko2:)
(:toggle hide gekko2a button show='Show Example 2 with Python GEKKO ABS (Failure)':) (:div id=gekko2a:)
(:toggle hide gekko2 button show='Show Example 2 with Python GEKKO ABS2 (Success)':) (:div id=gekko2:)
(:toggle hide gekko2b button show='Show Example 2 with Python GEKKO ABS2 (Success)':) (:div id=gekko2b:)
x = m.Param(-0.5)
x = m.Var(1.0)
Python GEKKO ABS function (abs2)
(:toggle hide gekko1 button show='Show Example 1 with Python GEKKO':) (:div id=gekko1:)
- use abs2 to define a new variable
y = m.abs2(x)
- use abs2 in an equation
- use abs to define a new variable
y = m.abs(x)
- use abs in an equation
m.Equation(z==m.abs2(x)+1)
m.Equation(z==m.abs(x)+1)
(:divend:)
(:toggle hide gekko2 button show='Show Example 2 with Python GEKKO ABS (Failure)':) (:div id=gekko2:)
(:divend:)
(:toggle hide gekko2 button show='Show Example 2 with Python GEKKO ABS2 (Success)':) (:div id=gekko2:)
(:divend:)
(:toggle hide gekko3 button show='Show Example 3 with Python GEKKO Binary Variable':) (:div id=gekko3:)
Python GEKKO binary variable in simulation (Success)
(:source lang=python:) from gekko import GEKKO
- define new GEKKO model
m = GEKKO()
- calculate x to minimize objective
x = m.Param(-0.5)
- define new binary variable
intb = m.Var(0,lb=0,ub=1,integer=True)
- define y
y = m.Var()
- define equations
m.Equation((1-intb)*x <= 0) m.Equation(intb * (-x) <= 0)
- output
m.Equation(y==(1-intb)*(-x) + intb*x)
- solve with APOPT (MINLP solver)
m.options.SOLVER=1 m.solve()
- print solution
print('x: ' + str(x.value)) print('intb: ' + str(intb.value)) print('y: ' + str(y.value)) (:sourceend:) (:divend:)
(:toggle hide gekko4 button show='Show Example 4 with Python GEKKO Binary Variable':) (:div id=gekko4:)
Python GEKKO binary variable in simulation (Success)
(:source lang=python:) from gekko import GEKKO
- define new GEKKO model
m = GEKKO()
- calculate x to minimize objective
x = m.Param(-0.5)
- define new binary variable
intb = m.Var(0,lb=0,ub=1,integer=True)
- define y
y = m.Var()
- define equations
m.Equation((1-intb)*x <= 0) m.Equation(intb * (-x) <= 0)
- output
m.Equation(y==(1-intb)*(-x) + intb*x)
- solve with APOPT (MINLP solver)
m.options.SOLVER=1 m.solve()
- print solution
print('x: ' + str(x.value)) print('intb: ' + str(intb.value)) print('y: ' + str(y.value)) (:sourceend:) (:divend:)
GEKKO ABS function (abs2)
Python GEKKO ABS function (abs2)
In this case, the IPOPT solver reaches the default maximum number of iterations (100) and reports a failure to converge. Now if the problem is reformulated with an additional variable intb, the optimizer can find a solution to the same problem that failed with the abs(x) operator. The value of intb is a binary variable that can be either 0 or 1. The value of intb is zero when x<0 and is one when x>=0. The following two examples show that this reformulation allows the solver to quickly find a solution either away from or at the discontinuity.
Python GEKKO ABS function in optimization (Failure)
(:source lang=python:) from gekko import GEKKO
- define new GEKKO model
m = GEKKO()
- calculate x to minimize objective
x = m.Var(1)
- use abs to define y
y = m.abs(x)
- define objective to minimize
m.Obj((y+3)**2)
- solve
m.solve()
- print solution
print('x: ' + str(x.value)) print('y: ' + str(y.value)) (:sourceend:)
In this case, the IPOPT solver reaches the default maximum number of iterations (100) and reports a failure to converge. However, if another form with continuous first and second derivatives (abs2 in GEKKO) is used, a solution is found.
Python GEKKO ABS2 function in optimization (Success)
(:source lang=python:) from gekko import GEKKO
- define new GEKKO model
m = GEKKO()
- calculate x to minimize objective
x = m.Var(1)
- use abs2 to define y
y = m.abs2(x)
- define objective to minimize
m.Obj((y+3)**2)
- solve
m.solve()
- print solution
print('x: ' + str(x.value)) print('y: ' + str(y.value)) (:sourceend:)
Also, if the problem is reformulated with an additional binary variable intb, the optimizer can find a solution to the same problem that failed with the abs(x) operator. The value of intb is a binary variable that can be either 0 or 1. The value of intb is zero when x<0 and is one when x>=0. The following two examples show that this reformulation allows the solver to quickly find a solution either away from or at the discontinuity.
GEKKO ABS function (abs2)
(:source lang=python:) from gekko import GEKKO
m = GEKKO() x = m.Param(-1)
- use abs2 to define a new variable
y = m.abs2(x)
- use abs2 in an equation
z = m.Var() m.Equation(z==m.abs2(x)+1)
- solve
m.solve()
print('x: ' + str(x.value)) print('y: ' + str(y.value)) print('z: ' + str(z.value)) (:sourceend:)
Conditional statements can cause problems for gradient-based optimization algorithms because they are often posed in a form that gives discontinuous functions, first derivatives, or second derivatives. For example, the absolute value operator is a continuous function but gives a discontinuous first derivative at the origin.
Conditional statements can cause problems for gradient-based optimization algorithms because they are often posed in a form that gives discontinuous functions, first derivatives, or second derivatives.
(:html:) <iframe width="560" height="315" src="https://www.youtube.com/embed/NPUNixLGlh0" frameborder="0" allowfullscreen></iframe> (:htmlend:)
For example, the absolute value operator is a continuous function but gives a discontinuous first derivative at the origin.
MPECs: Mathematical Programs with Equilibrium Constraints
Mathematical Programs with Equilibrium Constraints (MPECs) are formulations that can also be used to model certain classes of discrete events. MPECs can be more efficient than solving mixed integer formulations of the optimization problems because it avoids the combinatorial difficulties of searching for optimal discrete variables.
- ABS: Absolute Value Operator (MPEC Form)
- MAX: Maximum Operator (MPEC Form)
- MIN: Minimum Operator (MPEC Form)
- Piecewise Linear Function without Object Use (MPEC Form)
- Piecewise Linear Function with PWL Object (MPEC Form)
- Piecewise Linear Function with LOOKUP and PWL Objects (MPEC Form)
- SIGN: Signum Operator (MPEC Form)
MPCCs: Mathematical Programs with Complementarity Constraints
Mathematical Programs with Complementarity Constraints (MPCCs) are formulations that can also be used to model certain classes of discrete events. MPCCs can be more efficient than solving mixed integer formulations of the optimization problems because it avoids the combinatorial difficulties of searching for optimal discrete variables.
- ABS: Absolute Value Operator (MPCC Form)
- MAX: Maximum Operator (MPCC Form)
- MIN: Minimum Operator (MPCC Form)
- Piecewise Linear Function without Object Use (MPCC Form)
- Piecewise Linear Function with PWL Object (MPCC Form)
- Piecewise Linear Function with LOOKUP and PWL Objects (MPCC Form)
- SIGN: Signum Operator (MPCC Form)
- Mathematical Programs with Equilibrium Constraints (MPECs)
- Mathematical Programs with Equilibrium/Complementarity Constraints (MPECs/MPCCs)
Two popular methods for reformulation of the conditional statements or operators is to either use:
Two popular methods for reformulation of the conditional statements is to either use:
Each of these techniques are described below with a number of examples. The approach taken above with the ABS function used a single binary variable. The ABS function can also be expressed as an MPEC as shown below.
Each of these techniques are described below with a number of examples.
- ABS: Absolute Value Operator (Integer Form)
The approach taken above with the ABS function used a single binary variable.
- ABS: Absolute Value Operator (Integer Form)
Piece-wise Linear (PWL) functions are one method to approximate any nonlinear function. The following example programs demonstrate a piece-wise linear function with binary decision variables. The sum of the binary decision variables is required to be one, meaning that only one of the linear approximations can be active at a time.
- Simulate Piecewise Linear Function with Binary Decision Variables
The value of x is now declared as a decision variable and is adjusted by the optimizer to minimize the objective function that is equal to y. By inspection, the optimal value is at x=2 giving a result of y=0.
- Optimize Piecewise Linear Function with Binary Decision Variables

The example shown above demonstrates a PWL function with one input and one output but it can also be extended to cases with multiple inputs and multiple outputs.
- Piecewise Linear Function without Object Use (MPEC Form)
- Piecewise Linear Function with PWL Object (MPEC Form)
- Piecewise Linear Function with LOOKUP and PWL Objects (MPEC Form)

The following examples demonstrate the use of conditional statements to switch between different functions. In this case, the function y=6*exp(-x)+1 if the value of x<3 else the function y=x is chosen when x>=3. The simulate example verifies that the correct value is reported with a fixed value of x. The second example shows how x can be adjusted to find a minimum value of y or f(x).


With three functions an if...elseif...else structure may be used. The following two examples show how to implement these conditional statements to achieve continuous first and second derivatives.

The solver can still converge because the solution is away from the discontinuity. In Example 2, the value of x is now determined by the optimizer. The objective function to minimize (y+3)2 means that the optimal solution is at x=0 and y==0. However, when the solution is at the discontinuity, a gradient based solver will often fail to converge.
The solver can still converge because the solution is away from the discontinuity. In Example 2, the value of x is now determined by the optimizer. The objective function to minimize (y+3)2 means that the optimal solution is at x=0 and y=0. However, when the solution is at the discontinuity, a gradient based solver will often fail to converge.
Logical Conditions with Integer Variables
Logical Conditions with Binary Variables
- ABS: Absolute Value Operator (Integer Form)

- IF: Conditional Statement with Two Functions - Simulate (Integer Form)
- IF: Conditional Statement with Two Functions - Optimize (Integer Form)

- IF: Conditional Statement with Three Functions - Simulate (Integer Form)
- IF: Conditional Statement with Three Functions - Optimize (Integer Form)
- Signum Function
- Signum Function (What is Signum?)
Conditional Statements in Optimization
Conditional Statements in Optimization
- Example 1: Absolute Value Operator
- Example 1: Absolute Value Operator Away from the Discontinuity
- Example 2: Absolute Value Operator in Optimization
- Example 2: Absolute Value Operator at the Discontinuity
In this case, the IPOPT solver reaches the default maximum number of iterations (100) and reports a failure to converge. Now if the problem is reformulated with an additional variable intb, the optimizer can find a solution to the same problem that failed with the abs(x) operator. The value of intb is a binary variable that can be either 0 or 1. The value of intb is zero when x<0 and is one when x>=0. The following two examples show that this reformulation allows the solver to quickly find a solution either away from or at the discontinuity.
- Example 3: Absolute Value away from the Discontinuity
- Example 4: Absolute Value at the Discontinuity
- Sign Operator
- Most other discontinuous functions
MPEC: Mathematical Programs with Equilibrium Constraints
Mathematical Programs with Equilibrium Constraints (MPECs) are formulations that can be used to model certain classes of discrete events. MPECs can be more efficient than solving mixed integer formulations of the optimization problems because it avoids the combinatorial difficulties of searching for optimal discrete variables.
SIGN Operator (MPEC Form)
Absolute Value (ABS) Operator
Minimum Selector (MIN) Operator
Maximum Selector (MAX) Operator
- Piece-wise Linear Functions
- Signum Function
- Other discontinuous functions
Two popular methods for reformulation of the conditional statements or operators is to either use:
- Binary or integer variables
- Mathematical Programs with Equilibrium Constraints (MPECs)
Each of these techniques are described below with a number of examples. The approach taken above with the ABS function used a single binary variable. The ABS function can also be expressed as an MPEC as shown below.
Logical Conditions with Integer Variables
MPECs: Mathematical Programs with Equilibrium Constraints
Mathematical Programs with Equilibrium Constraints (MPECs) are formulations that can also be used to model certain classes of discrete events. MPECs can be more efficient than solving mixed integer formulations of the optimization problems because it avoids the combinatorial difficulties of searching for optimal discrete variables.
- ABS: Absolute Value Operator (MPEC Form)
- MAX: Maximum Operator (MPEC Form)
- MIN: Minimum Operator (MPEC Form)
- SIGN: Signum Operator (MPEC Form)
Minimizing this function can cause a problem for solvers that rely on first and second derivative information to determine search directions for each iteration.
Minimizing this function can cause a problem for solvers that rely on first and second derivative information to determine search directions at each iteration. As an exercise, solve the following model that uses the absolute value operator.
- Example 1: Absolute Value Operator
The solver can still converge because the solution is away from the discontinuity. In Example 2, the value of x is now determined by the optimizer. The objective function to minimize (y+3)2 means that the optimal solution is at x=0 and y==0. However, when the solution is at the discontinuity, a gradient based solver will often fail to converge.
- Example 2: Absolute Value Operator in Optimization
The above examples demonstrate this concept with the absolute value operator. The same techniques can be applied to:
- If...Else Statements
- Max Function
- Min Function
- Sign Operator
- Most other discontinuous functions
(:title Logical Conditions in Optimization:) (:keywords if conditions, maximum, minimum, max operator, min operator, sign operator, APMonitor, summation:) (:description Formulate conditional statements in numerical optimization so that the problem can be solved with gradient based approaches.:)
Conditional Statements in Optimization
Conditional statements can cause problems for gradient-based optimization algorithms because they are often posed in a form that gives discontinuous functions, first derivatives, or second derivatives. For example, the absolute value operator is a continuous function but gives a discontinuous first derivative at the origin.

Minimizing this function can cause a problem for solvers that rely on first and second derivative information to determine search directions for each iteration.
MPEC: Mathematical Programs with Equilibrium Constraints
Mathematical Programs with Equilibrium Constraints (MPECs) are formulations that can be used to model certain classes of discrete events. MPECs can be more efficient than solving mixed integer formulations of the optimization problems because it avoids the combinatorial difficulties of searching for optimal discrete variables.
SIGN Operator (MPEC Form)
Absolute Value (ABS) Operator
Minimum Selector (MIN) Operator
Maximum Selector (MAX) Operator
(:html:)
<div id="disqus_thread"></div> <script type="text/javascript"> /* * * CONFIGURATION VARIABLES: EDIT BEFORE PASTING INTO YOUR WEBPAGE * * */ var disqus_shortname = 'apmonitor'; // required: replace example with your forum shortname /* * * DON'T EDIT BELOW THIS LINE * * */ (function() { var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true; dsq.src = 'https://' + disqus_shortname + '.disqus.com/embed.js'; (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq); })(); </script> <noscript>Please enable JavaScript to view the <a href="https://disqus.com/?ref_noscript">comments powered by Disqus.</a></noscript> <a href="https://disqus.com" class="dsq-brlink">comments powered by <span class="logo-disqus">Disqus</span></a>
(:htmlend:)