pythonsympysymbolic-math

Find a common partial application of a pair of functions


Suppose we have two functions f(a,b,c) and g(a,b,d) that we can express as expressions in Sympy. How can we find the functions h(a,b), f'(x,c), g'(x,d) such that f'(h(a,b),c) = f(a,b,c) and g'(h(a,b),d)=g(a,b,d) via SymPy?

For example, I'd like to do the following using Sympy:

from sympy import symbols, Eq

a,b,c,d = symbols('a b c d')

eq1 = a-b+c
eq2 = sin(2a-2b)*d

# Function I'd like to implement
common_partial(eq1, eq2) # Returns h(a, b) = (a-b), f'(x, c) = x+c, g'(x, d) = sin(2x)*d

I'm not sure if there is a straightforward way to do it in SymPy. I'm also not aware of the name of this exact mathematical problem to look up for in research literature.


Solution

  • Turns out there is a SymPy function that does this, "Common Sub-expressions": https://docs.sympy.org/latest/modules/simplify/simplify.html#sympy.simplify.cse_main.cse

    from sympy import symbols, sin, cse
    a,b,c,d = symbols('a b c d')
    
    eq1 = a-b+c
    eq2 = sin(2*a-2*b)*d
    
    cse([eq1, eq2], optimizations='basic', ignore=[c, d])
    ([(x0, a - b)], [c + x0, d*sin(2*x0)])