Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Poor sympy linsolve/ solve performance

I'm using sympy to solve a simple linear system of equations.

It's a coupled ODE, there are time-derivatives of variables and I need to solve the system of equations for the highest derivatives. Since sympy doesn't allow me to solve for statements like phi_1.diff(t), I've replaced all derivatives with placeholder symbols.

For example:

phi.diff(t).diff(t) + phi(t) =0

becomes

ddphi + phi(t) = 0

This works fine. The solutions are correct and I can simulate the system - it's a pendulum: https://youtu.be/Gc_V2FussNk

The problem is that solving the system of equations (with linsolve) takes very long.

For just 2 equations, it takes 2 seconds. For 3 equations, it's still calculating (after over 10 minutes).

EDIT: @asmeurer advised me to try out solve instead. For n=3, linsolve took about 34 minutes - I only made one measurement. solve takes 31 seconds (averages over 3 runs).

Still, I believe that a linear 3x3 system should be solved in fractions of a second.

And for n=4 solve becomes unbearably slow, too (still calculating)

I've formatted the code and created an iPython notebook: http://nbviewer.jupyter.org/gist/lhk/bec52b222d1d8d28e0d1baf77d545ec5 If you scroll down a little, you can see the formatted output of the system of equations and directly below that the call to linsolve

The equations are rather long but strictly linear in the second derivatives. I'm sure that this system can be solved. All I need to do is solve a 3x3 system of linear equations where the coefficients might be symbols.

Is there a more performant way to do this ?

like image 853
lhk Avatar asked Feb 06 '23 17:02

lhk


2 Answers

solve (not linsolve) has some flags that you can set which can make it faster:

  • simplify=False: disables simplification of the result.
  • rational=False: disables the automatic conversion of floats to rationals.

There is a warning in the solve docstring that rational=False can lead to some equations not being solvable due to issues in the polys, so be aware that that's a potential issue.

like image 182
asmeurer Avatar answered Feb 11 '23 18:02

asmeurer


I have found that solve can be very slow in jupyter notebook if you have run sp.init_printing() before your equations. I have a module "equations" where I write my equations and solve them.

This is faster:

import sympy as sp
import equations
sp.init_printing()

Than this:

import sympy as sp
sp.init_printing()
import equations
like image 40
Martin Alexandersson Avatar answered Feb 11 '23 18:02

Martin Alexandersson