Targeting specific subexpression for transformations

34 views
Skip to first unread message

Francesco Bonazzi

unread,
Oct 24, 2014, 9:16:53 AM10/24/14
to sy...@googlegroups.com
Consider this use case

In [97]: expr = 1/(1-x) + 1/(1+x)

In [98]: e2 = Integral(expr, x)

In [99]: e2
Out[99]:
                   
 1       1    
⎜───── + ──────⎟ dx
x + 1   -x + 1  
                   


Suppose now I want to act on the expression inside the integral by applying together and expand on it, is there a simple way to do so?

In [102]: expr.together().expand()
Out[102]:
   
2    
────────
   
2    
- x  + 1


More accurately, is there an easy way to select a subexpression, apply some transformations only on that subexpression, and returning the entire expression with the applied transformations?

In this case one could extract the integral argument by e2.args[0], and then rebuild e2.func(new_arg_0, e2.args[1:]), but imagine if the tree expression is much more complicated and it is hard/uncomfortable to select the subexpression by accessing the args, what can one do?

Mateusz Paprocki

unread,
Oct 24, 2014, 10:50:16 AM10/24/14
to sympy
Hi,
You could use epath(), e.g.:

In [1]: expr = 1/(1-x) + 1/(1+x)

In [2]: e2 = Integral(expr, x)

In [3]: epath("/[0]", e2, lambda e: e.together().expand())
Out[3]:

⎮ 2
⎮ ──────── dx
⎮ 2
⎮ - x + 1


If you know XPath, then this approach should be familiar. See the
docstring for details. If unsure what expressions will be selected,
then skip the lambda part and epath() will return matching
expressions.

Mateusz

> --
> You received this message because you are subscribed to the Google Groups
> "sympy" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to sympy+un...@googlegroups.com.
> To post to this group, send email to sy...@googlegroups.com.
> Visit this group at http://groups.google.com/group/sympy.
> To view this discussion on the web visit
> https://groups.google.com/d/msgid/sympy/b59b0e08-884b-4d09-9065-d604f3509d5c%40googlegroups.com.
> For more options, visit https://groups.google.com/d/optout.

Francesco Bonazzi

unread,
Oct 27, 2014, 10:57:49 AM10/27/14
to sy...@googlegroups.com
Interesting, I didn't know of epath, it looks like it supports type-matching, which current wildcards do not support.

Chris Smith

unread,
Nov 3, 2014, 11:23:08 AM11/3/14
to sy...@googlegroups.com
see also the docstring of replace for instructions on how it might be used

>>> expr=1/(1-x)+1/(1+x)
>>> i=Integral(expr,x)
>>> i.replace(lambda arg: arg.is_Add, lambda arg: arg.together().expand())
Integral(2/(-x**2 + 1), x)
Reply all
Reply to author
Forward
0 new messages