求解具有 python 中随时间变化的系数的常微分方程 (odeint)
solve ordinary differential equation with time dependent coefficients in python (odeint)
我想使用 scipy 的 odeint 函数求解具有 15 个时间相关系数的 7 个常微分方程 (ODE) 的系统。
我将我的系数存储在字典中,以便我可以通过我定义为与 odeint() 一起使用的函数 (func) 中的键名访问它们。系数取决于时间,因此在每个系数的字典中,我将函数称为 time_dep(t)。但是,由于我的字典存储在 odeint() 使用的函数之外,所以我在开始时初始化了一个时间变量 t = 0。现在我担心当 odeint() 分析访问系数时,它们会保持不变(在 t = 0 时)。
任何帮助将不胜感激!
这是一个最小工作示例的尝试,它并不完美,但我打印出系数值并且它没有改变,这是我不想要的 :) :
import numpy as np
import matplotlib.pyplot as plt
from scipy.integrate import odeint
t = 0
def time_dep(t):
return (10 * np.exp(-t))
coefficients = {'coeff1' : 1 + time_dep(t)}
def func(state, t, coefficients):
mrna = state[0]
protein = state[1]
dt_mrna = coefficients['coeff1'] * mrna * protein
dt_protein = coefficients['coeff1'] * protein
print(coefficients['coeff1'])
return[dt_mrna,dt_protein]
state0 = [1,1]
t = np.arange(0,100,0.1)
solve = odeint(func,state0,t,args=(coefficients,))
plt.plot(t,solve)
plt.show()
字典应包含函数而不是评估值(如现在):
coefficients = {'coeff1' : lambda x: 1+time_dep(x)}
然后获取函数并在正确的时间调用:
dt_mrna = coefficients['coeff1'](t) * mrna * protein
您已将单个数字 1 + time_dep(0)
存储为 coefficients['coeff1']
的值。与其这样做,不如将函数本身存储在字典中,并在 func()
中调用函数。像这样:
coefficients = {'coeff1' : time_dep}
def func(state, t, coefficients):
mrna = state[0]
protein = state[1]
c1 = 1 + coefficients['coeff1'](t)
dt_mrna = c1 * mrna * protein
dt_protein = c1 * protein
return [dt_mrna, dt_protein]
我想使用 scipy 的 odeint 函数求解具有 15 个时间相关系数的 7 个常微分方程 (ODE) 的系统。
我将我的系数存储在字典中,以便我可以通过我定义为与 odeint() 一起使用的函数 (func) 中的键名访问它们。系数取决于时间,因此在每个系数的字典中,我将函数称为 time_dep(t)。但是,由于我的字典存储在 odeint() 使用的函数之外,所以我在开始时初始化了一个时间变量 t = 0。现在我担心当 odeint() 分析访问系数时,它们会保持不变(在 t = 0 时)。
任何帮助将不胜感激!
这是一个最小工作示例的尝试,它并不完美,但我打印出系数值并且它没有改变,这是我不想要的 :) :
import numpy as np
import matplotlib.pyplot as plt
from scipy.integrate import odeint
t = 0
def time_dep(t):
return (10 * np.exp(-t))
coefficients = {'coeff1' : 1 + time_dep(t)}
def func(state, t, coefficients):
mrna = state[0]
protein = state[1]
dt_mrna = coefficients['coeff1'] * mrna * protein
dt_protein = coefficients['coeff1'] * protein
print(coefficients['coeff1'])
return[dt_mrna,dt_protein]
state0 = [1,1]
t = np.arange(0,100,0.1)
solve = odeint(func,state0,t,args=(coefficients,))
plt.plot(t,solve)
plt.show()
字典应包含函数而不是评估值(如现在):
coefficients = {'coeff1' : lambda x: 1+time_dep(x)}
然后获取函数并在正确的时间调用:
dt_mrna = coefficients['coeff1'](t) * mrna * protein
您已将单个数字 1 + time_dep(0)
存储为 coefficients['coeff1']
的值。与其这样做,不如将函数本身存储在字典中,并在 func()
中调用函数。像这样:
coefficients = {'coeff1' : time_dep}
def func(state, t, coefficients):
mrna = state[0]
protein = state[1]
c1 = 1 + coefficients['coeff1'](t)
dt_mrna = c1 * mrna * protein
dt_protein = c1 * protein
return [dt_mrna, dt_protein]