简体   繁体   English

Python odeint 与微分方程中的数组

[英]Python odeint with array in differential equation

I have next first order differential equation (example):我有下一个一阶微分方程(示例):

dn/dt=A*n; n(0)=28

When A is constant, it is perfectly solved with python odeint.当A为常数时,用python odeint完美解决。 But i have an array of different values of A from .txt file [not function,just an array of values]但是我有一个来自 .txt 文件的不同 A 值的数组[不是函数,只是一个值数组]

A = [0.1,0.2,0.3,-0.4,0.7,...,0.0028]

And i want that in each iteration (or in each moment of time t ) of solving ode A is a new value from array.我希望在求解 ode A 的每次迭代(或在时间t每个时刻)中都是来自数组的新值。 I mean that: First iteration (or t=0) - A=0.1 Second iteration (or t=1) - A=0.2 and etc from array.我的意思是:第一次迭代(或 t=0)- A=0.1 第二次迭代(或 t=1)- A=0.2 等来自数组。

How can i do it with using python odeint?我如何使用 python odeint 做到这一点?

Yes, you can to that, but not directly in odeint , as that has no event mechanism, and what you propose needs an event-action mechanism.是的,您可以这样做,但不能直接在odeint ,因为它没有事件机制,而您建议的内容需要事件-动作机制。

But you can separate your problem into steps, use inside each step odeint with the now constant A parameter, and then in the end join the steps.但是你可以把你的问题分成几个步骤,在每个步骤中使用odeint和现在常量A参数,然后最后加入这些步骤。

T = [[0]]
N = [[n0]]
for k in range(len(A)):
    t = np.linspan(k,k+1,11);
    n = odeint(lambda u,t: A[k]*u, [n0],t)
    n0 = n[-1]
    T.append(t[1:])
    N.append(n[1:])

T = np.concatenate(T)
N = np.concatenate(N)

If you are satisfied with less efficiency, both in the evaluation of the ODE and in the number of internal steps, you can also implement the parameter as a piecewise constant function.如果您对较低的效率感到满意,无论是在 ODE 的评估还是在内部步骤的数量上,您还可以将参数实现为分段常数函数。

tA = np.arange(len(A));
A_func = interp1d(tA, A, kind="zero", fill_value="extrapolate")
T = np.linspace(0,len(A)+1, 10*len(A)+11);
N = odeint(lambda u,t: A_func(t)*u, [n0], T)

The internal step size controller works on the assumption that the ODE function is well differentiable to 5th or higher order.内部步长控制器假设 ODE 函数可以很好地微分到 5 阶或更高阶。 The jumps are then seen via the implicit numerical differentiation inherent in the step error calculation as highly oscillatory events, requiring a very small step size.然后通过阶跃误差计算中固有的隐式数值微分将跳跃视为高度振荡事件,需要非常小的步长。 There is some mitigation inside the code that usually allows the solver to eventually step over such a jump, but it will require much more internal steps and thus function evaluations than the first variant above.代码内部有一些缓解措施,通常允许求解器最终跳过这样的跳跃,但与上述第一个变体相比,它需要更多的内部步骤,因此需要更多的函数评估。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM