pythonsympypoly

How to collect terms of given powers of multivariable polynomials using sympy?


I have a polynomial like this: 3*D*c1*cos_psi**2*p**2*u/(d*k**4*kappa**2) + 3*D*c1*cos_psi*p*q*u/(2*k**4*kappa**2) - 3*D*c1*cos_psi*p*q*u/(d*k**4*kappa**2) - 3*D*c1*u/(2*k**2*kappa**2) - 3*D*c1*p**2*u/(2*k**4*kappa**2) - 3*D*c1*q**2*u/(4*k**4*kappa**2) + 3*D*c1*p**2*u*(1 - cos_psi**2)/(d*k**4*kappa**2) + 3*D*c1*q**2*u/(2*d*k**4*kappa**2) - 6*D*c3*cos_psi**2*p**2*u/(d*k**4*kappa**2) - 6*D*c3*cos_psi*p*q*u/(k**4*kappa**2) + 6*D*c3*cos_psi*p*q*u/(d*k**4*kappa**2) + 6*D*c3*p**2*u/(k**4*kappa**2) + 3*D*c3*q**2*u/(k**4*kappa**2) - 6*D*c3*p**2*u*(1 - cos_psi**2)/(d*k**4*kappa**2) - 3*D*c3*q**2*u/(d*k**4*kappa**2)

I want to collect the terms like a multivariable polynomial of powers of q and p.

I found the Poly(expr,q,p) does exactly what I want. But the outcome is Poly((-3*D*c1*d*u + 6*D*c1*u + 12*D*c3*d*u - 12*D*c3*u)/(4*d*k**4*kappa**2)*q**2 + (3*D*c1*cos_psi*d*u - 6*D*c1*cos_psi*u - 12*D*c3*cos_psi*d*u + 12*D*c3*cos_psi*u)/(2*d*k**4*kappa**2)*q*p + (-3*D*c1*d*u + 6*D*c1*u + 12*D*c3*d*u - 12*D*c3*u)/(2*d*k**4*kappa**2)*p**2 - 3*D*c1*u/(2*k**2*kappa**2), q, p, domain='ZZ(u,c1,c3,d,k,D,cos_psi,kappa)'). I just want the final expression without the 'Poly(__,q,p,domain=....)'. I only want the ____ .


Solution

  • If Poly does what you want then you can get the expression part of a Poly as follows:

    >>> Poly(3*x+y*x+4+z,x).as_expr()
    x*(y + 3) + z + 4