Abstract Representation of Expressions in SymPy

Consider these two equations:

x ^ y + xy

a ^ b + ab

I want to be able to recognize them as identical symbolic expressions. "Simplifying" won't work. "Subs" (substituting a for x, etc.) will not always work either because the order of the variables may change, etc.

So, is there a way to get an abstract representation for a SymPy expression that doesn't depend on the symbols used?

+3


source to share


2 answers


A representation that is not associated with the symbols used is a function. For example,

f1 = lambda x, y: (2*x+y)**2 

      

defines a function that is not bound to x and y, they do not exist except as placeholders inside that function. (This is a Python function, it is also possible to define a SymPy function object, but the difference is not significant here.)

If someone asked you if is (2*x+y)**2

"identical" for a**2 + 4*b*(a+b)

, what would you do? The only way I know is to simplify and try to match the variables in all possible permutations. This is what the following code does.



from sympy import *
from itertools import permutations
f1 = lambda x, y: (2*x+y)**2
f2 = lambda a, b: a**2 + 4*b*(a+b)
vars = symbols("v0:2")    # auxiliary variables to plug in f1 and f2
identical = any([simplify(f1(*vars) - f2(*p)) == 0 for p in permutations(vars)])

      

It now identical

evaluates to True, since the expressions are in the sense you described.

If you have expressions, not functions, to begin with, you can use instead subs

:

x, y, a, b = symbols("x y a b")
expr1 = (2*x+y)**2
expr2 = a**2 + 4*b*(a+b)
vars = symbols("v0:2")
identical = any([simplify(expr1.subs(zip((x, y), vars)) - expr2.subs(zip((a, b), p))) for p in permutations(vars)]) 

      

+4


source


Just clarify a little:



I was not happy with the substitution. So I kept digging and I noticed that SymPy generates a tree plot to represent symbolic expressions. A tree structure is an expression structure and does not depend on symbols. However, once you have matching graphs, you will need to decide if they are isomorphic (i.e. if both expressions are identical), which is .

0


source







All Articles