Gekko, dynamically limit lower bound of variables based on intervals

Viewed 262

For example if I have a variable f I want the lower bound to be

  • 0.1 if f < 0.25
  • 0.75 if f < 1
  • 1.25 if f < 1.5
  • 1.7 if f >= 1.5

I've tried the following to no avail

limit1 = m.if3(f-0.25, 0.1, 0.25)
limit2 = m.if3(f-1,limit1, 0.75)
limit3 = m.if3(f-1.5, limit2, 1.7)
f.lower = limit3.value
f.upper = 3

This seems to be able to set the lower bound correctly but when I do

print(f.lower,"<", f.value,"<", f.upper)

I get [0.1] < [constant value independent of lower bound] < 3

Now, I have multiple variables like f in an array with differing lower bound possibilities and all have the exact same values, as if the lower bound didn't even matter

When writing

f.lower=f1

then when I print f.lower.value I get

[correct lower bound] < [upper bound] < upper bound

I'm probably approaching the problem wrong, so I would love some help.

1 Answers

The .lower and .upper values of a Gekko variable have a single value and are not adjustable by the optimizer during the iterations.

You can generate any arbitrary relationship (like a step function) with a Piecewise linear pwl function such as shown in the Model Building Methods. In your case, you want the lower bound to change as the value of f changes. Here is one implementation just for showing the function for lower as it depends on f:

Piecewise linear function

from gekko import GEKKO
import numpy as np
m = GEKKO()
f = m.Param(np.linspace(0,2,200))
lower = m.Var()

d=1e-5
x_data = [-1e5,0.25,0.25+d,1,1+d,1.5,1.5+d,1e5]
y_data = [0.1,0.1,0.75,0.75,1.25,1.25,1.7,1.7]

m.pwl(f,lower,x_data,y_data)
#m.Equation(f>=lower)

m.options.IMODE = 2
m.solve()

import matplotlib.pyplot as plt
plt.plot(f,lower,'b--')
plt.plot(x_data,y_data,'ro')
plt.xlim([0,2])
plt.show()

I commented out the equation m.Equation(f>=lower) because I have f values that are lower than 0.1 and this creates an infeasible solution. Another way to solve this problem is to use binary variables as shown in the discussion of logical conditions in optimization. There is also an example in APMonitor of solving piecewise discontinuous functions with binary variables.

Related