You can input the equation as a string (as seqn
). You can convert the string to an expression with the eval()
function. This evaluates the expression as if you had it in the code.
from gekko import GEKKO
seqn = '3*x+5==4*x' # input as string
m = GEKKO(remote=False)
x = m.Var()
m.Obj(x**2)
m.Equation(eval(seqn))
m.solve(disp=False)
print(x.value)
If the form of the equation is always the same, you can add parameter inputs such as p=m.Param()
and then set p.value=6
. This inserts a different number in your equation such as 3*x+p==(p-1)*x
when you need to solve the same equations multiple times but with different inputs.
from gekko import GEKKO
m = GEKKO(remote=False)
x = m.Var()
p = m.Param(5)
m.Obj(x**2)
m.Equation(3*x+p==(p-1)*x)
m.solve(disp=False)
print('Solution with p=5: ' + str(x.value))
p.value=6
m.solve(disp=False)
print('Solution with p=6: ' + str(x.value))
You can also add an input as a float or int as p=6
but this only works to set the value once because gekko
writes the model file with this constant. You can see the model file gk_model0.apm
by opening the run folder with m.open_folder()
.
Model
Variables
v1 = 0
End Variables
Equations
(((3)*(v1))+5)=((4)*(v1))
minimize ((v1)^(2))
End Equations
End Model
This APMonitor model file is compiled to byte-code each time there is a solve
command. Advanced users can add lines to this file with m.Raw()
but I don't recommend it unless there is a good understanding of the internal methods of APMonitor.