Last active
February 8, 2018 17:50
-
-
Save Upabjojr/bc07c49262944f9c1eb0 to your computer and use it in GitHub Desktop.
A draft to transform some limited subset of Mathematica's FullForm expression into a SymPy expression.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import re | |
replacements = dict( | |
Times="Mul", | |
Plus="Add", | |
Power="Pow", | |
) | |
def parse_full_form(wmexpr): | |
out = [] | |
stack = [out] | |
generator = re.finditer(r'[\[\],]', wmexpr) | |
last_pos = 0 | |
for match in generator: | |
if match is None: | |
break | |
position = match.start() | |
last_expr = wmexpr[last_pos:position].replace(',', '').replace(']', '').replace('[', '').strip() | |
if match.group() == ',': | |
if last_expr != '': | |
stack[-1].append(last_expr) | |
elif match.group() == ']': | |
if last_expr != '': | |
stack[-1].append(last_expr) | |
stack.pop() | |
current_pos = stack[-1] | |
elif match.group() == '[': | |
stack[-1].append([last_expr]) | |
stack.append(stack[-1][-1]) | |
last_pos = match.end() | |
return out[0] | |
def generate_sympy_from_parsed(parsed, depth=0): | |
out = "" | |
if not isinstance(parsed, list): | |
return parsed | |
if parsed[0] == "If": | |
out += "\nif ("+generate_sympy_from_parsed(parsed[1])+"):\n" | |
out += shift4(generate_sympy_from_parsed(parsed[2])) | |
if len(parsed) > 2: | |
out += "\nelse:\n" | |
out += shift4(generate_sympy_from_parsed(parsed[3])) | |
else: | |
if parsed[0] in replacements: | |
out += replacements[parsed[0]] | |
else: | |
out += parsed[0] | |
if len(parsed) == 1: | |
return out | |
out += "(" | |
out += ", ".join([generate_sympy_from_parsed(i) for i in parsed[1:]]) | |
out += ")" | |
return out | |
def shift4(out): | |
return ' '*4 + re.sub(r'\n', '\n ', out) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
A Mathematica expression should be exposed to both __HoldForm__ and __FullForm__, that is | |
FullForm[HoldForm[ expression ]] | |
after this, copy the result into a Python string, let's say _expr_, then call: | |
list_tree = parse_full_form(expr) | |
generate_sympy_from_parsed(list_tree) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example: given the expression:
FullForm[HoldForm [ ... ]] will reduce it to
The variable
list_tree
will beand the (currently wrong) SymPy expression