How do I need to setup m.time
and update the initial conditions if I want to use GEKKO in an online simulation that updates every second? I have tried:
JavaScript
x
7
1
m.time = np.linspace(0,1,2)
2
while simulation_on:
3
m.solve()
4
x1.value = x1.value.value
5
x2.value = x2.value.value
6
x3.value = x3.value.value
7
but it doesn’t seem to update the values. I’m using IMODE = 4
This is just a dynamic simulation application. No control at the moment.
Advertisement
Answer
Gekko manages the initial conditions automatically when m.options.TIME_SHIFT=1
(default). Below is a simple example with a simulation loop and a single input and single output.
JavaScript
1
29
29
1
import numpy as np
2
from gekko import GEKKO
3
import matplotlib.pyplot as plt
4
5
m = GEKKO() # create GEKKO model
6
n = 10
7
m.time = np.linspace(0,n,n+1) # time points
8
9
# input step 0 to 0.5 at t=3
10
us = np.zeros_like(m.time); us[3:] = 0.5
11
u = m.Param(0)
12
x = m.Var(0.0)
13
m.Equation(2*x.dt()==-x+4*u)
14
m.options.IMODE = 4
15
16
xs=[0]
17
for i in range(n):
18
u.value=us[i] # new input
19
m.solve(disp=False)
20
xs.append(x.value[1])
21
22
# plot results
23
plt.plot(m.time,us,'ro',label='u(t)')
24
plt.plot(m.time,xs,'bx-',label='x(t)')
25
plt.ylabel('values')
26
plt.xlabel('time')
27
plt.legend(loc='best')
28
plt.show()
29
The initial condition can be adjusted if it needs to change cycle-to-cycle such as with:
JavaScript
1
4
1
if i==5:
2
xs[i]=5
3
x.value = xs[i]
4
JavaScript
1
32
32
1
import numpy as np
2
from gekko import GEKKO
3
import matplotlib.pyplot as plt
4
5
m = GEKKO() # create GEKKO model
6
n = 10
7
m.time = np.linspace(0,n,n+1) # time points
8
9
# input step 0 to 0.5 at t=3
10
us = np.zeros_like(m.time); us[3:] = 0.5
11
u = m.Param(0)
12
x = m.Var(0.0)
13
m.Equation(2*x.dt()==-x+4*u)
14
m.options.IMODE = 4
15
16
xs=[0]
17
for i in range(n):
18
u.value=us[i] # new input
19
if i==5:
20
xs[i]=5
21
x.value = xs[i]
22
m.solve(disp=False)
23
xs.append(x.value[1])
24
25
# plot results
26
plt.plot(m.time,us,'ro',label='u(t)')
27
plt.plot(m.time,xs,'bx-',label='x(t)')
28
plt.ylabel('values')
29
plt.xlabel('time')
30
plt.legend(loc='best')
31
plt.show()
32
There was a bug just in Gekko v1.0.1
that may affect these results. I recommend upgrading with pip install gekko --upgrade
to the latest version.