I just used scipy.odeint to solve a diff_equation system, and use matplotlib to plot it. I got the graphs. My question is can I get some specific data points, like when t = 1, what is x1, x2, x3. I need when t = 1,2,3,4..., what value of concentration is. Thank you.
import matplotlib.pyplot as plt
from scipy.integrate import odeint
Dose = 100
V = 43.8
k12 = 1.2 # rate of central -> peripheral
k21 = 1.4 # rate of peripheral -> central
kel = 0.20 # rate of excrete from plasma
def diff(d_list, t):
x1, x2, x3, = d_list
# X1(t), X2(t), X3(t)
return np.array([(-k12*x1-kel*x1 k21*x2),
(k12*x1-k21*x2),
(kel*x1)])
t = np.linspace(0, 24, 960)
result = odeint(diff, [(Dose/V), 0, 0], t)
plt.plot(t, result[:, 0], label='x1: central')
plt.plot(t, result[:, 1], label='x2: tissue')
plt.plot(t, result[:, 2], label='x3: excreted')
plt.legend()
plt.xlabel('t (hr)')
plt.ylabel('Concentration (mg/L)')
plt.show()
CodePudding user response:
This is not related to matplotlib or scipy. You can either interpolate or get the closest data point.
Interpolated value
If you need to get the x1, x2 and x3 for values of t which do not correspond to a data point (you mentioned 1,2,3,4 which are not in your t array), you will need to interpolate. To get x1, x2 and x3 at t=1, you can do (at the end of your script):
valuesAt1 = [np.interp(1, t, result[:,col]) for col in range(result.shape[1])]
The output of print(valuesAt1) is then:
[1.1059703843218311, 0.8813129004034452, 0.2958217381057726]
If you only need x1, just do
valuesAt1 = np.interp(1, t, result[:,0])
then, the output of print(valuesAt1) is:
1.1059703843218311
Closest data point
If you do not want to do interpolation but want the value of x1, x2 and x3 for the value of the t array element which is the closest from 1, do:
valuesAtClosestPointFrom1 = result[ np.argmin(np.abs(t-1))]
The output from print(valuesAtClosestPointFrom1) is:
[1.10563546 0.88141641 0.29605315]
CodePudding user response:
This can be done by interpolation and using scipy.interpolate.InterpolatedUnivariateSpline as follows:
from scipy.interpolate import InterpolatedUnivariateSpline
splx1 = InterpolatedUnivariateSpline(t, result[:,0])
splx2 = InterpolatedUnivariateSpline(t, result[:,1])
splx3 = InterpolatedUnivariateSpline(t, result[:,2])
Firstly, you need to pass the x and y data that you want to interpolate. Secondly, create a list for x for which you want the desired values of y.
import numpy as np
desired_time = np.arange(1,25)
x1 = splx1(desired_time)
x2 = splx2(desired_time)
x3 = splx3(desired_time)
Lastly, pass it to the respective spline object to get the desired values. For example, a desired_time array from 1 to 24 using np.arange is created and passed to the spline objects in the example above.
