简体   繁体   中英

How to automate simplifying an expression by given sub-expressions in SymPy

I want to shorten a long equation with shorter expressions. Here is a simple example:

from sympy.abc import z, h, m, G
y = 0.2 * m  + 0.2 * z * m +z - h
y_1 = y.subs({m + z * m: G})
print(y_1)

Expected result is z - h + 0.2 * G but it doesn't replace the expression. I know the problem is 0.2 . Is there any way to fix this automatically?

OR another solution can be : Common subexpression elimination (cse(y)), which is not efficient as it works with default conditions to create sub-expressions.

Unfortunately, as far as I know, subs just isn't as powerful (yet?). You can try to automate splitting your substitution m + z * m: G into two separate substitutions z: G / m - 1 and m: G / (z + 1) and simplify in between.

from sympy.abc import z, h, m, G
y = 0.2 * m + z - h + 0.2 * z * m
y_1 = y.subs({m + z * m: G})
print(y_1)
y_2 = y.subs({z: G / m - 1, m: G / (z + 1)}).simplify()
print(y_2)
y_3 = y_2.subs({G / m - 1: z, G / (z + 1): m}).simplify()
print(y_3)

Which has the following output:

-h + 0.2*m*z + 0.2*m + z
0.2*G + G/m - h - 1
0.2*G - h + z

Update: When I said that you can try to automate the process, I meant something like the following code example. I do not know how much this is applicable to your situation.

from sympy import *
from sympy.abc import z, h, m, G

def elaborate_subs(expr, old, new):
    subs = {}
    for symbol in old.free_symbols:
        solution = solve(Eq(old, new), symbol, simplify=False)
        if solution:
            subs[symbol] = solution[0]
    expr = expr.subs(subs).simplify()
    expr = expr.subs({v: k for k, v in subs.items()}).simplify()
    return expr

y = 0.2 * m + z - h + 0.2 * z * m
print(elaborate_subs(y, m + z * m, G))

Which has the expected output:

0.2*G - h + z

I don't think the subs method works the way you think it does. It simply replaces a term with an input value that is passed. For example,

expr = cos(x)
expr.subs(x, 0)#here 0 is replaced with x
print(expr) # 1, sinces cos(0) is 1

#Or

expr = x**3 + 4*x*y - z
expr.subs([(x, 2), (y, 4), (z, 0)])
print(expr) #40

As you can see, in your subs method you are not telling exactly what should be replaced. Follow the examples above as a guideline and it should work. You can read more here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM