Skip to content Skip to sidebar Skip to footer

How To Set Variable Value At X[3]=6 (not Initial Condition) In Python Gekko?

I can set an initial condition y(0)=5 in Gekko with y = m.Var(5) but how do I set a value that is not the initial condition such as y(3)=6 where the value at time=3 is 6 as shown b

Solution 1:

The first thing is to make the initial condition calculated with fixed_initial=False option when you specify x=m.Var(). The model building function m.fix() can fix any point in the horizon such as with m.fix(x,pos=3,val=6) but this also fixes the derivative at that point.

An alternative method is to specify an objective to minimize the deviation from the value of 6 at time=3.

pi = np.zeros(11); pi[3]=1
p = m.Param(pi)
m.Minimize(p*(x-6)**2)

This creates the objective everywhere but p is only non-zero at time=3.

Free initial condition

from gekko import GEKKO
import numpy as np
import matplotlib.pyplot as plt
m = GEKKO(remote=False)
m.time = np.linspace(0,10,11)
x = m.Var(np.zeros(11)*6,fixed_initial=False)
m.Equation(5*x.dt() == -x)
pi = np.zeros(11); pi[3]=1
p = m.Param(pi)
m.Minimize(p*(x-6)**2)
m.options.IMODE = 6
m.solve()
plt.plot(m.time, x.value)
plt.plot([3],[6],'ro',MarkerSize=5)
plt.show()

Solution 2:

The Bryson benchmark problem (see #2) shows four ways to fix values that are not initial conditions.

if option == 1:
    # most likely to cause DOF issues because of many #  zero (0==0) equations
    m.Equation(final*x1 == 0)
    m.Equation(final*x2 == 0) 
elif option == 2:
    # inequality constraint approach is better but there#   are still many inactive equations
    m.Equation((final*x1)**2 <= 0)
    m.Equation((final*x2)**2 <= 0)
elif option == 3: #requires GEKKO version >= 0.0.3a2# fix the value just at the endpoint (best option)
    m.fix(x1,pos=nt-1,val=0)
    m.fix(x2,pos=nt-1,val=0)
else:
    #penalty method ("soft constraint") that may influence# optimal solution because there is just one# combined objective and it may interfere with# minimizing myObj
    m.Obj(1000*(final*x1)**2)
    m.Obj(1000*(final*x2)**2)

m.Obj(myObj*final)

This code could be adapted to have a point in the middle.

Post a Comment for "How To Set Variable Value At X[3]=6 (not Initial Condition) In Python Gekko?"