Search code examples
pythonmatrixscipysystemdifferential-equations

Solving 1st order differential equations for matrices


I'd like to code in python a coupled system of differential equations : dF/dt=A(F) where F is a matrix and A(F) is a function of the matrix F.

When F and A(F) are vectors the equation is solved using scipy.integrate.odeint.

However, scipy.integrate.odeint doesn't work for matrices, and I get an error :

tmin, tmax, tstep = (0., 200., 1)
t_test=np.arange(tmin, tmax, tstep) #time vector

dydt_testm=np.array([[0.,1.],[2.,3.]])
Y0_test=np.array([[0,1],[0,1]])

def dydt_test(y,t):
    return dydt_testm

result = si.odeint(dydt_test, Y0_test,t_test)

ValueError: Initial condition y0 must be one-dimensional.


Solution

  • As commented by Warren Weckesser in the comments, odeintw does the job.

    from odeintw import odeintw
    import numpy as np
    
    Y0_test=np.array([[0,1],[0,1]])
    tmin, tmax, tstep = (0., 200., 1)
    t_test=np.arange(tmin, tmax, tstep) #time vector
    
    dydt_testm=np.array([[0.,1.],[2.,3.]])
    
    def dydt_test(y,t):
        return dydt_testm
    
    result = odeintw(dydt_test, #Computes the derivative of y at t 
                                         Y0_test,               #Initial condition on y (can be a vector).
                                         t_test)
    plt.plot(t_test,result[:,0,1])
    plt.show()