3
votes

I'm trying to solve an optimization problem with GEKKO using python, I'm trying to develop some mathematical function with log and sqrt and I figure out that I should use gekko operator instead of using numpy or math function. I wanted to know how to implement log base 2 instead of log or log10 using gekko.

gk = GEKKO()
gk.log(...) # work
gk.sqrt(...) # work
gk.log2(...) # does not work!

Error :

AttributeError: 'GEKKO' object has no attribute 'log2'
2

2 Answers

3
votes

Instead you can change the log base using the rule:

log2(x) = gk.log(x)/gk.log(2)

You can't expect for it to have all of the log bases implemented.

1
votes

You can create a log2 function in Gekko, especially if you need to use it multiple times throughout your model.

def glog2(x):
    return gk.log(x)/np.log(2) 

Below is a complete script that demonstrates the use of the new log2 function and shows the agreement with the Numpy log2 function.

log2 Gekko function

from gekko import GEKKO
import numpy as np

# compare with numpy
xnp = np.logspace(-1,4,100)
ynp = np.log2(xnp)

gk = GEKKO(remote=False)
x = gk.Param(xnp)
y,z = gk.Array(gk.Var,2)

# define a new log2 function
def glog2(x):
    return gk.log(x)/np.log(2) 

gk.Equation(y==glog2(x))
gk.options.IMODE=2; gk.solve(disp=False)

import matplotlib.pyplot as plt
plt.semilogx(xnp,ynp,'b-',lw=4,label=r'$y=\log_2(x)$ Numpy')
plt.semilogx(x.value,y.value,'r--',lw=2,label=r'$y=\log_2(x)$ Gekko')
plt.legend(); plt.xlabel('x'); plt.ylabel('y'); plt.grid(); plt.show()