SymPy, simplification / substitution using known patterns or sub-expressions
Asked Answered
L

2

7

I have the following expression:

from sympy import pi, sin, cos, var, simplify
var('j,u,v,w,vt,wt,a2,t,phi')

u0 = v*a2*sin(pi*j/2 + pi*j*t*phi**(-1)/2) + pi*vt*a2*cos(pi*j/2 + pi*j*t*phi**(-1)/2)*j*phi**(-1)/2 + pi*w*a2*cos(pi*j/2 + pi*j*t*phi**(-1)/2)*j*phi**(-1)

Which can be simplified:

print simplify(u0)
#a2*(pi*j*vt*cos(pi*j*(phi + t)/(2*phi)) + 2*pi*j*w*cos(pi*j*(phi + t)/(2*phi)) + 2*phi*v*sin(pi*j*(phi + t)/(2*phi)))/(2*phi)

Given the sub-expressions:

bj = pi*j*(phi + t)/(2*phi)
cj = j*pi/(2*phi)

Currently I substitute manually bj and cj in the simplified u0 expression to get:

u0 = a2*(v*sin(bj) + cj*vt*cos(bj) + 2*cj*w*cos(bj))

Is it possible to use SymPy to achieve that, avoiding the manual substitution?

Landeros answered 2/8, 2013 at 7:27 Comment(0)
K
11

I guess what you are missing is that subs will replace arbitrary expressions, not just symbols

>>> print simplify(u0).subs({pi*j*(phi + t)/(2*phi): bj, j*pi/(2*phi): cj})
a2*(pi*j*vt*cos(bj) + 2*pi*j*w*cos(bj) + 2*phi*v*sin(bj))/(2*phi)

(I used simplify because that is what results in the pi*j*(phi + t)/(2*phi) instead of pi*j/2 + pi*j*t/(2*phi), but it's not otherwise required)

Read http://docs.sympy.org/0.7.3/tutorial/basic_operations.html#substitution for more information about substitution and replacement. If you want to do more advanced replacement, take a look at the replace method.

Kerianne answered 2/8, 2013 at 19:23 Comment(0)
D
1

You can find common subexpressions with the cse routine.

Djebel answered 2/8, 2013 at 8:51 Comment(4)
is it possible to pass to cse the sub-expressions that it should look for?Landeros
The point of cse is to find the expressions for you. If you know the common subexpressions, why would you need to search for them? If on the other hand your question is about substituting expressions, just use subs or any of the other routines mentioned in subs docstring. Check out the sympy tutorial docs.sympy.org/0.7.3/tutorial/index.htmlDjebel
I have to search for them because sometimes they are not obviously visible, otherwise I could just replace in a text editor or similar. See for example cj, its sub-expression is inside u0 but not explicitly separated...Landeros
So just use cse. I don't understand does or doesn't do that you want different. Also, using a text editor to do symbolic manipulation sounds like a really bad idea...Kerianne

© 2022 - 2024 — McMap. All rights reserved.