Collect function along with its derivatives

58 views
Skip to first unread message

Jonathan Essen

unread,
Apr 25, 2017, 3:35:10 PM4/25/17
to sympy
I am attempting to use sympy to generate an implicit scheme for the heat equation. With the Crank-Nicolson time discretization I have equation 1 (attached).

Is there any way to isolate all occurrences of $\rho^{n+1}$ (along with its derivatves) to the lefthand side, as in equation 2 (attached).

I would be very interested to know! Apparently it has something to do with the collect function.

Best,
Jonathan
equation_1.png
equation_2.png

Chris Smith

unread,
May 4, 2017, 11:21:44 AM5/4/17
to sympy
Given Eq(L, R) where L and R are the left and right hand sides of the equation, try: `Eq(*list(reversed((L - R).expand().as_indepedent(foo, as_Add=True))))` where foo is the variable of interest to get the new equation.

Jonathan Essen

unread,
May 6, 2017, 4:24:24 PM5/6/17
to sympy
Thank you for the reply, but I noticed that the new right hand side is off by an overall minus sign! I fixed it using:

tmp = (ht * _lhs - ht * _rhs).expand().as_independent(rho1)
sp.Eq(tmp[1], rhs=-tmp[0])

Is there was a cleaner way to do this?

Chris Smith

unread,
May 8, 2017, 1:02:35 PM5/8/17
to sympy
Not that I can think of. Good catch on the minus sign. And use the `as_Add` flag unless you are positive that the expression you are working with is always an Add. Does this work:

sp.Eq(*[-1**i*a for i, a in enumerate(reversed((ht * _lhs - ht * _rhs).expand().as_independent(rho1, as_Add=True)))]

Chris Smith

unread,
May 8, 2017, 1:04:29 PM5/8/17
to sympy
with the closing paren!


sp.Eq(*[-1**i*a for i, a in enumerate(reversed((ht * _lhs - ht * _rhs).expand().as_independent(rho1, as_Add=True)))])

Chris Smith

unread,
May 8, 2017, 1:08:53 PM5/8/17
to sympy
and paren around -1; the canonical will make things look nicer in general, too:

sp.Eq(*[(-1)**i*a for i, a in enumerate(reversed((ht * _lhs - ht * _rhs).expand().as_independent(rho1, as_Add=True)))]).canonical
Reply all
Reply to author
Forward
0 new messages