简体   繁体   中英

How can I solve a system of differential equations with constants in python?

I would like to solve the following system without defining the constants, using Python.

dx1(t)/dt = - kf1*x1(t)*x2(t) + kr1*x3(t)

dx2(t)/dt = - kf1*x1(t)*x2(t) + kr1*x3(t)

dx3(t)/dt = kf1*x1(t)*x2(t) - kr1*x3(t) - k2*(x3(t) - x4(t))

dx4(t)/dt = k2*(x3(t) - x4(t)) + kf3*x5(t)*x6(t) - kr3*x4(t)

dx5(t)/dt = -kf3*x5(t)*x6(t) + kr3*x4(t)

dx6(t)/dt = -kf3*x5(t)*x6(t) + kr3*x4(t)

x1(0)=x1_0,  x2(0)=x2_0 and x(3)=x(4)=x(5)=x(6)=0

I would like to solve the system without replacing kf1,kr1,k2,kf3,kr3,x1_0 and x2_0 with real numbers

Comment: I am describing the kinetic equations for a DNA Strand displacement reaction with (3), (4) and (5) being intermediate products,

(1) + (2) <--> (5) + (6)

I have tried using sympy and for defining my constants as symbols without success

from sympy import *

x1,x2,x3,x4,x5,x6 =symbols('x1 x2 x3 x4 x5 x6', cls=Function)

kf1,kr1,k2,kf3,kr3 = symbols("kf1 kr1 k2 kf3 kr3")

diffeqq1=Eq(x1(t).diff(t), - kf1*x1*x2 + kr1*x3)
diffeqq2=Eq(x2(t).diff(t), - kf1*x1*x2 + kr1*x3)
diffeqq3=Eq(x3(t).diff(t), kf1*x1*x2 - kr1*x3 - k2*(x3 - x4))
diffeqq4=Eq(x4(t).diff(t), k2*(x3 - x4) + kf3*x5*x6 - kr3*x4)
diffeqq5=Eq(x5(t).diff(t), -kf3*x5*x6 + kr3*x4)
diffeqq6=Eq(x6(t).diff(t), -kf3*x5*x6 + kr3*x4)

dsolve(system,[x1,x2,x3,x4,x5,x6])

The result I would like to have is a function between x1,x2,x5,x6 and the constants.

You define one vector function to contain the dynamic

def reactions(t,u):
    x1,x2,x3,x4,x5,x6 = u
    F1 = kf1*x1*x2
    R1 = kr2*x3
    FR2 = k2*(x3-x4)
    F3 = kf3*x5*x6
    R3 = kr3*x4
    return [ -F1+R1, -F1+R1, F1-R1-FR2, FR2+F3-R3, -F3+R3, -F3+R3]

and then call scipy.integrate.solve_ivp to solve the system over a sufficiently long time span,

res = solve_ivp(reactions, [t0, tf], x_init, dense_output=True, atol=1e-8, rtol=1e-6)
t = np.linspace(t0, tf, 702)
u = res.sol(t)
x1,x2,x3,x4,x5,x6 = u
plt.plot(t,x1,lw=3,label='$x_1$')
plt.plot(t,x2,lw=3,label='$x_2$')
plt.plot(t,x6,lw=3,label='$x_6$')
plt.grid(); plt.legend(); plt.show()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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