字典的写函数与solve_ivp一起使用

问题描述 投票:0回答:1

我正在尝试使用solve_ivp解决大型微分方程组。

from scipy import integrate

def dXdt(X,t):
    return np.array([dadt(X,t), dbdt(X,t), dcdt(X,t), dddt(X,t])

sol = integrate.solve_ivp(dXdt, (0,100), initial_value_array, t_eval)

[dadt(X,t)dbdt(X,t)dcdt(X,t)dddt(X,t]是微分方程组,我需要从以下词典中获得:

da_dict = {'a': -1.0, 'b': 2.0, 'c': 4.0}
db_dict = {'b': -10.0, 'a': 1.0}
dc_dict = {'c': -4.0, 'b': 3.0}
dd_dict = {'b': 5.0}

如下:

def dadt(X,t):
    return -1.0*X[0] + 2*X[1] + 3*X[2]

其中,X[0]X[1]X[2]x[3]在词典中由'a''b''c''d'表示。同样,

def dbdt(X,t):
    return -10*X[1] + 1*X[0]

def dcdt(X,t):
    return -4*X[2] + 3*X[1]

def dddt(X,t):
    return 5*X[1]

我需要使用Solve_ivp解决100多个微分方程。如何从字典中写出dadt(X,t)dbdt(X,t) ....而没有实际写出它们?

python function differential-equations odeint
1个回答
0
投票

我不确定如何处理t参数,因为您在任何示例中都没有使用它。我将X和t的占位符值放在下面的代码中

我在下面写了一段代码,可能对您的示例有用。如果您已经写了所有词典,那么我会将您的词典列在列表中,您可以自己添加其他词典。

da_dict = {'a': -1.0, 'b': 2.0, 'c': 4.0}
db_dict = {'b': -10.0, 'a': 1.0}
dc_dict = {'c': -4.0, 'b': 3.0}
dd_dict = {'b': 5.0}

# associate the order of the coefficient letter to a position in the array.
order = {
    "a": 0,
    "b": 1,
    "c": 2,
    "d": 3,
    "e": 4
}

def equation_maker(X,t,equation):

    output_eq = 0
    # coeff: a,b,.. coeff_value: -1.0, 2.0,...
    for coeff,coeff_value in equation.items():
        output_eq += X[order.get(coeff)]*coeff_value
    return output_eq


equation_list = [da_dict,db_dict,dc_dict,dd_dict]
# output list of equations that you can convert to numpy arrays or whatever
diff_eq_list = []
# placeholder values for X and t
X = [0,1,2,3,4]
t = 0
for equation in equation_list:
    # assuming you have X and t from somewhere else
    diff_eq_list.append(equation_maker(X,t,equation))

print(diff_eq_list)

我还从未使用过scipy(但!),但我希望这可以帮助您不必编写所有功能,请告诉我这对您是否有用。

© www.soinside.com 2019 - 2024. All rights reserved.