VDF
VDF

Reputation: 143

Converting Mathematica expression in python and evaluating it

I have imported in python a Mathematica expression successfully, but I am not able to use it to evaluate in the numbers I have in my python code. Here it follows an example:

from sympy.parsing.mathematica import mathematica
from sympy import var
import numpy as np

G=1
c=1
m1in=1
m2in=1
Rxin=1
Ryin=1
Rzin=1
Vxin=1
Vyin=1
Vzin=1
sx1in=1
sy1in=1
sz1in=1
sx2in=1
sy2in=1
sz2in=1

G,c,m1in,m2in,Rxin,Ryin,Rzin,Vxin,Vyin,Vzin,sx1in,sy1in,sz1in,sx2in,sy2in,sz2in = var('G c m1 m2 Rx Ry Rz Vx Vy Vz sx1 sy1in sz1 sx2 sy2 sz2')

term1 = mathematica('-1/(3 (m1 + m2) (Rx^2 + Ry^2 + Rz^2)^4)*16 G^2 m1 m2 (Rz (-((m2^2 sy1 + m1^2 sy2) Vx) + (m2^2 sx1 + m1^2 sx2) Vy) + Ry ((m2^2 sz1 + m1^2 sz2) Vx - (m2^2 sx1 + m1^2 sx2) Vz) + Rx (-((m2^2 sz1 + m1^2 sz2) Vy) + (m2^2 sy1 + m1^2 sy2) Vz)) (2 G (m1 + m2) Sqrt[Rx^2 + Ry^2 + Rz^2] - 30 Ry Rz Vy Vz - 30 Rx Vx (Ry Vy + Rz Vz) + Rz^2 (14 (Vx^2 + Vy^2) - Vz^2) + Ry^2 (14 Vx^2 - Vy^2 + 14 Vz^2) + Rx^2 (-Vx^2 + 14 (Vy^2 + Vz^2)))')

print(term1)

I would like to evaluate term1 in the values I have written at the beginning of the code in order to have a number as final output.

Upvotes: 0

Views: 483

Answers (1)

smichr
smichr

Reputation: 19135

I'm not sure if it is common for mathematica variables to list 'in' before the = but if it does, the following might be useful for converting that list to a replacement dictionary that you can use on your parsed expression:

>>> def mathin2reps(s):
...   from sympy.parsing.sympy_parser import parse_expr
...   return dict(parse_expr(i.replace('in=','='), None, T[1,9]).args
...       for i in s.splitlines())
...
>>> reps = mathin2reps('''G=1
... c=1
... m1in=1
... m2in=1
... Rxin=1
... Ryin=1
... Rzin=1
... Vxin=1
... Vyin=1
... Vzin=1
... sx1in=1
... sy1in=1
... sz1in=1
... sx2in=1
... sy2in=1
... sz2in=1''')
>>> term1.xreplace(reps)
0

Upvotes: 1

Related Questions