# Slow conversion of symbolic expression to sympy

I need to convert symbolic expressions to sympy for code generation using codegen. The symbolic expressions are very long and right now it could take hours to finish the sage to sympy conversion. Any idea to speed things up? Thanks.

edit retag close merge delete

Could you post an example of what you are trying? It is very hard to come up with advices without knowing what exactly you are doing.

( 2016-04-19 02:48:10 -0600 )edit

Here's a short example. It takes about 40 seconds to finish the conversion.

C=matrix(SR, 3, 3, var('C11, C12, C13, C21, C22, C23, C31, C32, C33'))

F=matrix(SR, 3, 3, var('F11, F12, F13, F21, F22, F23, F31, F32, F33'))

Cg=matrix(SR, 3, 3, var('Cg11, Cg12, Cg13, Cg21, Cg22, Cg23, Cg31, Cg32, Cg33'))

Fg=matrix(SR, 3, 3, var('Fg11, Fg12, Fg13, Fg21, Fg22, Fg23, Fg31, Fg32, Fg33'))

Fg_inv=Fg.inverse()

Ce=Fg_inv.T*C*Fg_inv

Fe=F*Fg_inv

Cedet=Ce.det()

Je=sqrt(Cedet)

W=(Je-1)^2

S_PK=Matrix(SR, 3,3, jacobian(W, C.list()).list())

S=Fe*S_PK*Fe.T*Je**(-1)

CF=F.T*F

out1=S[0,0].substitute([(C.list())[i]==(CF.list())[i] for i in xrange(9)])._sympy_()


enter code here

( 2016-04-20 00:07:37 -0600 )edit

Sort by » oldest newest most voted

As I understand, the slowness is not related to the conversion to Sympy. The point is that your expressions become huge, and that's why Sage becomes slow to perform operations (be it conversion or anything else). The solution is to simplify your expression while doing the computations. Below is an example of such simplifications you can add (the complete computation takes 1.27s on my laptop). Note that there may be better strategies (apply simplify_rational to more, or on the contrary less, expressions to optimize computation time). At least, I obtain reasonable computation times:

C = matrix(SR, 3, 3, var('C11, C12, C13, C21, C22, C23, C31, C32, C33'))
F = matrix(SR, 3, 3, var('F11, F12, F13, F21, F22, F23, F31, F32, F33'))
Cg = matrix(SR, 3, 3, var('Cg11, Cg12, Cg13, Cg21, Cg22, Cg23, Cg31, Cg32, Cg33'))
Fg = matrix(SR, 3, 3, var('Fg11, Fg12, Fg13, Fg21, Fg22, Fg23, Fg31, Fg32, Fg33'))

Fg_inv = Fg.inverse().simplify_rational()
Ce = (Fg_inv.T*C*Fg_inv).simplify_rational()
Fe = (F*Fg_inv).simplify_rational()

Cedet = Ce.det().simplify_rational()
Je = sqrt(Cedet)
W = ((Je-1)^2).expand().simplify_rational()

S_PK = matrix(SR, 3,3, jacobian(W, C.list()).list()).simplify_rational()
S = Fe*S_PK*Fe.T*Je**(-1)
CF = F.T*F

S00 = S[0,0].substitute([(C.list())[i]==(CF.list())[i] for i in xrange(9)])

out1 = S00._sympy_()

more

This works great. Thank you!

( 2016-04-28 01:54:42 -0600 )edit