[1]:
import numpy
import matplotlib.pyplot as plt
%matplotlib inline

3. Read simulation input from a file

It is often useful to read simulation inputs from a file. Let’s do this for our standard tank system.

d52e52a3386d4ad3a77f5870a63f1ca6

\begin{align} F_{out} &= kh\\ \frac{\mathrm{d}h}{\mathrm{d}t} &= \frac{1}{A}\left(F_{in} - F_{out}\right)\\ \end{align}

First we define the parameters of the system

[2]:
K = 1
A = 1

Then, we’ll read the values of \(F_{in}\) from an Excel file using pandas.read_excel.

[3]:
import pandas
[4]:
df = pandas.read_excel('../../assets/tankdata.xlsx')
df
[4]:
Time Fin
0 0 1.0
1 5 2.0
2 10 2.0
3 15 1.5
4 20 1.0
5 25 2.0
6 30 2.0

We’ll set this function up to interpolate on the above table for the value of \(F_in\) given a known time.

[5]:
def Fin(t):
    return numpy.interp(t, df.Time, df.Fin)

We can test for one value at a time

[6]:
Fin(1)
[6]:
1.2

interp also accepts vector inputs:

[7]:
tspan = (0, 30)
t = numpy.linspace(*tspan)
[8]:
plt.plot(t, Fin(t))
[8]:
[<matplotlib.lines.Line2D at 0x112b4c208>]
../../_images/1_Dynamics_2_Time_domain_simulation_Read_input_from_file_14_1.png

Now we’re ready to define our differential equation function:

[9]:
def dhdt(t, h):
    Fout = K*h
    return 1/A*(Fin(t) - Fout)
[10]:
h0 = 1
[11]:
import scipy.integrate
[12]:
sol = scipy.integrate.solve_ivp(dhdt, tspan, [h0], t_eval=t)
[13]:
plt.plot(sol.t, sol.y.T)
[13]:
[<matplotlib.lines.Line2D at 0x1513ee6b38>]
../../_images/1_Dynamics_2_Time_domain_simulation_Read_input_from_file_20_1.png
[ ]: