Ask Your Question
0

Grouping Variables in SageMath

asked 2023-03-14 21:27:28 +0200

I have a multivariate polynomial of the form (type sage.rings.polynomial.multi_polynomial_libsingular.MPolynomial_libsingular)

a_1*x^2 + a_2*x*y + a_3*y^2 + a_4*x + a_5*y + a_6  + b_1*x^2 + b_2*x*y + b_3*y^2 + b_4*x + b_5*y + b_6

in the ring where all of the a_i, b_j, x, y are variables. Is there a way to group the variables x,y such that I can treat the equation as

(a_1+b_1)*x^2 + (a_2+b_2)*x*y + (a_3+b_3)*y^2 + (a_4+b_4)*x + (a_5+b_5)*y + (a_6+b_6)

in particular, I want to extract the coefficients of monomials in x,y say for example to get the coefficient of x^2 I want to get a_1+b_1.

Thanks in advance.

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
1

answered 2023-03-31 23:41:06 +0200

rburing gravatar image

Given

sage: R.<a_1,a_2,a_3,a_4,a_5,a_6,b_1,b_2,b_3,b_4,b_5,b_6,x,y> = PolynomialRing(QQ)
sage: f = a_1*x^2 + a_2*x*y + a_3*y^2 + a_4*x + a_5*y + a_6  + b_1*x^2 + b_2*x*y + b_3*y^2 + b_4*x + b_5*y + b_6

You can do:

sage: S = QQ['a_1,a_2,a_3,a_4,a_5,a_6,b_1,b_2,b_3,b_4,b_5,b_6']['x,y']; S
Multivariate Polynomial Ring in x, y over Multivariate Polynomial Ring in a_1, a_2, a_3, a_4, a_5, a_6, b_1, b_2, b_3, b_4, b_5, b_6 over Rational Field
sage: f_of_xy = S(f); f_of_xy
(a_1 + b_1)*x^2 + (a_2 + b_2)*x*y + (a_3 + b_3)*y^2 + (a_4 + b_4)*x + (a_5 + b_5)*y + a_6 + b_6
sage: f_of_xy.monomial_coefficient(S(x^2))
a_1 + b_1
sage: f_of_xy.monomials()
[x^2, x*y, y^2, x, y, 1]
sage: f_of_xy.coefficients()
[a_1 + b_1, a_2 + b_2, a_3 + b_3, a_4 + b_4, a_5 + b_5, a_6 + b_6]

Or without leaving the original ring, something like this:

coeffs = {}
for m, c in f.dict().items():
    m_xy = x^m[12]*y^m[13]
    m_rest = prod(b^e for (b, e) in zip(R.gens()[:-2], m[:-2]))
    if m_xy in coeffs:
        coeffs[m_xy] += c * m_rest
    else:
        coeffs[m_xy] = c * m_rest
coeffs

Result:

{x^2: a_1 + b_1,
 x*y: a_2 + b_2,
 y^2: a_3 + b_3,
 x: a_4 + b_4,
 y: a_5 + b_5,
 1: a_6 + b_6}
edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools

1 follower

Stats

Asked: 2023-03-14 21:26:10 +0200

Seen: 135 times

Last updated: Mar 31 '23