7

I have an expression in Mathematica; I want to convert this expression into python readable format. how to do this?

a=-4 b^16 Sin[(b^2 \[Gamma]^2)/Sqrt[\[Alpha]]]^2 (-4 b^2 Cos[b z1] Cos[b (L - z2)] Cos[
b (-z1 + z2)]^2)
Szabolcs
  • 234,956
  • 30
  • 623
  • 1,263
acoustics
  • 1,709
  • 9
  • 20
  • Please clarify what you mean by "Python readable format" when it comes to a symbolic expression. What do you want to do with it in Python? – Szabolcs Jun 25 '21 at 13:08
  • 1
    I want to read this equation in python and perform some operation on this – acoustics Jun 25 '21 at 13:18
  • Python has no built-in capability to manipulate equations. Only some Python libraries do, and each one is different. – Szabolcs Jun 25 '21 at 13:22
  • Oh the problem is if I use python I can access google colab for running my programs, I can make use of GPUs. That is the reason I am converting the expression – acoustics Jun 25 '21 at 13:30

2 Answers2

9

You can use from sympy.parsing.mathematica import mathematica from python.

Copy the mathematica expression as string to Python and do the following

>python
Python 3.8.8 (default, Apr 13 2021, 19:58:26)
[GCC 7.3.0] :: Anaconda, Inc. on linux
>>> from sympy.parsing.mathematica import mathematica
>>> from sympy import var
>>> b,Gamma,L,Alpha,z1,z2 = var('a Gamma L Alpha z1 z2')
>>> expr='16 b^18 Cos[b z1] Cos[b (L - z2)] Cos[b (-z1 + z2)]^2 Sin[(b^2 Gamma^2)/Sqrt[Alpha]]^2'
>>> my_expr_in_python  = mathematica(expr)
>>> my_expr_in_python

Gives

16*b**18*sin(Gamma**2*b**2/sqrt(Alpha))**2*cos(b*z1)*cos(b*(L - z2))*cos(b*(-z1 + z2))**2

Note that the parser in Python does not handle '\[Gamma]' and '\[Alpha]' as they are inside Mathematica. These have to be done using normal non-Greek text in Mathematica and avoid using the palettes symbols.

Every symbol needs to be defined in sympy using the var command. For example to convert Sin[x] Log[y] then do

>>> x,y = var('x y')
>>> expr='Sin[x] Log[y]'
>>> mathematica(expr)

log(y)*sin(x)

You can read more about Python's Mathematica parser and how to use it on https://docs.sympy.org/latest/modules/parsing.html

You can also add your own side translations of Mathematica expressions if you want, as shown in the example on the above page.

enter image description here

Nasser
  • 143,286
  • 11
  • 154
  • 359
3

Does this ad-hoc transformation work?

ClearAll[a, b, \[Alpha], \[Gamma]]

eq = a == -4 b^16 Sin[(b^2 [Gamma]^2)/Sqrt[[Alpha]]]^2 (-4 b^2 Cos[ b z1] Cos[b (L - z2)] Cos[b (-z1 + z2)]^2);

StringReplace[ ToString@CForm[eq], {"Power" -> "pow", "Sin" -> "sin", "Cos" -> "cos", "Sqrt" -> "sqrt", "[Alpha]" -> "alpha", "[Gamma]" -> "gamma"}]

(* "a == 16pow(b,18)cos(bz1)cos(b(L - z2))pow(cos(b*(-z1 \

  • z2)),2)pow(sin((pow(b,2)pow(gamma,2))/sqrt(alpha)),2)" *)

```

Anton Antonov
  • 37,787
  • 3
  • 100
  • 178