Sympy and matrix differential ODE

Viewed 1214

How can I use Sympy to solve a matrix differential equation?

I have an equation of the form y'(t) = A*y(t) + B, where A is a 3x3 matrix, y(t) is a 1x3 vector, and B is a 1x3 vector.

More specifically, I'm working on a computer graphics problem that uses a differential equation to move points in 3D. I have a point in 3D space y(t), a 3x3 rotation matrix, and a translation vector. The y'=Ay+B equation is a simplification of the real problem I'm working on, but I've been unable to use Sympy to solve even y'=Ay+B. I am looking for the closed-form solution (not the numerical answer) in Sympy.

I know how to solve the equation y'=Ay+B, but I want to use Sympy to find the same solution, and then adapt the code to the more complex problem I'm trying to solve.

My current code is this:

from sympy import *

y0 = Function('y0')
y1 = Function('y1')
y2 = Function('y2')
t = symbols(('t'))
b0,b1,b2 = symbols(('b0:3'))

y = Matrix([y0(t), y1(t), y2(t)])
B = Matrix([b0,b1,b2])

ode = Eq(y.diff(t), y)

soln = dsolve(ode, y0(t),y1(t),y2(t))

but that causes the Python error

TypeError: cannot add <class 'sympy.matrices.immutable.ImmutableDenseMatrix'> and <class 'sympy.core.symbol.Dummy'>

In the above example, it's using the even more simplified example of y'=y+B, but even that's not working.

What's the best way to set problems like this up in Sympy?

1 Answers

dsolve expects flat lists or flat tuples, not matrices. To convert a column matrix A into a flat list, one can use the incantation A.T.tolist()[0] - that is, transpose, turn into a nested list [[x, y, z]], then take the 0th entry [x, y, z]. So, your code should be

ode = (y.diff(t) - y).T.tolist()[0]
soln = dsolve(ode, y.T.tolist()[0])

It is usually more convenient to pass the difference lhs-rhs instead of Eq(lhs, rhs), so I did that.

Sadly, the output is

[Eq(y0(t), C1*exp(t)), False, False] 

(in both 1.1.1 and 1.2), which is obviously a bug. The solution of linear ODE systems with more than two equations in SymPy is currently based on some college student's misunderstanding of an ODE course they took. This PR would fix most of those issues but it's abandoned.

Related