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?

Saullo G. P. Castro
  • 56,802
  • 26
  • 179
  • 234

2 Answers2

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.

asmeurer
  • 86,894
  • 26
  • 169
  • 240
1

You can find common subexpressions with the cse routine.

Krastanov
  • 6,479
  • 3
  • 29
  • 42
  • is it possible to pass to `cse` the sub-expressions that it should look for? – Saullo G. P. Castro Aug 02 '13 at 10:18
  • 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 http://docs.sympy.org/0.7.3/tutorial/index.html – Krastanov Aug 02 '13 at 10:24
  • 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... – Saullo G. P. Castro Aug 02 '13 at 10:26
  • 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... – asmeurer Aug 02 '13 at 19:17