From bf7f14fb5b92b349e2c5baf2ba844159441c8fe6 Mon Sep 17 00:00:00 2001 From: Martin Rubey Date: Sat, 28 Sep 2024 21:08:42 +0200 Subject: [PATCH 1/9] provide monomial_coefficients for polynomials and allow single argument for MPolynomialRing_base.monomial --- src/sage/rings/polynomial/multi_polynomial_element.py | 2 ++ src/sage/rings/polynomial/multi_polynomial_ring_base.pyx | 7 +++++++ src/sage/rings/polynomial/polynomial_element.pyx | 2 ++ 3 files changed, 11 insertions(+) diff --git a/src/sage/rings/polynomial/multi_polynomial_element.py b/src/sage/rings/polynomial/multi_polynomial_element.py index 0e8d831b808..ab13879bf10 100644 --- a/src/sage/rings/polynomial/multi_polynomial_element.py +++ b/src/sage/rings/polynomial/multi_polynomial_element.py @@ -804,6 +804,8 @@ def dict(self): """ return self.element().dict() + monomial_coefficients = dict + def __iter__(self): """ Iterate over ``self`` respecting the term order. diff --git a/src/sage/rings/polynomial/multi_polynomial_ring_base.pyx b/src/sage/rings/polynomial/multi_polynomial_ring_base.pyx index 90e736dbadf..9814d5fe385 100644 --- a/src/sage/rings/polynomial/multi_polynomial_ring_base.pyx +++ b/src/sage/rings/polynomial/multi_polynomial_ring_base.pyx @@ -1371,7 +1371,14 @@ cdef class MPolynomialRing_base(CommutativeRing): sage: m = R.monomial(1,2,3) sage: R.monomial(*m.degrees()) == m True + + We also allow to specify the exponents in a single tuple:: + + sage: R.monomial(e) + x*y^2*z^3 """ + if len(exponents) == 1 and isinstance(exponents, tuple): + return self({exponents[0]: self.base_ring().one()}) return self({exponents: self.base_ring().one()}) def monomials_of_degree(self, degree): diff --git a/src/sage/rings/polynomial/polynomial_element.pyx b/src/sage/rings/polynomial/polynomial_element.pyx index 4f20542237f..076d585105f 100644 --- a/src/sage/rings/polynomial/polynomial_element.pyx +++ b/src/sage/rings/polynomial/polynomial_element.pyx @@ -4485,6 +4485,8 @@ cdef class Polynomial(CommutativePolynomial): X[i] = c return X + monomial_coefficients = dict + def factor(self, **kwargs): r""" Return the factorization of ``self`` over its base ring. From 3dfdfa6d58fee3e0b136e4a71ceed26f2779fdd7 Mon Sep 17 00:00:00 2001 From: Martin Rubey Date: Sun, 29 Sep 2024 11:35:14 +0200 Subject: [PATCH 2/9] fix thinko --- src/sage/rings/polynomial/multi_polynomial_ring_base.pyx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/sage/rings/polynomial/multi_polynomial_ring_base.pyx b/src/sage/rings/polynomial/multi_polynomial_ring_base.pyx index 9814d5fe385..8b7845479cf 100644 --- a/src/sage/rings/polynomial/multi_polynomial_ring_base.pyx +++ b/src/sage/rings/polynomial/multi_polynomial_ring_base.pyx @@ -1377,7 +1377,7 @@ cdef class MPolynomialRing_base(CommutativeRing): sage: R.monomial(e) x*y^2*z^3 """ - if len(exponents) == 1 and isinstance(exponents, tuple): + if len(exponents) == 1 and isinstance(exponents[0], tuple): return self({exponents[0]: self.base_ring().one()}) return self({exponents: self.base_ring().one()}) From 4729f848c6d637b62b533de2722826a388810f8d Mon Sep 17 00:00:00 2001 From: Martin Rubey Date: Mon, 30 Sep 2024 10:02:55 +0200 Subject: [PATCH 3/9] allow ETuples as well --- .../polynomial/multi_polynomial_ring_base.pyx | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-) diff --git a/src/sage/rings/polynomial/multi_polynomial_ring_base.pyx b/src/sage/rings/polynomial/multi_polynomial_ring_base.pyx index 8b7845479cf..fb04c537702 100644 --- a/src/sage/rings/polynomial/multi_polynomial_ring_base.pyx +++ b/src/sage/rings/polynomial/multi_polynomial_ring_base.pyx @@ -26,7 +26,7 @@ from sage.rings.polynomial import polynomial_ring from sage.rings.polynomial.term_order import TermOrder from sage.rings.polynomial.polynomial_ring_constructor import (PolynomialRing, polynomial_default_category) - +from sage.rings.polynomial.polydict import ETuple def is_MPolynomialRing(x): from sage.misc.superseded import deprecation_cython @@ -617,7 +617,6 @@ cdef class MPolynomialRing_base(CommutativeRing): a dict with respect to ``self.variable_names()``. """ # This is probably horribly inefficient - from sage.rings.polynomial.polydict import ETuple other_vars = list(x.parent().variable_names()) name_mapping = [(other_vars.index(var) if var in other_vars else -1) for var in self.variable_names()] K = self.base_ring() @@ -1376,9 +1375,17 @@ cdef class MPolynomialRing_base(CommutativeRing): sage: R.monomial(e) x*y^2*z^3 + + TESTS: + + Check that ETuples also work:: + + sage: from sage.rings.polynomial.polydict import ETuple + sage: R.monomial(ETuple(e)) + x*y^2*z^3 """ - if len(exponents) == 1 and isinstance(exponents[0], tuple): - return self({exponents[0]: self.base_ring().one()}) + if len(exponents) == 1 and isinstance((e := exponents[0]), (tuple, ETuple)): + return self({e: self.base_ring().one()}) return self({exponents: self.base_ring().one()}) def monomials_of_degree(self, degree): From 9a37e277089c8f2e09fdf475f0a7583e300c55f1 Mon Sep 17 00:00:00 2001 From: Martin Rubey Date: Mon, 30 Sep 2024 10:16:46 +0200 Subject: [PATCH 4/9] add line for linter --- src/sage/rings/polynomial/multi_polynomial_ring_base.pyx | 1 + 1 file changed, 1 insertion(+) diff --git a/src/sage/rings/polynomial/multi_polynomial_ring_base.pyx b/src/sage/rings/polynomial/multi_polynomial_ring_base.pyx index fb04c537702..19a74c9d540 100644 --- a/src/sage/rings/polynomial/multi_polynomial_ring_base.pyx +++ b/src/sage/rings/polynomial/multi_polynomial_ring_base.pyx @@ -28,6 +28,7 @@ from sage.rings.polynomial.polynomial_ring_constructor import (PolynomialRing, polynomial_default_category) from sage.rings.polynomial.polydict import ETuple + def is_MPolynomialRing(x): from sage.misc.superseded import deprecation_cython deprecation_cython(38266, From 1a94d8fb21a8274ec02cbf3cf605dfed54a400d7 Mon Sep 17 00:00:00 2001 From: Martin Rubey Date: Mon, 30 Sep 2024 12:11:37 +0200 Subject: [PATCH 5/9] use cimport --- src/sage/rings/polynomial/multi_polynomial_ring_base.pyx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/sage/rings/polynomial/multi_polynomial_ring_base.pyx b/src/sage/rings/polynomial/multi_polynomial_ring_base.pyx index 19a74c9d540..fa9947b028e 100644 --- a/src/sage/rings/polynomial/multi_polynomial_ring_base.pyx +++ b/src/sage/rings/polynomial/multi_polynomial_ring_base.pyx @@ -26,7 +26,7 @@ from sage.rings.polynomial import polynomial_ring from sage.rings.polynomial.term_order import TermOrder from sage.rings.polynomial.polynomial_ring_constructor import (PolynomialRing, polynomial_default_category) -from sage.rings.polynomial.polydict import ETuple +from sage.rings.polynomial.polydict cimport ETuple def is_MPolynomialRing(x): From 45175252cd3b864266a2bdc2663977f5efe52d6b Mon Sep 17 00:00:00 2001 From: Martin Rubey Date: Tue, 1 Oct 2024 09:44:20 +0200 Subject: [PATCH 6/9] provide monomial_coefficients for all kinds of polynomials --- src/sage/rings/polynomial/laurent_polynomial.pyx | 5 +++++ .../rings/polynomial/laurent_polynomial_mpair.pyx | 5 +++++ src/sage/rings/polynomial/multi_polynomial_element.py | 11 +++++++++++ .../rings/polynomial/multi_polynomial_libsingular.pyx | 7 ++++++- src/sage/rings/polynomial/ore_polynomial_element.pyx | 5 +++++ src/sage/rings/polynomial/plural.pyx | 3 +++ src/sage/rings/polynomial/polynomial_element.pyx | 3 +++ .../rings/polynomial/polynomial_element_generic.py | 5 +++++ 8 files changed, 43 insertions(+), 1 deletion(-) diff --git a/src/sage/rings/polynomial/laurent_polynomial.pyx b/src/sage/rings/polynomial/laurent_polynomial.pyx index 70cec491cae..8b1033f4fd5 100644 --- a/src/sage/rings/polynomial/laurent_polynomial.pyx +++ b/src/sage/rings/polynomial/laurent_polynomial.pyx @@ -850,10 +850,15 @@ cdef class LaurentPolynomial_univariate(LaurentPolynomial): y^3*t^-9 + 3*x^3*y^2*t^-6 + 3*x^6*y*t^-3 + x^9 + t^2 sage: f.dict() {-9: y^3, -6: 3*x^3*y^2, -3: 3*x^6*y, 0: x^9, 2: 1} + + sage: f.monomial_coefficients() + {-9: y^3, -6: 3*x^3*y^2, -3: 3*x^6*y, 0: x^9, 2: 1} """ cdef dict d = self.__u.dict() return {k+self.__n: d[k] for k in d} + monomial_coefficients = dict + def coefficients(self): """ Return the nonzero coefficients of ``self``. diff --git a/src/sage/rings/polynomial/laurent_polynomial_mpair.pyx b/src/sage/rings/polynomial/laurent_polynomial_mpair.pyx index e6ea53e1756..4b14f79cdca 100644 --- a/src/sage/rings/polynomial/laurent_polynomial_mpair.pyx +++ b/src/sage/rings/polynomial/laurent_polynomial_mpair.pyx @@ -804,11 +804,16 @@ cdef class LaurentPolynomial_mpair(LaurentPolynomial): sage: f = 4*x^7*z^-1 + 3*x^3*y + 2*x^4*z^-2 + x^6*y^-7 sage: sorted(f.dict().items()) [((3, 1, 0), 3), ((4, 0, -2), 2), ((6, -7, 0), 1), ((7, 0, -1), 4)] + + sage: sorted(f.monomial_coefficients().items()) + [((3, 1, 0), 3), ((4, 0, -2), 2), ((6, -7, 0), 1), ((7, 0, -1), 4)] """ if self._prod is None: self._compute_polydict() return < dict > self._prod.dict() + monomial_coefficients = dict + def _fraction_pair(self): """ Return one representation of ``self`` as a pair diff --git a/src/sage/rings/polynomial/multi_polynomial_element.py b/src/sage/rings/polynomial/multi_polynomial_element.py index 65ba655b114..e856fd9e46e 100644 --- a/src/sage/rings/polynomial/multi_polynomial_element.py +++ b/src/sage/rings/polynomial/multi_polynomial_element.py @@ -806,6 +806,17 @@ def dict(self): """ Return underlying dictionary with keys the exponents and values the coefficients of this polynomial. + + EXAMPLES:: + + sage: # needs sage.rings.number_field + sage: R. = PolynomialRing(QQbar, order='lex') + sage: f = (x^1*y^5*z^2 + x^2*z + x^4*y^1*z^3) + sage: f.dict() + {(1, 5, 2): 1, (2, 0, 1): 1, (4, 1, 3): 1} + + sage: f.monomial_coefficients() # needs sage.rings.number_field + {(1, 5, 2): 1, (2, 0, 1): 1, (4, 1, 3): 1} """ return self.element().dict() diff --git a/src/sage/rings/polynomial/multi_polynomial_libsingular.pyx b/src/sage/rings/polynomial/multi_polynomial_libsingular.pyx index d177889bd6e..307735c46ba 100644 --- a/src/sage/rings/polynomial/multi_polynomial_libsingular.pyx +++ b/src/sage/rings/polynomial/multi_polynomial_libsingular.pyx @@ -2992,9 +2992,12 @@ cdef class MPolynomial_libsingular(MPolynomial_libsingular_base): EXAMPLES:: sage: R. = QQ[] - sage: f=2*x*y^3*z^2 + 1/7*x^2 + 2/3 + sage: f = 2*x*y^3*z^2 + 1/7*x^2 + 2/3 sage: f.dict() {(0, 0, 0): 2/3, (1, 3, 2): 2, (2, 0, 0): 1/7} + + sage: f.monomial_coefficients() + {(0, 0, 0): 2/3, (1, 3, 2): 2, (2, 0, 0): 1/7} """ cdef poly *p cdef ring *r = self._parent_ring @@ -3016,6 +3019,8 @@ cdef class MPolynomial_libsingular(MPolynomial_libsingular_base): p = pNext(p) return pd + monomial_coefficients = dict + def iterator_exp_coeff(self, as_ETuples=True): """ Iterate over ``self`` as pairs of ((E)Tuple, coefficient). diff --git a/src/sage/rings/polynomial/ore_polynomial_element.pyx b/src/sage/rings/polynomial/ore_polynomial_element.pyx index 8307bf9694a..1acc82dd583 100644 --- a/src/sage/rings/polynomial/ore_polynomial_element.pyx +++ b/src/sage/rings/polynomial/ore_polynomial_element.pyx @@ -2493,6 +2493,9 @@ cdef class OrePolynomial_generic_dense(OrePolynomial): sage: a = x^2012 + t*x^1006 + t^3 + 2*t sage: a.dict() {0: t^3 + 2*t, 1006: t, 2012: 1} + + sage: a.monomial_coefficients() + {0: t^3 + 2*t, 1006: t, 2012: 1} """ cdef dict X = {} cdef list Y = (self)._coeffs @@ -2503,6 +2506,8 @@ cdef class OrePolynomial_generic_dense(OrePolynomial): X[i] = c return X + monomial_coefficients = dict + cpdef Integer degree(self): r""" Return the degree of ``self``. diff --git a/src/sage/rings/polynomial/plural.pyx b/src/sage/rings/polynomial/plural.pyx index eb6b091c683..8fb9592e0b7 100644 --- a/src/sage/rings/polynomial/plural.pyx +++ b/src/sage/rings/polynomial/plural.pyx @@ -2203,6 +2203,9 @@ cdef class NCPolynomial_plural(RingElement): sage: f = (2*x*y^3*z^2 + (7)*x^2 + (3)) sage: f.dict() {(0, 0, 0): 3, (1, 2, 3): 2, (2, 0, 0): 7} + + sage: f.monomial_coefficients() + {(0, 0, 0): 3, (1, 2, 3): 2, (2, 0, 0): 7} """ cdef poly *p cdef ring *r diff --git a/src/sage/rings/polynomial/polynomial_element.pyx b/src/sage/rings/polynomial/polynomial_element.pyx index 3ce764d6f01..dbb7a6f0565 100644 --- a/src/sage/rings/polynomial/polynomial_element.pyx +++ b/src/sage/rings/polynomial/polynomial_element.pyx @@ -4475,6 +4475,9 @@ cdef class Polynomial(CommutativePolynomial): sage: f = x^3 + -1/7*x + 13 sage: f.dict() {0: 13, 1: -1/7, 3: 1} + + sage: f.monomial_coefficients() + {0: 13, 1: -1/7, 3: 1} """ cdef dict X = {} cdef list Y = self.list(copy=False) diff --git a/src/sage/rings/polynomial/polynomial_element_generic.py b/src/sage/rings/polynomial/polynomial_element_generic.py index 3e8a6b45ee1..abfe216aae8 100644 --- a/src/sage/rings/polynomial/polynomial_element_generic.py +++ b/src/sage/rings/polynomial/polynomial_element_generic.py @@ -143,9 +143,14 @@ def dict(self): sage: d[0] = 10 sage: f.dict() {0: 5, 1997: 1, 10000: 7} + + sage: f.monomial_coefficients() + {0: 5, 1997: 1, 10000: 7} """ return dict(self.__coeffs) + monomial_coefficients = dict + def coefficients(self, sparse=True): """ Return the coefficients of the monomials appearing in ``self``. From 92c4646457930aaac78b571e8cd1bade33924c8c Mon Sep 17 00:00:00 2001 From: Martin Rubey Date: Thu, 3 Oct 2024 21:00:52 +0200 Subject: [PATCH 7/9] make dict an alias of monomial_coefficients, thoroughly --- src/sage/algebras/cluster_algebra.py | 7 +- src/sage/algebras/commutative_dga.py | 41 +++++---- src/sage/algebras/free_algebra.py | 2 +- .../fast_parallel_fmats_methods.pyx | 4 +- .../algebras/fusion_rings/poly_tup_engine.pyx | 2 +- .../hecke_algebras/cubic_hecke_base_ring.py | 2 +- src/sage/algebras/iwahori_hecke_algebra.py | 2 +- .../free_algebra_element_letterplace.pyx | 2 +- src/sage/algebras/quantum_clifford.py | 4 +- .../algebras/rational_cherednik_algebra.py | 8 +- src/sage/algebras/splitting_algebra.py | 15 +++- src/sage/algebras/weyl_algebra.py | 2 +- src/sage/combinat/ncsf_qsym/qsym.py | 2 +- .../root_lattice_realization_algebras.py | 2 +- src/sage/combinat/sf/monomial.py | 23 +++-- src/sage/combinat/sf/sfa.py | 2 +- src/sage/combinat/triangles_FHM.py | 4 +- src/sage/databases/cubic_hecke_db.py | 4 +- .../polyhedron/generating_function.py | 6 +- src/sage/groups/braid.py | 2 +- src/sage/libs/singular/singular.pyx | 8 +- src/sage/rings/morphism.pyx | 2 +- .../rings/multi_power_series_ring_element.py | 20 +++-- src/sage/rings/polynomial/flatten.py | 10 +-- .../rings/polynomial/laurent_polynomial.pxd | 2 +- .../rings/polynomial/laurent_polynomial.pyx | 23 +++-- .../polynomial/laurent_polynomial_mpair.pyx | 33 +++---- .../polynomial/laurent_polynomial_ring.py | 15 ++-- .../rings/polynomial/multi_polynomial.pyx | 38 ++++---- .../polynomial/multi_polynomial_element.py | 24 +++--- .../multi_polynomial_libsingular.pyx | 29 ++++--- .../rings/polynomial/multi_polynomial_ring.py | 86 +++++++++++-------- .../polynomial/multi_polynomial_ring_base.pyx | 8 +- src/sage/rings/polynomial/omega.py | 9 +- .../polynomial/ore_polynomial_element.pxd | 3 +- .../polynomial/ore_polynomial_element.pyx | 5 +- .../polynomial_padic_capped_relative_dense.py | 2 +- .../rings/polynomial/polynomial_element.pyx | 22 ++--- .../polynomial/polynomial_element_generic.py | 28 +++--- .../polynomial_ring_homomorphism.pyx | 5 +- src/sage/rings/power_series_mpoly.pyx | 4 +- src/sage/rings/power_series_pari.pyx | 12 ++- src/sage/rings/power_series_poly.pyx | 12 ++- src/sage/rings/power_series_ring_element.pyx | 2 +- src/sage/rings/qqbar.py | 4 +- .../rings/semirings/tropical_mpolynomial.py | 11 ++- .../rings/semirings/tropical_polynomial.py | 12 +-- src/sage/rings/semirings/tropical_variety.py | 2 +- src/sage/rings/tate_algebra_element.pyx | 12 ++- src/sage/schemes/curves/projective_curve.py | 6 +- .../con_rational_function_field.py | 18 ++-- .../riemann_surfaces/riemann_surface.py | 4 +- src/sage/schemes/toric/ideal.py | 2 +- .../schemes/toric/weierstrass_covering.py | 6 +- src/sage/structure/parent.pyx | 2 +- src/sage/symbolic/expression.pyx | 2 +- 56 files changed, 358 insertions(+), 261 deletions(-) diff --git a/src/sage/algebras/cluster_algebra.py b/src/sage/algebras/cluster_algebra.py index a101064eb0e..6772673cbcb 100644 --- a/src/sage/algebras/cluster_algebra.py +++ b/src/sage/algebras/cluster_algebra.py @@ -462,7 +462,7 @@ def d_vector(self) -> tuple: sage: x.d_vector() (1, 1, 2, -2) """ - monomials = self.lift().dict() + monomials = self.lift().monomial_coefficients() minimal = map(min, zip(*monomials)) return tuple(-vector(minimal))[:self.parent().rank()] @@ -615,8 +615,9 @@ def theta_basis_decomposition(self): f_poly = components[g_vect].F_polynomial() g_vect = vector(g_vect) while f_poly != zero_U: - y_exp = min(f_poly.dict()) - coeff = f_poly.dict()[y_exp] + coeffs = f_poly.monomial_coefficients() + y_exp = min(coeffs) + coeff = coeffs[y_exp] g_theta = tuple(g_vect + B * vector(y_exp)) out[g_theta] = out.get(g_theta, zero_A) + A({zero_t + tuple(y_exp): coeff}) f_poly -= U({y_exp: coeff}) * A.theta_basis_F_polynomial(g_theta) diff --git a/src/sage/algebras/commutative_dga.py b/src/sage/algebras/commutative_dga.py index d71f93a2600..fdcaeedaad8 100644 --- a/src/sage/algebras/commutative_dga.py +++ b/src/sage/algebras/commutative_dga.py @@ -222,7 +222,7 @@ def image_monomial(exponent): return A.zero() for g in I.gens(): - d = g.dict() + d = g.monomial_coefficients() res = A.sum(d[ex] * image_monomial(ex) for ex in d) if not res.is_zero(): raise ValueError("the differential does not preserve the ideal") @@ -303,7 +303,7 @@ def _call_(self, x): if x.is_zero(): return self.codomain().zero() res = self.codomain().zero() - dic = x.dict() + dic = x.monomial_coefficients() for key in dic: keyl = list(key) coef = dic[key] @@ -392,11 +392,11 @@ def differential_matrix(self, n): A = self.domain() dom = A.basis(n) cod = A.basis(n + 1) - cokeys = [next(iter(a.lift().dict().keys())) for a in cod] + cokeys = [next(iter(a.lift().monomial_coefficients().keys())) for a in cod] m = matrix(A.base_ring(), len(dom), len(cod)) for i, domi in enumerate(dom): im = self(domi) - dic = im.lift().dict() + dic = im.lift().monomial_coefficients() for j in dic.keys(): k = cokeys.index(j) m[i, k] = dic[j] @@ -670,11 +670,11 @@ def differential_matrix_multigraded(self, n, total=False): n = G(vector(n)) dom = A.basis(n) cod = A.basis(n + self._degree_of_differential) - cokeys = [next(iter(a.lift().dict().keys())) for a in cod] + cokeys = [next(iter(a.lift().monomial_coefficients().keys())) for a in cod] m = matrix(self.base_ring(), len(dom), len(cod)) for i, domi in enumerate(dom): im = self(domi) - dic = im.lift().dict() + dic = im.lift().monomial_coefficients() for j in dic.keys(): k = cokeys.index(j) m[i, k] = dic[j] @@ -1182,7 +1182,7 @@ def basis(self, n): basis = [] for v in free_basis: el = prod([self.gen(i)**v[i] for i in range(len(v))]) - di = el.dict() + di = el.monomial_coefficients() if len(di) == 1: k, = di.keys() if tuple(k) == v: @@ -1477,7 +1477,7 @@ def degree(self, total=False): """ if self.is_zero(): raise ValueError("the zero element does not have a well-defined degree") - exps = self.lift().dict().keys() + exps = self.monomial_coefficients().keys() degrees = self.parent()._degrees n = self.parent().ngens() l = [sum(e[i] * degrees[i] for i in range(n)) for e in exps] @@ -1548,7 +1548,7 @@ def homogeneous_parts(self): sage: a.homogeneous_parts() {1: -2*e3 + e5, 2: e1*e2, 3: e1*e3*e5 - 3*e2*e3*e5} """ - dic = self.dict() + dic = self.monomial_coefficients() terms = [self.parent()({t: dic[t]}) for t in dic.keys()] res = {} for term in terms: @@ -1559,7 +1559,7 @@ def homogeneous_parts(self): res[deg] = term return {i: res[i] for i in sorted(res.keys())} - def dict(self): + def monomial_coefficients(self): r""" A dictionary that determines the element. @@ -1569,11 +1569,18 @@ def dict(self): EXAMPLES:: sage: A. = GradedCommutativeAlgebra(QQ, degrees=(1, 2, 2, 3)) - sage: dic = (x*y - 5*y*z + 7*x*y^2*z^3*t).dict() - sage: sorted(dic.items()) + sage: elt = x*y - 5*y*z + 7*x*y^2*z^3*t + sage: sorted(elt.monomial_coefficients().items()) + [((0, 1, 1, 0), -5), ((1, 1, 0, 0), 1), ((1, 2, 3, 1), 7)] + + ``dict`` is an alias:: + + sage: sorted(elt.dict().items()) [((0, 1, 1, 0), -5), ((1, 1, 0, 0), 1), ((1, 2, 3, 1), 7)] """ - return self.lift().dict() + return self.lift().monomial_coefficients() + + dict = monomial_coefficients def __call__(self, *values, **kwargs): r""" @@ -1645,8 +1652,8 @@ def __call__(self, *values, **kwargs): if gstr in kwargs: images[i] = kwargs[gstr] res = 0 - for (m, c) in self.dict().items(): - term = prod((gen**y for (y, gen) in zip(m, images)), c) + for m, c in self.monomial_coefficients().items(): + term = prod((gen ** y for y, gen in zip(m, images)), c) res += term return res @@ -2000,7 +2007,7 @@ def degree(self, total=False): raise ValueError("the zero element does not have a well-defined degree") degrees = self.parent()._degrees_multi n = self.parent().ngens() - exps = self.lift().dict().keys() + exps = self.monomial_coefficients().keys() l = [sum(exp[i] * degrees[i] for i in range(n)) for exp in exps] if len(set(l)) == 1: return l[0] @@ -3861,7 +3868,7 @@ def _call_(self, x): """ codomain = self.codomain() result = codomain.zero() - for mono, coeff in x.dict().items(): + for mono, coeff in x.monomial_coefficients().items(): term = prod([gen**y for (y, gen) in zip(mono, self.im_gens())], codomain.one()) result += coeff * term diff --git a/src/sage/algebras/free_algebra.py b/src/sage/algebras/free_algebra.py index 6080b82a396..8b73482e7bf 100644 --- a/src/sage/algebras/free_algebra.py +++ b/src/sage/algebras/free_algebra.py @@ -651,7 +651,7 @@ def exp_to_monomial(T): return M([(i % ngens, Ti) for i, Ti in enumerate(T) if Ti]) return self.element_class(self, {exp_to_monomial(T): c - for T, c in x.letterplace_polynomial().dict().items()}) + for T, c in x.letterplace_polynomial().monomial_coefficients().items()}) # ok, not a free algebra element (or should not be viewed as one). if isinstance(x, str): from sage.misc.sage_eval import sage_eval diff --git a/src/sage/algebras/fusion_rings/fast_parallel_fmats_methods.pyx b/src/sage/algebras/fusion_rings/fast_parallel_fmats_methods.pyx index 2e04549ec7f..ba2a626c9f0 100644 --- a/src/sage/algebras/fusion_rings/fast_parallel_fmats_methods.pyx +++ b/src/sage/algebras/fusion_rings/fast_parallel_fmats_methods.pyx @@ -273,7 +273,7 @@ cdef get_reduced_hexagons(factory, tuple mp_params): if i % n_proc == child_id: he = req_cy(basis, r_matrix, fvars, _Nk_ij, id_anyon, sextuple) if he: - red = reduce_poly_dict(he.dict(), _nnz, _ks, one) + red = reduce_poly_dict(he.monomial_coefficients(), _nnz, _ks, one) # Avoid pickling cyclotomic coefficients red = _flatten_coeffs(red) @@ -341,7 +341,7 @@ cdef get_reduced_pentagons(factory, tuple mp_params): if i % n_proc == child_id: pe = feq_cy(basis, fvars, _Nk_ij, id_anyon, zero, nonuple, prune=True) if pe: - red = reduce_poly_dict(pe.dict(), _nnz, _ks, one) + red = reduce_poly_dict(pe.monomial_coefficients(), _nnz, _ks, one) # Avoid pickling cyclotomic coefficients red = _flatten_coeffs(red) diff --git a/src/sage/algebras/fusion_rings/poly_tup_engine.pyx b/src/sage/algebras/fusion_rings/poly_tup_engine.pyx index 6c0b8d2ac27..8d6869bd484 100644 --- a/src/sage/algebras/fusion_rings/poly_tup_engine.pyx +++ b/src/sage/algebras/fusion_rings/poly_tup_engine.pyx @@ -26,7 +26,7 @@ cpdef inline tuple poly_to_tup(MPolynomial_libsingular poly): sage: poly_to_tup(x**2*y**4 - 4/5*x*y**2 + 1/3 * y) (((2, 4), 1), ((1, 2), -4/5), ((0, 1), 1/3)) """ - return tuple(poly.dict().items()) + return tuple(poly.monomial_coefficients().items()) cpdef inline MPolynomial_libsingular _tup_to_poly(tuple eq_tup, MPolynomialRing_libsingular parent): r""" diff --git a/src/sage/algebras/hecke_algebras/cubic_hecke_base_ring.py b/src/sage/algebras/hecke_algebras/cubic_hecke_base_ring.py index 3521e9bd478..b980e2fa80c 100644 --- a/src/sage/algebras/hecke_algebras/cubic_hecke_base_ring.py +++ b/src/sage/algebras/hecke_algebras/cubic_hecke_base_ring.py @@ -148,7 +148,7 @@ def _act_(self, perm, pol): if not self.is_left(): perm, pol = pol, perm pol_dict = {} - for key, value in pol.dict().items(): + for key, value in pol.monomial_coefficients().items(): newkey = [0] * len(key) for pos, k in enumerate(key): newkey[perm(pos + 1) - 1] = k diff --git a/src/sage/algebras/iwahori_hecke_algebra.py b/src/sage/algebras/iwahori_hecke_algebra.py index 48796fbd605..01390f1a5a4 100644 --- a/src/sage/algebras/iwahori_hecke_algebra.py +++ b/src/sage/algebras/iwahori_hecke_algebra.py @@ -83,7 +83,7 @@ def normalized_laurent_polynomial(R, p): u + v^-1 + u^-1 """ try: - return R({k: R._base(c) for k, c in p.dict().items()}) + return R({k: R._base(c) for k, c in p.monomial_coefficients().items()}) except (AttributeError, TypeError): return R(p) diff --git a/src/sage/algebras/letterplace/free_algebra_element_letterplace.pyx b/src/sage/algebras/letterplace/free_algebra_element_letterplace.pyx index 5b99c87dd17..8eae3602f9d 100644 --- a/src/sage/algebras/letterplace/free_algebra_element_letterplace.pyx +++ b/src/sage/algebras/letterplace/free_algebra_element_letterplace.pyx @@ -139,7 +139,7 @@ cdef class FreeAlgebraElement_letterplace(AlgebraElement): sage: sorted(p) # indirect doctest [((0, 0, 0, 1, 0, 0, 0, 1), 2), ((0, 1, 0, 0, 0, 0, 1, 0), 1)] """ - cdef dict d = self._poly.dict() + cdef dict d = self._poly.monomial_coefficients() yield from d.iteritems() def _repr_(self): diff --git a/src/sage/algebras/quantum_clifford.py b/src/sage/algebras/quantum_clifford.py index ff888ba5aaa..99c0c1e226f 100644 --- a/src/sage/algebras/quantum_clifford.py +++ b/src/sage/algebras/quantum_clifford.py @@ -533,7 +533,7 @@ def product_on_basis(self, m1, m2): poly *= self._w_poly.monomial(*v) poly = poly.reduce([vp[i]**(4*k) - (1 + q**(-2*k)) * vp[i]**(2*k) + q**(-2*k) for i in range(self._n)]) - pdict = poly.dict() + pdict = poly.monomial_coefficients() ret = {(self._psi(p), tuple(e)): pdict[e] * q**q_power * sign for e in pdict} @@ -610,7 +610,7 @@ def inverse(self): for wi in wp}) poly = poly.reduce([wi**(4*k) - (1 + q**(-2*k)) * wi**(2*k) + q**(-2*k) for wi in wp]) - pdict = poly.dict() + pdict = poly.monomial_coefficients() coeff = coeff.inverse_of_unit() ret = {(p, tuple(e)): coeff * c for e, c in pdict.items()} return Cl.element_class(Cl, ret) diff --git a/src/sage/algebras/rational_cherednik_algebra.py b/src/sage/algebras/rational_cherednik_algebra.py index c3ff9ff25e6..1ded26a1112 100644 --- a/src/sage/algebras/rational_cherednik_algebra.py +++ b/src/sage/algebras/rational_cherednik_algebra.py @@ -328,11 +328,11 @@ def product_on_basis(self, left, right): def commute_w_hd(w, al): # al is given as a dictionary ret = P.one() for k in al: - x = sum(c * gens_dict[i] for i,c in alpha[k].weyl_action(w)) + x = sum(c * gens_dict[i] for i, c in alpha[k].weyl_action(w)) ret *= x**al[k] - ret = ret.dict() + ret = ret.monomial_coefficients() for k in ret: - yield (self._hd({I[i]: e for i,e in enumerate(k) if e != 0}), ret[k]) + yield (self._hd({I[i]: e for i, e in enumerate(k) if e != 0}), ret[k]) # Do Lac Ra if they are both non-trivial if dl and dr: @@ -374,7 +374,7 @@ def commute_w_hd(w, al): # al is given as a dictionary for i,c in alphacheck[k].weyl_action(right[1].reduced_word(), inverse=True)) ret *= x**dl[k] - ret = ret.dict() + ret = ret.monomial_coefficients() w = left[1]*right[1] return self._from_dict({(left[0], w, self._h({I[i]: e for i,e in enumerate(k) diff --git a/src/sage/algebras/splitting_algebra.py b/src/sage/algebras/splitting_algebra.py index cfcb86e5c28..43d72ed7470 100644 --- a/src/sage/algebras/splitting_algebra.py +++ b/src/sage/algebras/splitting_algebra.py @@ -102,7 +102,7 @@ def is_unit(self): return super().is_unit() - def dict(self): + def monomial_coefficients(self): r""" Return the dictionary of ``self`` according to its lift to the cover. @@ -110,11 +110,18 @@ def dict(self): sage: from sage.algebras.splitting_algebra import SplittingAlgebra sage: CR3. = SplittingAlgebra(cyclotomic_polynomial(3)) - sage: (e3 + 42).dict() + sage: f = e3 + 42 + sage: f.monomial_coefficients() + {0: 42, 1: 1} + + ``dict`` is an alias:: + + sage: f.dict() {0: 42, 1: 1} """ - return self.lift().dict() + return self.lift().monomial_coefficients() + dict = monomial_coefficients # ------------------------------------------------------------------------------------------------------------------ # Parent class of the splitting algebra @@ -282,7 +289,7 @@ def __init__(self, monic_polynomial, names='X', iterate=True, warning=True): root_names_reduces.remove(root_name) P = base_ring_step[root_names_reduces[0]] - p = P(monic_polynomial.dict()) + p = P(monic_polynomial.monomial_coefficients()) q, _ = p.quo_rem(P.gen() - first_root) verbose("Invoking recursion with: %s" % (q,)) diff --git a/src/sage/algebras/weyl_algebra.py b/src/sage/algebras/weyl_algebra.py index ac554795cfd..8eae4797c7d 100644 --- a/src/sage/algebras/weyl_algebra.py +++ b/src/sage/algebras/weyl_algebra.py @@ -786,7 +786,7 @@ def _element_constructor_(self, x): return self.element_class(self, {i: R(c) for i, c in x if R(c) != zero}) x = self._poly_ring(x) return self.element_class(self, {(tuple(m), t): c - for m, c in x.dict().items()}) + for m, c in x.monomial_coefficients().items()}) def _coerce_map_from_(self, R): """ diff --git a/src/sage/combinat/ncsf_qsym/qsym.py b/src/sage/combinat/ncsf_qsym/qsym.py index 39d1769f0b6..af82a1569f3 100644 --- a/src/sage/combinat/ncsf_qsym/qsym.py +++ b/src/sage/combinat/ncsf_qsym/qsym.py @@ -697,7 +697,7 @@ def from_polynomial(self, f, check=True): -F[1, 1] + F[2] """ assert self.base_ring() == f.base_ring() - exponent_coefficient = f.dict() + exponent_coefficient = f.monomial_coefficients() z = {} for e, c in exponent_coefficient.items(): I = Compositions()([ei for ei in e if ei]) diff --git a/src/sage/combinat/root_system/root_lattice_realization_algebras.py b/src/sage/combinat/root_system/root_lattice_realization_algebras.py index 030b108c774..970f134ba90 100644 --- a/src/sage/combinat/root_system/root_lattice_realization_algebras.py +++ b/src/sage/combinat/root_system/root_lattice_realization_algebras.py @@ -121,7 +121,7 @@ def from_polynomial(self, p): """ L = self.basis().keys() return self.sum_of_terms((L.from_vector(vector(t)), c) - for (t,c) in p.dict().items()) + for t, c in p.monomial_coefficients().items()) @cached_method def divided_difference_on_basis(self, weight, i): diff --git a/src/sage/combinat/sf/monomial.py b/src/sage/combinat/sf/monomial.py index 0afecfa4b89..bb7b54bae4e 100644 --- a/src/sage/combinat/sf/monomial.py +++ b/src/sage/combinat/sf/monomial.py @@ -135,21 +135,25 @@ def product(self, left, right): return self._from_dict(z_elt) def from_polynomial(self, f, check=True): - """ - Return the symmetric function in the monomial basis corresponding to the polynomial ``f``. + r""" + Return the symmetric function in the monomial basis corresponding + to the polynomial ``f``. INPUT: - ``self`` -- a monomial symmetric function basis - - ``f`` -- a polynomial in finitely many variables over the same base ring as ``self``; - it is assumed that this polynomial is symmetric - - ``check`` -- boolean (default: ``True``); checks whether the polynomial is indeed symmetric + - ``f`` -- a polynomial in finitely many variables over the + same base ring as ``self``; it is assumed that this + polynomial is symmetric + - ``check`` -- boolean (default: ``True``); checks whether + the polynomial is indeed symmetric OUTPUT: - - This function converts a symmetric polynomial `f` in a polynomial ring in finitely - many variables to a symmetric function in the monomial - basis of the ring of symmetric functions over the same base ring. + - This function converts a symmetric polynomial `f` in a + polynomial ring in finitely many variables to a symmetric + function in the monomial basis of the ring of symmetric + functions over the same base ring. EXAMPLES:: @@ -173,12 +177,13 @@ def from_polynomial(self, f, check=True): sage: f = (2*m[2,1]+m[1,1]+3*m[3]).expand(3) sage: m.from_polynomial(f) m[1, 1] + 2*m[2, 1] + 3*m[3] + """ assert self.base_ring() == f.base_ring() if check and not f.is_symmetric(): raise ValueError("%s is not a symmetric polynomial" % f) out = self._from_dict({_Partitions.element_class(_Partitions, list(e)): c - for (e,c) in f.dict().items() + for e, c in f.monomial_coefficients().items() if all(e[i+1] <= e[i] for i in range(len(e)-1))}, remove_zeros=False) return out diff --git a/src/sage/combinat/sf/sfa.py b/src/sage/combinat/sf/sfa.py index 47d5e0042c1..d44758ad1ff 100644 --- a/src/sage/combinat/sf/sfa.py +++ b/src/sage/combinat/sf/sfa.py @@ -6900,7 +6900,7 @@ def _from_polynomial(p, f): n = p.parent().ngens() if n == 1: d = {_Partitions.from_exp([e]): c - for e, c in p.dict().items()} + for e, c in p.monomial_coefficients().items()} else: d = {_Partitions.from_exp(e): c for e, c in p.iterator_exp_coeff(False)} diff --git a/src/sage/combinat/triangles_FHM.py b/src/sage/combinat/triangles_FHM.py index ebd457d7487..c8248bdc5f2 100644 --- a/src/sage/combinat/triangles_FHM.py +++ b/src/sage/combinat/triangles_FHM.py @@ -381,7 +381,7 @@ def dual(self): A = self._poly.parent() dict_dual = {(n - dy, n - dx): coeff - for (dx, dy), coeff in self._poly.dict().items()} + for (dx, dy), coeff in self._poly.monomial_coefficients().items()} return M_triangle(A(dict_dual), variables=(x, y)) def transmute(self): @@ -484,7 +484,7 @@ def transpose(self): A = self._poly.parent() dict_dual = {(n - dy, n - dx): coeff - for (dx, dy), coeff in self._poly.dict().items()} + for (dx, dy), coeff in self._poly.monomial_coefficients().items()} return H_triangle(A(dict_dual), variables=(x, y)) def m(self): diff --git a/src/sage/databases/cubic_hecke_db.py b/src/sage/databases/cubic_hecke_db.py index ef8d1f7f1c5..9e5ec47a40c 100644 --- a/src/sage/databases/cubic_hecke_db.py +++ b/src/sage/databases/cubic_hecke_db.py @@ -117,7 +117,9 @@ def simplify(mat): d = mat.dict() if isinstance(B, CubicHeckeExtensionRing): # Laurent polynomial cannot be reconstructed from string - res = {k: {tuple(j): u.dict() for j, u in v.dict().items()} for k, v in d.items()} + res = {k: {tuple(j): u.monomial_coefficients() + for j, u in v.monomial_coefficients().items()} + for k, v in d.items()} else: res = {k: str(v) for k, v in d.items()} return res diff --git a/src/sage/geometry/polyhedron/generating_function.py b/src/sage/geometry/polyhedron/generating_function.py index 16200bf6616..c4bece2af55 100644 --- a/src/sage/geometry/polyhedron/generating_function.py +++ b/src/sage/geometry/polyhedron/generating_function.py @@ -680,7 +680,7 @@ def __generating_function_of_integral_points__( if sort_factors: def key(t): - D = t.dict().popitem()[0] + D = t.monomial_coefficients().popitem()[0] return (-sum(abs(d) for d in D), D) terms = sorted(terms, key=key, reverse=True) return Factorization([(numerator, 1)] + @@ -748,7 +748,7 @@ def _generating_function_via_Omega_(inequalities, B, skip_indices=()): logger.debug('terms denominator %s', terms) def decode_factor(factor): - D = factor.dict() + D = factor.monomial_coefficients() assert len(D) == 1 exponent, coefficient = next(iter(D.items())) return coefficient, exponent @@ -764,7 +764,7 @@ def decode_factor(factor): lambda factor: factor[1] == 0) other_factors = tuple(factor[0] for factor in other_factors) numerator, factors_denominator = \ - _Omega_(numerator.dict(), tuple(decoded_factors)) + _Omega_(numerator.monomial_coefficients(), tuple(decoded_factors)) terms = other_factors + factors_denominator return _simplify_(numerator, terms) diff --git a/src/sage/groups/braid.py b/src/sage/groups/braid.py index 88aa11802de..8945175cf7a 100644 --- a/src/sage/groups/braid.py +++ b/src/sage/groups/braid.py @@ -888,7 +888,7 @@ def links_gould_polynomial(self, varnames=None, use_symbolics=False): # Since the result of the calculation is known to be a Laurent polynomial # in t0 and t1 all exponents of ltemp must be divisable by 2 L = ltemp.parent() - lred = L({(k[0]/2, k[1]/2): v for k, v in ltemp.dict().items()}) + lred = L({(k[0]/2, k[1]/2): v for k, v in ltemp.monomial_coefficients().items()}) t0, t1 = R.gens() return lred(t0, t1) diff --git a/src/sage/libs/singular/singular.pyx b/src/sage/libs/singular/singular.pyx index b51c08b8506..9c7b4078583 100644 --- a/src/sage/libs/singular/singular.pyx +++ b/src/sage/libs/singular/singular.pyx @@ -1188,8 +1188,8 @@ cdef number *sa2si_transext_QQ(object elem, ring *_ring) noexcept: if nMapFuncPtr is NULL: raise RuntimeError("Failed to determine nMapFuncPtr") - numerdic = elem.numerator().dict() - denomdic = elem.denominator().dict() + numerdic = elem.numerator().monomial_coefficients() + denomdic = elem.denominator().monomial_coefficients() if numerdic and not isinstance(list(numerdic)[0], (tuple, ETuple)): numerdic = {(k,):b for k,b in numerdic.items()} @@ -1303,8 +1303,8 @@ cdef number *sa2si_transext_FF(object elem, ring *_ring) noexcept: if nMapFuncPtr is NULL: raise RuntimeError("Failed to determine nMapFuncPtr") - numerdic = elem.numerator().dict() - denomdic = elem.denominator().dict() + numerdic = elem.numerator().monomial_coefficients() + denomdic = elem.denominator().monomial_coefficients() if numerdic and not isinstance(list(numerdic)[0], (tuple, ETuple)): numerdic = {(k,):b for k,b in numerdic.items()} diff --git a/src/sage/rings/morphism.pyx b/src/sage/rings/morphism.pyx index 68ee2d5ee8e..594e2ff0a3e 100644 --- a/src/sage/rings/morphism.pyx +++ b/src/sage/rings/morphism.pyx @@ -2277,7 +2277,7 @@ cdef class RingHomomorphism_from_base(RingHomomorphism): """ P = self.codomain() try: - return P(dict([(a, self._underlying(b)) for a,b in x.dict().items()])) + return P({a: self._underlying(b) for a, b in x.monomial_coefficients().items()}) except Exception: pass try: diff --git a/src/sage/rings/multi_power_series_ring_element.py b/src/sage/rings/multi_power_series_ring_element.py index b7731d59f74..76d81db6997 100644 --- a/src/sage/rings/multi_power_series_ring_element.py +++ b/src/sage/rings/multi_power_series_ring_element.py @@ -567,7 +567,7 @@ def _subs_formal(self, *x, **kwds): base_map = kwds.get('base_map') if base_map is None: base_map = lambda t: t - for m, c in self.dict().items(): + for m, c in self.monomial_coefficients().items(): y += base_map(c)*prod([x[i]**m[i] for i in range(n) if m[i] != 0]) if self.prec() == infinity: return y @@ -1099,7 +1099,7 @@ def __mod__(self, other): return self.change_ring(Zmod(other)) raise NotImplementedError("Mod on multivariate power series ring elements not defined except modulo an integer.") - def dict(self): + def monomial_coefficients(self): """ Return underlying dictionary with keys the exponents and values the coefficients of this power series. @@ -1116,6 +1116,14 @@ def dict(self): sage: m = 2/3*t0*t1^15*t3^48 - t0^15*t1^21*t2^28*t3^5 sage: m2 = 1/2*t0^12*t1^29*t2^46*t3^6 - 1/4*t0^39*t1^5*t2^23*t3^30 + M.O(100) sage: s = m + m2 + sage: s.monomial_coefficients() + {(1, 15, 0, 48): 2/3, + (12, 29, 46, 6): 1/2, + (15, 21, 28, 5): -1, + (39, 5, 23, 30): -1/4} + + ``dict`` is an alias:: + sage: s.dict() {(1, 15, 0, 48): 2/3, (12, 29, 46, 6): 1/2, @@ -1124,9 +1132,11 @@ def dict(self): """ out_dict = {} for j in self._bg_value.coefficients(): - out_dict.update(j.dict()) + out_dict.update(j.monomial_coefficients()) return out_dict + dict = monomial_coefficients + def polynomial(self): """ Return the underlying polynomial of ``self`` as an element of @@ -1224,7 +1234,7 @@ def coefficients(self): True """ if self.is_sparse(): - return self.dict() + return self.monomial_coefficients() tmp = {} for j in self._bg_value.coefficients(): for m in j.monomials(): @@ -1727,7 +1737,7 @@ def _integral(self, xx): xxe = xx.exponents()[0] pos = [i for i, c in enumerate(xxe) if c != 0][0] # get the position of the variable res = {mon.eadd(xxe): R(co / (mon[pos]+1)) - for mon, co in self.dict().items()} + for mon, co in self.monomial_coefficients().items()} return P( res ).add_bigoh(self.prec()+1) def ogf(self): diff --git a/src/sage/rings/polynomial/flatten.py b/src/sage/rings/polynomial/flatten.py index ac0e594ab3c..6354bbcd382 100644 --- a/src/sage/rings/polynomial/flatten.py +++ b/src/sage/rings/polynomial/flatten.py @@ -224,13 +224,13 @@ def _call_(self, p): if isinstance(ring, PolynomialRing_general): for mon, pp in p.items(): assert pp.parent() is ring - for i, j in pp.dict().items(): - new_p[(i,)+(mon)] = j + for i, j in pp.monomial_coefficients().items(): + new_p[(i,) + (mon)] = j elif isinstance(ring, MPolynomialRing_base): for mon, pp in p.items(): assert pp.parent() is ring - for mmon, q in pp.dict().items(): - new_p[tuple(mmon)+mon] = q + for mmon, q in pp.monomial_coefficients().items(): + new_p[tuple(mmon) + mon] = q else: raise RuntimeError p = new_p @@ -642,7 +642,7 @@ def _call_(self, p): # apply _sub_specialization to each coefficient # in the flattened polynomial tmp = {} - for exponent, coefficient in flat.dict().items(): + for exponent, coefficient in flat.monomial_coefficients().items(): # Fix the type of exponent from (a,) to a # (necessary for R(tmp) later) if isinstance(exponent, ETuple) and len(exponent) == 1: diff --git a/src/sage/rings/polynomial/laurent_polynomial.pxd b/src/sage/rings/polynomial/laurent_polynomial.pxd index 8e9107aeb47..249e69b49e2 100644 --- a/src/sage/rings/polynomial/laurent_polynomial.pxd +++ b/src/sage/rings/polynomial/laurent_polynomial.pxd @@ -8,10 +8,10 @@ cdef class LaurentPolynomial(CommutativeAlgebraElement): cpdef _floordiv_(self, other) cpdef long number_of_terms(self) except -1 cpdef dict dict(self) + cpdef dict monomial_coefficients(self) cdef class LaurentPolynomial_univariate(LaurentPolynomial): cdef ModuleElement __u cdef long __n cpdef _normalize(self) cpdef _unsafe_mutate(self, i, value) - diff --git a/src/sage/rings/polynomial/laurent_polynomial.pyx b/src/sage/rings/polynomial/laurent_polynomial.pyx index 8b1033f4fd5..4b6ad584cb0 100644 --- a/src/sage/rings/polynomial/laurent_polynomial.pyx +++ b/src/sage/rings/polynomial/laurent_polynomial.pyx @@ -233,6 +233,9 @@ cdef class LaurentPolynomial(CommutativeAlgebraElement): """ raise NotImplementedError + cpdef dict monomial_coefficients(self): + raise NotImplementedError + def map_coefficients(self, f, new_base_ring=None): """ Apply ``f`` to the coefficients of ``self``. @@ -294,7 +297,8 @@ cdef class LaurentPolynomial(CommutativeAlgebraElement): R = R.change_ring(new_base_ring) elif isinstance(f, Map): R = R.change_ring(f.codomain()) - return R(dict([(k, f(v)) for (k, v) in self.dict().items()])) + return R(dict([(k, f(v)) + for k, v in self.monomial_coefficients().items()])) cdef class LaurentPolynomial_univariate(LaurentPolynomial): @@ -838,7 +842,7 @@ cdef class LaurentPolynomial_univariate(LaurentPolynomial): d = {repr(g): R.var(g) for g in self._parent.gens()} return self.subs(**d) - cpdef dict dict(self): + cpdef dict monomial_coefficients(self): """ Return a dictionary representing ``self``. @@ -848,16 +852,19 @@ cdef class LaurentPolynomial_univariate(LaurentPolynomial): sage: Q. = LaurentPolynomialRing(R) sage: f = (x^3 + y/t^3)^3 + t^2; f y^3*t^-9 + 3*x^3*y^2*t^-6 + 3*x^6*y*t^-3 + x^9 + t^2 - sage: f.dict() + sage: f.monomial_coefficients() {-9: y^3, -6: 3*x^3*y^2, -3: 3*x^6*y, 0: x^9, 2: 1} - sage: f.monomial_coefficients() + ``dict`` is an alias:: + + sage: f.dict() {-9: y^3, -6: 3*x^3*y^2, -3: 3*x^6*y, 0: x^9, 2: 1} """ - cdef dict d = self.__u.dict() - return {k+self.__n: d[k] for k in d} + cdef dict d = self.__u.monomial_coefficients() + return {k + self.__n: d[k] for k in d} - monomial_coefficients = dict + cpdef dict dict(self): + return self.monomial_coefficients() def coefficients(self): """ @@ -2129,7 +2136,7 @@ cdef class LaurentPolynomial_univariate(LaurentPolynomial): Multivariate Polynomial Ring in t, tinv over Rational Field """ dres = {} - for (e, c) in self.dict().items(): + for e, c in self.monomial_coefficients().items(): if e > 0: dres[(e, 0)] = c else: diff --git a/src/sage/rings/polynomial/laurent_polynomial_mpair.pyx b/src/sage/rings/polynomial/laurent_polynomial_mpair.pyx index 4b14f79cdca..5653459f106 100644 --- a/src/sage/rings/polynomial/laurent_polynomial_mpair.pyx +++ b/src/sage/rings/polynomial/laurent_polynomial_mpair.pyx @@ -281,7 +281,7 @@ cdef class LaurentPolynomial_mpair(LaurentPolynomial): # self._parent.variable_names(), # self._parent.base_ring() # ) - cdef dict D = self._poly.dict() + cdef dict D = self._poly.monomial_coefficients() cdef ETuple e if i is None: @@ -309,12 +309,12 @@ cdef class LaurentPolynomial_mpair(LaurentPolynomial): sage: L. = LaurentPolynomialRing(QQ) sage: a = w^2*z^-1 +3 - sage: a.dict() # indirect doctest + sage: a.monomial_coefficients() # indirect doctest {(0, 0): 3, (2, -1): 1} """ # cdef dict D = self._poly._mpoly_dict_recursive(self._parent.variable_names(), # self._parent.base_ring()) - cdef dict D = self._poly.dict() + cdef dict D = self._poly.monomial_coefficients() cdef dict DD if self._mon.is_constant(): self._prod = PolyDict(D) @@ -448,7 +448,7 @@ cdef class LaurentPolynomial_mpair(LaurentPolynomial): """ cdef ETuple e if self._poly.is_term(): - (e, c), = self.dict().items() + (e, c), = self.monomial_coefficients().items() e = e.emul(-1) P = self._parent try: @@ -574,7 +574,7 @@ cdef class LaurentPolynomial_mpair(LaurentPolynomial): Multivariate Polynomial Ring in t1, t1inv, t2, t2inv over Rational Field """ dres = {} - for (e, c) in self.dict().items(): + for e, c in self.monomial_coefficients().items(): exps = [] for t in e: if t > 0: @@ -742,7 +742,7 @@ cdef class LaurentPolynomial_mpair(LaurentPolynomial): self._compute_polydict() if m._prod is None: m._compute_polydict() - return self._parent(self._prod.coefficient(m.dict())) + return self._parent(self._prod.coefficient(m.monomial_coefficients())) def coefficients(self): """ @@ -781,7 +781,7 @@ cdef class LaurentPolynomial_mpair(LaurentPolynomial): sage: f.variables(sort=False) #random (y, z, x) """ - cdef dict d = self.dict() + cdef dict d = self.monomial_coefficients() cdef tuple g = self._parent.gens() cdef Py_ssize_t nvars = len(g) cdef set vars = set() @@ -794,7 +794,7 @@ cdef class LaurentPolynomial_mpair(LaurentPolynomial): v.sort() return tuple(v) - cpdef dict dict(self): + cpdef dict monomial_coefficients(self): """ Return ``self`` represented as a ``dict``. @@ -802,17 +802,20 @@ cdef class LaurentPolynomial_mpair(LaurentPolynomial): sage: L. = LaurentPolynomialRing(QQ) sage: f = 4*x^7*z^-1 + 3*x^3*y + 2*x^4*z^-2 + x^6*y^-7 - sage: sorted(f.dict().items()) + sage: sorted(f.monomial_coefficients().items()) [((3, 1, 0), 3), ((4, 0, -2), 2), ((6, -7, 0), 1), ((7, 0, -1), 4)] - sage: sorted(f.monomial_coefficients().items()) + ``dict`` is an alias:: + + sage: sorted(f.dict().items()) [((3, 1, 0), 3), ((4, 0, -2), 2), ((6, -7, 0), 1), ((7, 0, -1), 4)] """ if self._prod is None: self._compute_polydict() return < dict > self._prod.dict() - monomial_coefficients = dict + cpdef dict dict(self): + return self.monomial_coefficients() def _fraction_pair(self): """ @@ -1563,11 +1566,11 @@ cdef class LaurentPolynomial_mpair(LaurentPolynomial): except ValueError: # call _derivative() recursively on coefficients return P({m: c._derivative(var) - for (m, c) in self.dict().iteritems()}) + for m, c in self.monomial_coefficients().iteritems()}) # compute formal derivative with respect to generator cdef dict d = {} - for m, c in self.dict().iteritems(): + for m, c in self.monomial_coefficients().iteritems(): if m[index] != 0: new_m = [u for u in m] new_m[index] += -1 @@ -1648,7 +1651,7 @@ cdef class LaurentPolynomial_mpair(LaurentPolynomial): if R is None: R = LaurentPolynomialRing(self.base_ring(), x) - return R({m[i]: c for m, c in self.dict().iteritems()}) + return R({m[i]: c for m, c in self.monomial_coefficients().iteritems()}) def monomial_reduction(self): """ @@ -1718,7 +1721,7 @@ cdef class LaurentPolynomial_mpair(LaurentPolynomial): cdef list f = [] cdef dict d for t in pf: - d = (t[0].dict()) + d = (t[0].monomial_coefficients()) if len(d) == 1: # monomials are units u *= self.parent(d) ** t[1] else: diff --git a/src/sage/rings/polynomial/laurent_polynomial_ring.py b/src/sage/rings/polynomial/laurent_polynomial_ring.py index 680c4c0138c..c17819a1b2c 100644 --- a/src/sage/rings/polynomial/laurent_polynomial_ring.py +++ b/src/sage/rings/polynomial/laurent_polynomial_ring.py @@ -388,7 +388,8 @@ def value(d, R): return {k: value(v, P.base_ring()) for k, v in D.items()} except (ValueError, TypeError): pass - return sum(P({k: 1}) * value(v, P) for k, v in D.items()).dict() + return sum(P({k: 1}) * value(v, P) + for k, v in D.items()).monomial_coefficients() def from_fraction_field(L, x): r""" @@ -535,9 +536,9 @@ def _element_constructor_(self, x): P = x.parent() if set(self.variable_names()) & set(P.variable_names()): if isinstance(x, LaurentPolynomial_univariate): - d = {(k,): v for k, v in x.dict().items()} + d = {(k,): v for k, v in x.monomial_coefficients().items()} else: - d = x.dict() + d = x.monomial_coefficients() x = _split_laurent_polynomial_dict_(self, P, d) x = {k[0]: v for k, v in x.items()} elif P is self.base_ring(): @@ -545,7 +546,7 @@ def _element_constructor_(self, x): elif x.is_constant() and self.has_coerce_map_from(x.parent().base_ring()): return self(x.constant_coefficient()) elif len(self.variable_names()) == len(P.variable_names()): - x = x.dict() + x = x.monomial_coefficients() elif isinstance(x, FractionFieldElement): # since the field of fraction of self is defined corresponding to @@ -762,9 +763,9 @@ def _element_constructor_(self, x, mon=None): pass elif set(self.variable_names()) & set(P.variable_names()): if isinstance(x, LaurentPolynomial_univariate): - d = {(k,): v for k, v in x.dict().items()} + d = {(k,): v for k, v in x.monomial_coefficients().items()} else: - d = x.dict() + d = x.monomial_coefficients() x = _split_laurent_polynomial_dict_(self, P, d) elif P is self.base_ring(): from sage.rings.polynomial.polydict import ETuple @@ -773,7 +774,7 @@ def _element_constructor_(self, x, mon=None): elif x.is_constant() and self.has_coerce_map_from(P.base_ring()): return self(x.constant_coefficient()) elif len(self.variable_names()) == len(P.variable_names()): - x = x.dict() + x = x.monomial_coefficients() elif isinstance(x, FractionFieldElement): # since the field of fraction of self is defined corresponding to diff --git a/src/sage/rings/polynomial/multi_polynomial.pyx b/src/sage/rings/polynomial/multi_polynomial.pyx index c1fcaba8187..a537334ba3f 100644 --- a/src/sage/rings/polynomial/multi_polynomial.pyx +++ b/src/sage/rings/polynomial/multi_polynomial.pyx @@ -243,7 +243,7 @@ cdef class MPolynomial(CommutativePolynomial): - Didier Deshommes """ - d = self.dict() + d = self.monomial_coefficients() return [d[i] for i in self.exponents()] def truncate(self, var, n): @@ -260,8 +260,8 @@ cdef class MPolynomial(CommutativePolynomial): ind = Z.index(var) except ValueError: raise ValueError("var must be one of the generators of the parent polynomial ring.") - d = self.dict() - return R(dict([(k, c) for k, c in d.iteritems() if k[ind] < n])) + return R({k: c for k, c in self.monomial_coefficients().iteritems() + if k[ind] < n}) def _fast_callable_(self, etb): r""" @@ -299,9 +299,9 @@ cdef class MPolynomial(CommutativePolynomial): n = len(x) expr = etb.constant(self.base_ring().zero()) - for (m, c) in self.dict().iteritems(): - monom = prod([ x[i]**m[i] for i in range(n) if m[i] != 0], - etb.constant(c)) + for m, c in self.monomial_coefficients().iteritems(): + monom = prod([x[i] ** m[i] for i in range(n) if m[i] != 0], + etb.constant(c)) expr = expr + monom return expr @@ -426,11 +426,11 @@ cdef class MPolynomial(CommutativePolynomial): d = self.degree(var) B = ring.base_ring() w = {remove_from_tuple(e, ind): val - for e, val in self.dict().iteritems() if not e[ind]} + for e, val in self.monomial_coefficients().iteritems() if not e[ind]} v = [B(w)] # coefficients that don't involve var z = var for i in range(1,d+1): - c = self.coefficient(z).dict() + c = self.coefficient(z).monomial_coefficients() w = {remove_from_tuple(e, ind): val for e, val in c.iteritems()} v.append(B(w)) z *= var @@ -483,7 +483,7 @@ cdef class MPolynomial(CommutativePolynomial): vars = self._parent.variable_names_recursive() cdef tuple my_vars = self._parent.variable_names() if vars == my_vars: - return self.dict() + return self.monomial_coefficients() elif my_vars[-1] not in vars: x = base_ring(self) if base_ring is not None else self const_ix = ETuple((0,)*len(vars)) @@ -511,13 +511,13 @@ cdef class MPolynomial(CommutativePolynomial): new_map[k] -= m tmp = [0] * (len(vars) - m) try: - for ix,a in self.dict().iteritems(): + for ix, a in self.monomial_coefficients().iteritems(): for k in range(len(my_vars)): tmp[new_map[k]] = ix[k] postfix = ETuple(tmp) mpoly = a._mpoly_dict_recursive(prev_vars, base_ring) - for prefix,b in mpoly.iteritems(): - D[prefix+postfix] = b + for prefix, b in mpoly.iteritems(): + D[prefix + postfix] = b return D except AttributeError: @@ -527,7 +527,7 @@ cdef class MPolynomial(CommutativePolynomial): base_ring = None tmp = [0] * len(vars) - for ix,a in self.dict().iteritems(): + for ix, a in self.monomial_coefficients().iteritems(): for k in range(len(my_vars)): tmp[mapping[k]] = ix[k] if base_ring is not None: @@ -578,7 +578,7 @@ cdef class MPolynomial(CommutativePolynomial): cdef long result_mon var_name_hash = [hash(v) for v in self._parent.variable_names()] cdef long c_hash - for m,c in self.dict().iteritems(): + for m, c in self.monomial_coefficients().iteritems(): # I'm assuming (incorrectly) that hashes of zero indicate that the element is 0. # This assumption is not true, but I think it is true enough for the purposes and it # it allows us to write fast code that omits terms with 0 coefficients. This is @@ -913,7 +913,7 @@ cdef class MPolynomial(CommutativePolynomial): """ if isinstance(R, Map): return self.map_coefficients(R) - return self.parent().change_ring(R)(self.dict()) + return self.parent().change_ring(R)(self.monomial_coefficients()) def is_symmetric(self, group=None): r""" @@ -997,7 +997,7 @@ cdef class MPolynomial(CommutativePolynomial): raise ValueError("argument must be a permutation group") gens = [S(g) for g in gens] - cdef dict coeffs = self.dict() + cdef dict coeffs = self.monomial_coefficients() zero = self.base_ring().zero() return all(coeffs.get(g._act_on_etuple_on_position(e), zero) == coeff for e, coeff in coeffs.items() for g in gens) @@ -1360,7 +1360,7 @@ cdef class MPolynomial(CommutativePolynomial): R = R.change_ring(new_base_ring) elif isinstance(f, Map): R = R.change_ring(f.codomain()) - return R(dict([(k,f(v)) for (k,v) in self.dict().items()])) + return R({k: f(v) for k, v in self.monomial_coefficients().items()}) def _norm_over_nonprime_finite_field(self): r""" @@ -2611,7 +2611,7 @@ cdef class MPolynomial(CommutativePolynomial): # K[x,y,...] as K[x][y]... if not self.constant_coefficient().is_unit(): return False - cdef dict d = self.dict() + cdef dict d = self.monomial_coefficients() cdef ETuple zero_key = ETuple({}, int(self.parent().ngens())) d.pop(zero_key, None) return all(d[k].is_nilpotent() for k in d) @@ -2646,7 +2646,7 @@ cdef class MPolynomial(CommutativePolynomial): # Section 7.3 Exercise 33). # This generalizes easily to the multivariate case, by considering # K[x,y,...] as K[x][y]... - d = self.dict() + d = self.monomial_coefficients() return all(c.is_nilpotent() for c in d.values()) def _test_subs(self, tester=None, **options): diff --git a/src/sage/rings/polynomial/multi_polynomial_element.py b/src/sage/rings/polynomial/multi_polynomial_element.py index e856fd9e46e..2f3310b3af9 100644 --- a/src/sage/rings/polynomial/multi_polynomial_element.py +++ b/src/sage/rings/polynomial/multi_polynomial_element.py @@ -74,7 +74,6 @@ from sage.rings.rational_field import QQ from sage.rings.fraction_field import FractionField - class MPolynomial_element(MPolynomial): r""" Generic multivariate polynomial. @@ -802,7 +801,7 @@ def monomial_coefficient(self, mon): zero = self.parent().base_ring().zero() return self.element().get(exp, zero) - def dict(self): + def monomial_coefficients(self): """ Return underlying dictionary with keys the exponents and values the coefficients of this polynomial. @@ -812,15 +811,17 @@ def dict(self): sage: # needs sage.rings.number_field sage: R. = PolynomialRing(QQbar, order='lex') sage: f = (x^1*y^5*z^2 + x^2*z + x^4*y^1*z^3) - sage: f.dict() + sage: f.monomial_coefficients() {(1, 5, 2): 1, (2, 0, 1): 1, (4, 1, 3): 1} - sage: f.monomial_coefficients() # needs sage.rings.number_field + ``dict`` is an alias:: + + sage: f.dict() # needs sage.rings.number_field {(1, 5, 2): 1, (2, 0, 1): 1, (4, 1, 3): 1} """ return self.element().dict() - monomial_coefficients = dict + dict = monomial_coefficients def __iter__(self): """ @@ -1867,12 +1868,12 @@ def _floordiv_(self, right): """ # handle division by monomials without using Singular - if len(right.dict()) == 1: + if len(right.monomial_coefficients()) == 1: P = self.parent() ret = P(0) - denC,denM = next(iter(right)) - for c,m in self: - t = c*m + denC, denM = next(iter(right)) + for c, m in self: + t = c * m if denC.divides(c) and P.monomial_divides(denM, m): ret += P.monomial_quotient(t, right, coeff=True) return ret @@ -1928,7 +1929,8 @@ def _derivative(self, var=None): if index == -1: # var is not a generator; do term-by-term differentiation recursively # var may be, for example, a generator of the base ring - d = dict([(e, x._derivative(var)) for (e, x) in self.dict().items()]) + d = dict([(e, x._derivative(var)) + for e, x in self.monomial_coefficients().items()]) d = polydict.PolyDict(d, check=False) d.remove_zeros() return MPolynomial_polydict(P, d) @@ -2025,7 +2027,7 @@ def integral(self, var=None): # var is not a generator; do term-by-term integration recursively # var may be, for example, a generator of the base ring d = {e: x.integral(var) - for e, x in self.dict().items()} + for e, x in self.monomial_coefficients().items()} d = polydict.PolyDict(d, check=False) d.remove_zeros() else: diff --git a/src/sage/rings/polynomial/multi_polynomial_libsingular.pyx b/src/sage/rings/polynomial/multi_polynomial_libsingular.pyx index 307735c46ba..0f05f3a93d9 100644 --- a/src/sage/rings/polynomial/multi_polynomial_libsingular.pyx +++ b/src/sage/rings/polynomial/multi_polynomial_libsingular.pyx @@ -2088,10 +2088,11 @@ cdef class MPolynomial_libsingular(MPolynomial_libsingular_base): except TypeError: # give up, evaluate functional sage_res = parent.base_ring().zero() - for m, c in self.dict().iteritems(): + for m, c in self.monomial_coefficients().iteritems(): sage_res += c * mul([x[i] ** m[i] for i in m.nonzero_positions()]) else: - singular_polynomial_call(&res, self._poly, _ring, coerced_x, MPolynomial_libsingular_get_element) + singular_polynomial_call(&res, self._poly, _ring, coerced_x, + MPolynomial_libsingular_get_element) if res == NULL: return res_parent(0) @@ -2983,7 +2984,7 @@ cdef class MPolynomial_libsingular(MPolynomial_libsingular_base): return self._parent._base._zero_element - def dict(self): + def monomial_coefficients(self): """ Return a dictionary representing ``self``. This dictionary is in the same format as the generic MPolynomial: The dictionary @@ -2993,10 +2994,12 @@ cdef class MPolynomial_libsingular(MPolynomial_libsingular_base): sage: R. = QQ[] sage: f = 2*x*y^3*z^2 + 1/7*x^2 + 2/3 - sage: f.dict() + sage: f.monomial_coefficients() {(0, 0, 0): 2/3, (1, 3, 2): 2, (2, 0, 0): 1/7} - sage: f.monomial_coefficients() + ``dict`` is an alias:: + + sage: f.dict() {(0, 0, 0): 2/3, (1, 3, 2): 2, (2, 0, 0): 1/7} """ cdef poly *p @@ -3019,7 +3022,8 @@ cdef class MPolynomial_libsingular(MPolynomial_libsingular_base): p = pNext(p) return pd - monomial_coefficients = dict + def dict(self): + return self.monomial_coefficients() def iterator_exp_coeff(self, as_ETuples=True): """ @@ -3612,8 +3616,8 @@ cdef class MPolynomial_libsingular(MPolynomial_libsingular_base): for m, v in items: gg[g.index(m)] = v y = parent.base_ring().zero() - for (m,c) in self.dict().items(): - y += c*mul([ gg[i]**m[i] for i in m.nonzero_positions()]) + for m, c in self.monomial_coefficients().items(): + y += c*mul([gg[i] ** m[i] for i in m.nonzero_positions()]) return y _f = ( v)._poly if p_IsConstant(_f, _ring): @@ -5227,7 +5231,8 @@ cdef class MPolynomial_libsingular(MPolynomial_libsingular_base): sage: parent(h(R.0,0)) Univariate Polynomial Ring in x over Rational Field """ - return unpickle_MPolynomial_libsingular, (self._parent, self.dict()) + return unpickle_MPolynomial_libsingular, (self._parent, + self.monomial_coefficients()) def _im_gens_(self, codomain, im_gens, base_map=None): """ @@ -5268,8 +5273,8 @@ cdef class MPolynomial_libsingular(MPolynomial_libsingular_base): if base_map is None: # Just use conversion base_map = codomain - for (m,c) in self.dict().iteritems(): - y += base_map(c)*mul([ im_gens[i]**m[i] for i in range(n) if m[i]]) + for m, c in self.monomial_coefficients().iteritems(): + y += base_map(c) * mul([im_gens[i] ** m[i] for i in range(n) if m[i]]) return y def _derivative(self, MPolynomial_libsingular var): @@ -5396,7 +5401,7 @@ cdef class MPolynomial_libsingular(MPolynomial_libsingular_base): v = ETuple({index: 1}, len(gens)) _p = p_ISet(0, _ring) - for (exp, coeff) in self.dict().iteritems(): + for exp, coeff in self.monomial_coefficients().iteritems(): nexp = exp.eadd(v) # new exponent mon = p_Init(_ring) p_SetCoeff(mon, sa2si(coeff / (1 + exp[index]), _ring), _ring) diff --git a/src/sage/rings/polynomial/multi_polynomial_ring.py b/src/sage/rings/polynomial/multi_polynomial_ring.py index 588358ab3d9..41cc1fb7c87 100644 --- a/src/sage/rings/polynomial/multi_polynomial_ring.py +++ b/src/sage/rings/polynomial/multi_polynomial_ring.py @@ -430,13 +430,16 @@ def __call__(self, x=0, check=True): if P is self: return x - elif P == self: + + if P == self: return MPolynomial_polydict(self, x.element().dict()) - elif self.base_ring().has_coerce_map_from(P): + + if self.base_ring().has_coerce_map_from(P): # it might be in the base ring (i.e. a poly ring over a poly ring) c = self.base_ring()(x) return MPolynomial_polydict(self, {self._zero_tuple: c}) - elif len(P.variable_names()) == len(self.variable_names()): + + if len(P.variable_names()) == len(self.variable_names()): # Map the variables in some crazy way (but in order, # of course). This is here since R(blah) is supposed # to be "make an element of R if at all possible with @@ -446,63 +449,76 @@ def __call__(self, x=0, check=True): for i, a in D.items(): D[i] = K(a) return MPolynomial_polydict(self, D) - elif set(P.variable_names()).issubset(set(self.variable_names())) and self.base_ring().has_coerce_map_from(P.base_ring()): + + if (set(P.variable_names()).issubset(set(self.variable_names())) + and self.base_ring().has_coerce_map_from(P.base_ring())): # If the named variables are a superset of the input, map the variables by name return MPolynomial_polydict(self, self._extract_polydict(x)) - else: - return MPolynomial_polydict(self, x._mpoly_dict_recursive(self.variable_names(), self.base_ring())) + + return MPolynomial_polydict(self, + x._mpoly_dict_recursive(self.variable_names(), + self.base_ring())) elif isinstance(x, MPolynomial_libsingular): P = x.parent() if P == self: - return MPolynomial_polydict(self, x.dict()) - elif self.base_ring().has_coerce_map_from(P): + return MPolynomial_polydict(self, x.monomial_coefficients()) + + if self.base_ring().has_coerce_map_from(P): # it might be in the base ring (i.e. a poly ring over a poly ring) c = self.base_ring()(x) return MPolynomial_polydict(self, {self._zero_tuple: c}) - elif len(P.variable_names()) == len(self.variable_names()): + + if len(P.variable_names()) == len(self.variable_names()): # Map the variables in some crazy way (but in order, # of course). This is here since R(blah) is supposed # to be "make an element of R if at all possible with # no guarantees that this is mathematically solid." K = self.base_ring() - D = x.dict() + D = x.monomial_coefficients() for i, a in D.items(): D[i] = K(a) return MPolynomial_polydict(self, D) - elif set(P.variable_names()).issubset(set(self.variable_names())) and self.base_ring().has_coerce_map_from(P.base_ring()): + + if (set(P.variable_names()).issubset(set(self.variable_names())) + and self.base_ring().has_coerce_map_from(P.base_ring())): # If the named variables are a superset of the input, map the variables by name return MPolynomial_polydict(self, self._extract_polydict(x)) - else: - return MPolynomial_polydict(self, x._mpoly_dict_recursive(self.variable_names(), self.base_ring())) - elif isinstance(x, polynomial_element.Polynomial): - return MPolynomial_polydict(self, x._mpoly_dict_recursive(self.variable_names(), self.base_ring())) + return MPolynomial_polydict(self, + x._mpoly_dict_recursive(self.variable_names(), + self.base_ring())) - elif isinstance(x, PolyDict): + if isinstance(x, polynomial_element.Polynomial): + return MPolynomial_polydict(self, + x._mpoly_dict_recursive(self.variable_names(), + self.base_ring())) + + if isinstance(x, PolyDict): return MPolynomial_polydict(self, x) - elif isinstance(x, dict): + if isinstance(x, dict): K = self.base_ring() return MPolynomial_polydict(self, {i: K(a) for i, a in x.items()}) - elif isinstance(x, fraction_field_element.FractionFieldElement) and x.parent().ring() == self: + if (isinstance(x, fraction_field_element.FractionFieldElement) + and x.parent().ring() == self): if x.denominator() == 1: return x.numerator() - else: - raise TypeError("unable to coerce since the denominator is not 1") - elif isinstance(x, sage.interfaces.abc.SingularElement) and self._has_singular: + raise TypeError("unable to coerce since the denominator is not 1") + + if isinstance(x, sage.interfaces.abc.SingularElement) and self._has_singular: self._singular_().set_ring() try: return x.sage_poly(self) except TypeError: raise TypeError("unable to coerce singular object") - elif hasattr(x, '_polynomial_'): + if hasattr(x, '_polynomial_'): return x._polynomial_(self) - elif isinstance(x, str): + if isinstance(x, str): from sage.misc.sage_eval import sage_eval try: x = sage_eval(x, self.gens_dict_recursive()) @@ -510,7 +526,7 @@ def __call__(self, x=0, check=True): raise TypeError("unable to evaluate {!r} in {}".format(x, self)) return self(x) - elif isinstance(x, sage.interfaces.abc.Macaulay2Element): + if isinstance(x, sage.interfaces.abc.Macaulay2Element): try: s = x.sage_polystring() if len(s) == 0: @@ -524,7 +540,7 @@ def __call__(self, x=0, check=True): raise TypeError("Unable to coerce macaulay2 object") return MPolynomial_polydict(self, x) - elif isinstance(x, pari_gen) and x.type() == 't_POL': + if isinstance(x, pari_gen) and x.type() == 't_POL': # This recursive approach is needed because PARI # represents multivariate polynomials as iterated # univariate polynomials. Below, v is the variable @@ -538,9 +554,9 @@ def __call__(self, x=0, check=True): if isinstance(x, dict): return MPolynomial_polydict(self, x) - else: - c = self.base_ring()(x) - return MPolynomial_polydict(self, {self._zero_tuple: c}) + + c = self.base_ring()(x) + return MPolynomial_polydict(self, {self._zero_tuple: c}) # The following methods are handy for implementing Groebner # basis algorithms. They do only superficial type/sanity checks @@ -627,8 +643,8 @@ def monomial_quotient(self, f, g, coeff=False): if not g: raise ZeroDivisionError - fd = f.dict() - gd = g.dict() + fd = f.monomial_coefficients() + gd = g.monomial_coefficients() if not coeff: f = next(iter(fd)) @@ -682,8 +698,8 @@ def monomial_lcm(self, f, g): """ one = self.base_ring().one() - f, = f.dict() - g, = g.dict() + f, = f.monomial_coefficients() + g, = g.monomial_coefficients() length = len(f) @@ -785,8 +801,8 @@ def monomial_divides(self, a, b): if not a: raise ZeroDivisionError - a, = a.dict() - b, = b.dict() + a, = a.monomial_coefficients() + b, = b.monomial_coefficients() return all(b[i] >= a[i] for i in b.common_nonzero_positions(a)) @@ -879,7 +895,7 @@ def addwithcarry(tempvector, maxvector, pos): one = self.base_ring().one() M = list() - v, = t.dict() + v, = t.monomial_coefficients() maxvector = list(v) tempvector = [0] * len(maxvector) diff --git a/src/sage/rings/polynomial/multi_polynomial_ring_base.pyx b/src/sage/rings/polynomial/multi_polynomial_ring_base.pyx index fa9947b028e..dffe6cb80c1 100644 --- a/src/sage/rings/polynomial/multi_polynomial_ring_base.pyx +++ b/src/sage/rings/polynomial/multi_polynomial_ring_base.pyx @@ -619,12 +619,14 @@ cdef class MPolynomialRing_base(CommutativeRing): """ # This is probably horribly inefficient other_vars = list(x.parent().variable_names()) - name_mapping = [(other_vars.index(var) if var in other_vars else -1) for var in self.variable_names()] + name_mapping = [(other_vars.index(var) if var in other_vars else -1) + for var in self.variable_names()] K = self.base_ring() D = {} var_range = range(len(self.variable_names())) - for ix, a in x.dict().iteritems(): - ix = ETuple([0 if name_mapping[t] == -1 else ix[name_mapping[t]] for t in var_range]) + for ix, a in x.monomial_coefficients().iteritems(): + ix = ETuple([0 if name_mapping[t] == -1 else ix[name_mapping[t]] + for t in var_range]) D[ix] = K(a) return D diff --git a/src/sage/rings/polynomial/omega.py b/src/sage/rings/polynomial/omega.py index 20a61096548..797200f4e40 100644 --- a/src/sage/rings/polynomial/omega.py +++ b/src/sage/rings/polynomial/omega.py @@ -311,7 +311,7 @@ def MacMahonOmega(var, expression, denominator=None, op=operator.ge, decoded_factors = [] for factor in factors_denominator: factor = L(factor) - D = factor.dict() + D = factor.monomial_coefficients() if not D: raise ZeroDivisionError('Denominator contains a factor 0.') elif len(D) == 1: @@ -331,7 +331,7 @@ def MacMahonOmega(var, expression, denominator=None, op=operator.ge, numerator = L(numerator) / prod(to_numerator) result_numerator, result_factors_denominator = \ - _Omega_(numerator.dict(), decoded_factors) + _Omega_(numerator.monomial_coefficients(), decoded_factors) if result_numerator == 0: return Factorization([], unit=result_numerator) @@ -589,7 +589,7 @@ def subs_power(expression, var, exponent): It is assumed that ``var`` only occurs with exponents divisible by ``exponent``. """ - p = tuple(var.dict().popitem()[0]).index(1) # var is the p-th generator + p = tuple(var.monomial_coefficients().popitem()[0]).index(1) # var is the p-th generator def subs_e(e): e = list(e) @@ -597,7 +597,8 @@ def subs_e(e): e[p] = e[p] // exponent return tuple(e) parent = expression.parent() - result = parent({subs_e(e): c for e, c in expression.dict().items()}) + result = parent({subs_e(e): c + for e, c in expression.monomial_coefficients().items()}) return result def de_power(expression): diff --git a/src/sage/rings/polynomial/ore_polynomial_element.pxd b/src/sage/rings/polynomial/ore_polynomial_element.pxd index f38bcb0f0c5..73bc162a146 100644 --- a/src/sage/rings/polynomial/ore_polynomial_element.pxd +++ b/src/sage/rings/polynomial/ore_polynomial_element.pxd @@ -17,7 +17,7 @@ cdef class OrePolynomial(AlgebraElement): cpdef bint is_zero(self) noexcept cpdef bint is_one(self) noexcept - + cdef _left_quo_rem(self, OrePolynomial other) cdef _right_quo_rem(self, OrePolynomial other) cdef OrePolynomial _left_lcm_cofactor(self, OrePolynomial other) @@ -39,6 +39,7 @@ cdef class OrePolynomial_generic_dense(OrePolynomial): cpdef _mul_(self, other) cpdef dict dict(self) + cpdef dict monomial_coefficients(self) cpdef list list(self, bint copy=*) diff --git a/src/sage/rings/polynomial/ore_polynomial_element.pyx b/src/sage/rings/polynomial/ore_polynomial_element.pyx index 1acc82dd583..09146960c86 100644 --- a/src/sage/rings/polynomial/ore_polynomial_element.pyx +++ b/src/sage/rings/polynomial/ore_polynomial_element.pyx @@ -2481,7 +2481,7 @@ cdef class OrePolynomial_generic_dense(OrePolynomial): else: return (self)._coeffs - cpdef dict dict(self): + cpdef dict monomial_coefficients(self): r""" Return a dictionary representation of ``self``. @@ -2506,7 +2506,8 @@ cdef class OrePolynomial_generic_dense(OrePolynomial): X[i] = c return X - monomial_coefficients = dict + cpdef dict dict(self): + return self.monomial_coefficients() cpdef Integer degree(self): r""" diff --git a/src/sage/rings/polynomial/padics/polynomial_padic_capped_relative_dense.py b/src/sage/rings/polynomial/padics/polynomial_padic_capped_relative_dense.py index 604764eff35..668f66fe574 100644 --- a/src/sage/rings/polynomial/padics/polynomial_padic_capped_relative_dense.py +++ b/src/sage/rings/polynomial/padics/polynomial_padic_capped_relative_dense.py @@ -51,7 +51,7 @@ def __init__(self, parent, x=None, check=True, is_gen=False, construct=False, ab Check that :issue:`13620` has been fixed:: sage: f = R.zero() - sage: R(f.dict()) + sage: R(f.monomial_coefficients()) 0 Check that :issue:`29829` has been fixed:: diff --git a/src/sage/rings/polynomial/polynomial_element.pyx b/src/sage/rings/polynomial/polynomial_element.pyx index dbb7a6f0565..04fb9518ab8 100644 --- a/src/sage/rings/polynomial/polynomial_element.pyx +++ b/src/sage/rings/polynomial/polynomial_element.pyx @@ -76,7 +76,6 @@ from sage.arith.power cimport generic_power from sage.arith.misc import crt from sage.arith.long cimport pyobject_to_long from sage.misc.mrange import cartesian_product_iterator -from sage.misc.superseded import deprecated_function_alias from sage.structure.factorization import Factorization from sage.structure.richcmp cimport (richcmp, richcmp_item, rich_to_bool, rich_to_bool_sgn) @@ -174,7 +173,6 @@ cpdef is_Polynomial(f): sage: is_Polynomial(f) False """ - from sage.misc.superseded import deprecation deprecation(32709, "the function is_Polynomial is deprecated; use isinstance(x, sage.rings.polynomial.polynomial_element.Polynomial) instead") return isinstance(f, Polynomial) @@ -862,7 +860,7 @@ cdef class Polynomial(CommutativePolynomial): return R(pol) if pol._parent.is_sparse(): coeff_sparse = {} - coeff_dict = pol.dict() + coeff_dict = pol.monomial_coefficients() for i in coeff_dict: coeff_sparse[i * d] = coeff_dict[i] return R(coeff_sparse, check=False) @@ -883,7 +881,7 @@ cdef class Polynomial(CommutativePolynomial): if a.is_monomial(): etup = ETuple(( a).degrees()) if pol._parent.is_sparse(): - coeff_dict = pol.dict() + coeff_dict = pol.monomial_coefficients() return R({etup.emul(key): coeff_dict[key] for key in coeff_dict}) # Dense version return R({etup.emul(i): c for i, c in enumerate(pol)}) @@ -2648,7 +2646,6 @@ cdef class Polynomial(CommutativePolynomial): # ensure that the degree is positive. degree = ZZ(degree) if degree < 0: - from sage.misc.superseded import deprecation deprecation(37170, "negative ``degree`` will be disallowed. Instead use the bool `assume_equal_deg`.") degree = -degree assume_equal_deg = True @@ -2931,7 +2928,7 @@ cdef class Polynomial(CommutativePolynomial): q = right sparse = self.parent().is_sparse() if sparse: - d = self.dict() + d = self.monomial_coefficients() else: c = self.list(copy=False) while q > 0: @@ -4464,7 +4461,7 @@ cdef class Polynomial(CommutativePolynomial): if self.get_unsafe(n) else zero for n in range(self.degree() + 1)] return S(p) - def dict(self): + def monomial_coefficients(self): """ Return a sparse dictionary representation of this univariate polynomial. @@ -4473,10 +4470,12 @@ cdef class Polynomial(CommutativePolynomial): sage: R. = QQ[] sage: f = x^3 + -1/7*x + 13 - sage: f.dict() + sage: f.monomial_coefficients() {0: 13, 1: -1/7, 3: 1} - sage: f.monomial_coefficients() + ``dict`` is an alias:: + + sage: f.dict() {0: 13, 1: -1/7, 3: 1} """ cdef dict X = {} @@ -4488,7 +4487,8 @@ cdef class Polynomial(CommutativePolynomial): X[i] = c return X - monomial_coefficients = dict + def dict(self): + return self.monomial_coefficients() def factor(self, **kwargs): r""" @@ -10600,7 +10600,7 @@ cdef class Polynomial(CommutativePolynomial): R = R.change_ring(new_base_ring) elif isinstance(f, Map): R = R.change_ring(f.codomain()) - return R({k: f(v) for k, v in self.dict().items()}) + return R({k: f(v) for k, v in self.monomial_coefficients().items()}) def is_cyclotomic(self, certificate=False, algorithm='pari'): r""" diff --git a/src/sage/rings/polynomial/polynomial_element_generic.py b/src/sage/rings/polynomial/polynomial_element_generic.py index abfe216aae8..c3df26200e2 100644 --- a/src/sage/rings/polynomial/polynomial_element_generic.py +++ b/src/sage/rings/polynomial/polynomial_element_generic.py @@ -39,16 +39,16 @@ except ImportError: pari_gen = () -from sage.structure.richcmp import richcmp, richcmp_item, rich_to_bool, rich_to_bool_sgn from sage.structure.element import coerce_binop, parent +from sage.structure.factorization import Factorization +from sage.structure.richcmp import richcmp, richcmp_item, rich_to_bool, rich_to_bool_sgn from sage.rings.infinity import infinity, Infinity from sage.rings.integer_ring import ZZ from sage.rings.integer import Integer -from sage.structure.factorization import Factorization - from sage.rings.padics.precision_error import PrecisionError + class Polynomial_generic_sparse(Polynomial): """ A generic sparse polynomial. @@ -99,18 +99,18 @@ def __init__(self, parent, x=None, check=True, is_gen=False, construct=False): R = parent.base_ring() if isinstance(x, Polynomial): if x.parent() == self.parent(): - x = dict(x.dict()) + x = x.monomial_coefficients() elif x.parent() == R: - x = {0:x} + x = {0: x} else: w = {} - for n, c in x.dict().items(): + for n, c in x.monomial_coefficients().items(): w[n] = R(c) # The following line has been added in github issue #9944. # Apparently, the "else" case has never occurred before. x = w elif isinstance(x, (list, tuple)): - x = dict((i, c) for (i, c) in enumerate(x) if c) + x = {i: c for i, c in enumerate(x) if c} elif isinstance(x, pari_gen): y = {} for i in range(len(x)): @@ -118,7 +118,7 @@ def __init__(self, parent, x=None, check=True, is_gen=False, construct=False): x = y check = True elif not isinstance(x, dict): - x = {0:x} # constant polynomials + x = {0: x} # constant polynomials if check: self.__coeffs = {} for i, z in x.items(): @@ -128,7 +128,7 @@ def __init__(self, parent, x=None, check=True, is_gen=False, construct=False): if check: self.__normalize() - def dict(self): + def monomial_coefficients(self): """ Return a new copy of the dict of the underlying elements of ``self``. @@ -138,18 +138,20 @@ def dict(self): sage: R. = PolynomialRing(Integers(8), sparse=True) sage: f = 5 + w^1997 - w^10000; f 7*w^10000 + w^1997 + 5 - sage: d = f.dict(); d + sage: d = f.monomial_coefficients(); d {0: 5, 1997: 1, 10000: 7} sage: d[0] = 10 - sage: f.dict() + sage: f.monomial_coefficients() {0: 5, 1997: 1, 10000: 7} - sage: f.monomial_coefficients() + ``dict`` is an alias:: + + sage: f.dict() {0: 5, 1997: 1, 10000: 7} """ return dict(self.__coeffs) - monomial_coefficients = dict + dict = monomial_coefficients def coefficients(self, sparse=True): """ diff --git a/src/sage/rings/polynomial/polynomial_ring_homomorphism.pyx b/src/sage/rings/polynomial/polynomial_ring_homomorphism.pyx index b3ce1183e5e..01aca9fed01 100644 --- a/src/sage/rings/polynomial/polynomial_ring_homomorphism.pyx +++ b/src/sage/rings/polynomial/polynomial_ring_homomorphism.pyx @@ -58,7 +58,7 @@ cdef class PolynomialRingHomomorphism_from_base(RingHomomorphism_from_base): P = self.codomain() f = self.underlying_map() if P.is_sparse(): - return P({a: f(b) for a, b in x.dict().iteritems()}) + return P({a: f(b) for a, b in x.monomial_coefficients().iteritems()}) else: return P([f(b) for b in x]) @@ -88,7 +88,8 @@ cdef class PolynomialRingHomomorphism_from_base(RingHomomorphism_from_base): P = self.codomain() f = self.underlying_map() if P.is_sparse(): - return P({a: f(b) for a, b in x.dict().iteritems()}, *args, **kwds) + return P({a: f(b) for a, b in x.monomial_coefficients().iteritems()}, + *args, **kwds) else: return P([f(b) for b in x], *args, **kwds) diff --git a/src/sage/rings/power_series_mpoly.pyx b/src/sage/rings/power_series_mpoly.pyx index 42cf467912b..44c4be93423 100644 --- a/src/sage/rings/power_series_mpoly.pyx +++ b/src/sage/rings/power_series_mpoly.pyx @@ -58,11 +58,11 @@ cdef class PowerSeries_mpoly(PowerSeries): d = {} if isinstance(B, MPolynomialRing_base): for i in range(len(v)): - for n, c in v[i].dict().iteritems(): + for n, c in v[i].monomial_coefficients().iteritems(): d[tuple(n) + (i,)] = c else: for i in range(len(v)): - for n, c in v[i].dict().iteritems(): + for n, c in v[i].monomial_coefficients().iteritems(): d[(n,i)] = c self.__f = S(d) diff --git a/src/sage/rings/power_series_pari.pyx b/src/sage/rings/power_series_pari.pyx index 0e491cad78a..ca79b979228 100644 --- a/src/sage/rings/power_series_pari.pyx +++ b/src/sage/rings/power_series_pari.pyx @@ -734,7 +734,7 @@ cdef class PowerSeries_pari(PowerSeries): else: return [R(g)] + [R.zero()] * (n - 1) - def dict(self): + def monomial_coefficients(self): """ Return a dictionary of coefficients for ``self``. @@ -746,10 +746,18 @@ cdef class PowerSeries_pari(PowerSeries): sage: R. = PowerSeriesRing(ZZ, implementation='pari') sage: f = 1 + t^10 + O(t^12) + sage: f.monomial_coefficients() + {0: 1, 10: 1} + + ``dict`` is an alias:: + sage: f.dict() {0: 1, 10: 1} """ - return self.polynomial().dict() + return self.polynomial().monomial_coefficients() + + def dict(self): + return self.monomial_coefficients() def _derivative(self, var=None): """ diff --git a/src/sage/rings/power_series_poly.pyx b/src/sage/rings/power_series_poly.pyx index 91f790ffa16..4f5e02df06c 100644 --- a/src/sage/rings/power_series_poly.pyx +++ b/src/sage/rings/power_series_poly.pyx @@ -794,7 +794,7 @@ cdef class PowerSeries_poly(PowerSeries): """ return self.__f.list() - def dict(self): + def monomial_coefficients(self): """ Return a dictionary of coefficients for ``self``. @@ -806,10 +806,18 @@ cdef class PowerSeries_poly(PowerSeries): sage: R. = ZZ[[]] sage: f = 1 + t^10 + O(t^12) + sage: f.monomial_coefficients() + {0: 1, 10: 1} + + ``dict`` is an alias:: + sage: f.dict() {0: 1, 10: 1} """ - return self.__f.dict() + return self.__f.monomial_coefficients() + + def dict(self): + return self.monomial_coefficients() def _derivative(self, var=None): """ diff --git a/src/sage/rings/power_series_ring_element.pyx b/src/sage/rings/power_series_ring_element.pyx index 34e84ddbc5f..725927ba5ad 100644 --- a/src/sage/rings/power_series_ring_element.pyx +++ b/src/sage/rings/power_series_ring_element.pyx @@ -1045,7 +1045,7 @@ cdef class PowerSeries(AlgebraElement): else: n = int(n) v = {} - for k, x in self.dict().iteritems(): + for k, x in self.monomial_coefficients().iteritems(): if k >= n: v[k-n] = x return self._parent(v, self.prec()-n) diff --git a/src/sage/rings/qqbar.py b/src/sage/rings/qqbar.py index 47365a9a8c6..300d64b8279 100644 --- a/src/sage/rings/qqbar.py +++ b/src/sage/rings/qqbar.py @@ -981,9 +981,9 @@ def _factor_multivariate_polynomial(self, f, proof=True): numfield_polynomial_flat = numfield.polynomial()(nf_gen) - polynomial_flat = sum(flat_ring({(0,)+tuple(k):1}) + polynomial_flat = sum(flat_ring({(0,) + tuple(k): 1}) * v.polynomial()(nf_gen) - for k,v in numfield_f.dict().items()) + for k, v in numfield_f.monomial_coefficients().items()) norm_flat = polynomial_flat.resultant(numfield_polynomial_flat, nf_gen) norm_f = norm_flat((0,)+norm_ring.gens()) diff --git a/src/sage/rings/semirings/tropical_mpolynomial.py b/src/sage/rings/semirings/tropical_mpolynomial.py index 0fa89866a12..d8df667530b 100644 --- a/src/sage/rings/semirings/tropical_mpolynomial.py +++ b/src/sage/rings/semirings/tropical_mpolynomial.py @@ -401,7 +401,7 @@ def _repr_(self): sage: x + R(-1)*y + R(-3) 0*x + (-1)*y + (-3) """ - if not self.dict(): + if not self.monomial_coefficients(): return str(self.parent().base().zero()) s = super()._repr_() if self.monomials()[-1].is_constant(): @@ -425,7 +425,7 @@ def _latex_(self): sage: latex(R.zero()) \infty """ - if not self.dict(): + if not self.monomial_coefficients(): return self.parent().base().zero()._latex_() s = super()._latex_() if self.monomials()[-1].is_constant(): @@ -531,7 +531,7 @@ def _element_constructor_(self, x): raise ValueError(f"can not convert {x} to {self}") if isinstance(x, MPolynomial): if x.parent().variable_names() == self.variable_names(): - x = x.dict() + x = x.monomial_coefficients() else: raise ValueError(f"can not convert {x} to {self}") elif (x in self.base().base_ring()) or (x in self.base()): @@ -630,9 +630,8 @@ def random_element(self, degree=2, terms=None, choose_degree=False, R = PolynomialRing(self.base().base_ring(), self.variable_names()) f = R.random_element(degree=degree, terms=terms, choose_degree=choose_degree, *args, **kwargs) - new_dict = {} - for key, value in f.dict().items(): - new_dict[key] = self.base()(value) + new_dict = {key: self.base()(value) + for key, value in f.monomial_coefficients().items()} return self.element_class(self, new_dict) def gen(self, n=0): diff --git a/src/sage/rings/semirings/tropical_polynomial.py b/src/sage/rings/semirings/tropical_polynomial.py index b2d595e7e0a..74125633a22 100644 --- a/src/sage/rings/semirings/tropical_polynomial.py +++ b/src/sage/rings/semirings/tropical_polynomial.py @@ -207,7 +207,7 @@ def roots(self): """ from itertools import combinations tropical_roots = [] - data = self.dict() + data = self.monomial_coefficients() R = self.parent().base() if len(data) == 1: exponent = next(iter(data)) @@ -279,7 +279,7 @@ def split_form(self): """ roots = self.roots() R = self.parent() - poly = R(self.dict()[self.degree()].lift()) + poly = R(self.monomial_coefficients()[self.degree()].lift()) for root in roots: linear = R([root, 0]) poly *= linear @@ -321,7 +321,7 @@ def factor(self): (3) * 0 """ from sage.structure.factorization import Factorization - unit = self.dict()[self.degree()] + unit = self.monomial_coefficients()[self.degree()] if self != self.split_form() or not self.roots(): factor = [(self * self.parent(-unit.lift()), 1)] return Factorization(factor, unit=unit) @@ -374,7 +374,7 @@ def piecewise_function(self): from sage.sets.real_set import RealSet x = SR.var('x') - data = self.dict() + data = self.monomial_coefficients() R = self.parent().base() if not self.roots(): f = data[0].lift() @@ -537,7 +537,7 @@ def _repr_(self): (-1)*x^3 + 2*x^2 + (-1)*x + (-3) """ import re - if not self.dict(): + if not self.monomial_coefficients(): return str(self.parent().base().zero()) def replace_negatives(expr): @@ -844,7 +844,7 @@ def random_element(self, degree=(-1, 2), monic=False, *args, **kwds): from sage.rings.polynomial.polynomial_ring_constructor import PolynomialRing R = PolynomialRing(self.base().base_ring(), self.variable_names()) f = R.random_element(degree=degree, monic=monic, *args, **kwds) - new_dict = f.dict() + new_dict = f.monomial_coefficients() if monic: new_dict[f.degree()] = 0 return self.element_class(self, new_dict) diff --git a/src/sage/rings/semirings/tropical_variety.py b/src/sage/rings/semirings/tropical_variety.py index e65b2408904..3eb04372d13 100644 --- a/src/sage/rings/semirings/tropical_variety.py +++ b/src/sage/rings/semirings/tropical_variety.py @@ -201,7 +201,7 @@ def __init__(self, poly): # Convert each term to its linear function linear_eq = {} - pd = poly.dict() + pd = poly.monomial_coefficients() for key in pd: eq = sum(variables[i] * e for i, e in enumerate(key)) eq += pd[key].lift() diff --git a/src/sage/rings/tate_algebra_element.pyx b/src/sage/rings/tate_algebra_element.pyx index 1c435a2ccec..d8aa8758b42 100644 --- a/src/sage/rings/tate_algebra_element.pyx +++ b/src/sage/rings/tate_algebra_element.pyx @@ -1074,7 +1074,7 @@ cdef class TateAlgebraElement(CommutativeAlgebraElement): else: try: poly = parent._polynomial_ring(x) - self._poly = PolyDict(poly.dict(), None) + self._poly = PolyDict(poly.monomial_coefficients(), None) except TypeError: # last chance: we first try to convert to the rational Tate series if parent._integral: @@ -2192,7 +2192,7 @@ cdef class TateAlgebraElement(CommutativeAlgebraElement): """ return [ t.monomial() for t in self.terms() ] - def dict(self): + def monomial_coefficients(self): """ Return a dictionary whose keys are the exponents and whose values are the corresponding coefficients of this series. @@ -2202,12 +2202,20 @@ cdef class TateAlgebraElement(CommutativeAlgebraElement): sage: R = Zp(2, prec=10, print_mode='digits') sage: A. = TateAlgebra(R) sage: f = 2*x^2 + x + sage: f.monomial_coefficients() + {(1, 0): ...0000000001, (2, 0): ...00000000010} + + ``dict`` is an alias:: + sage: f.dict() {(1, 0): ...0000000001, (2, 0): ...00000000010} """ self._normalize() return dict(self._poly.__repn) + def dict(self): + return self.monomial_coefficients() + def coefficient(self, exponent): r""" Return the coefficient corresponding to the given exponent. diff --git a/src/sage/schemes/curves/projective_curve.py b/src/sage/schemes/curves/projective_curve.py index 7c8cf62c5ea..ed0da70e237 100755 --- a/src/sage/schemes/curves/projective_curve.py +++ b/src/sage/schemes/curves/projective_curve.py @@ -1105,7 +1105,7 @@ def quadratic_transform(self): for i in range(len(L)): degs[i] = min(F.degree(L[i]), degs[i]) T = [] - for item in G.dict().items(): + for item in G.monomial_coefficients().items(): tup = tuple([item[0][i] - degs[i] for i in range(len(L))]) T.append((tup, item[1])) G = R(dict(T)) @@ -1280,11 +1280,11 @@ def excellent_position(self, Q): if j == 0: div_pow = min(e[1] for e in npoly.exponents()) npoly = PP.coordinate_ring()({(v0, v1 - div_pow, v2): g - for (v0, v1, v2), g in npoly.dict().items()}) + for (v0, v1, v2), g in npoly.monomial_coefficients().items()}) else: div_pow = min(e[0] for e in npoly.exponents()) npoly = PP.coordinate_ring()({(v0 - div_pow, v1, v2): g - for (v0, v1, v2), g in npoly.dict().items()}) + for (v0, v1, v2), g in npoly.monomial_coefficients().items()}) # check the degree again if npoly.degree() != d - r: need_continue = True diff --git a/src/sage/schemes/plane_conics/con_rational_function_field.py b/src/sage/schemes/plane_conics/con_rational_function_field.py index 6ac78706107..26522878918 100755 --- a/src/sage/schemes/plane_conics/con_rational_function_field.py +++ b/src/sage/schemes/plane_conics/con_rational_function_field.py @@ -503,12 +503,12 @@ def find_point(self, supports, roots, case, solution=0): lastpoly = F(1) for n in range(B): lastpoly = (lastpoly * t) % p - phi_p[A + 2 + n] = vector(F, d, lastpoly.dict()) + phi_p[A + 2 + n] = vector(F, d, lastpoly.monomial_coefficients()) lastpoly = -alpha % p - phi_p[A + B + 2] = vector(F, d, lastpoly.dict()) + phi_p[A + B + 2] = vector(F, d, lastpoly.monomial_coefficients()) for n in range(C): lastpoly = (lastpoly * t) % p - phi_p[A + B + 3 + n] = vector(F, d, lastpoly.dict()) + phi_p[A + B + 3 + n] = vector(F, d, lastpoly.monomial_coefficients()) phi_p[A + B + C + 3] = vector(F, d) phi.append(matrix(phi_p).transpose()) for (i, p) in enumerate(supports[1]): @@ -525,12 +525,12 @@ def find_point(self, supports, roots, case, solution=0): lastpoly = F(1) for n in range(C): lastpoly = (lastpoly * t) % p - phi_p[A + B + 3 + n] = vector(F, d, lastpoly.dict()) + phi_p[A + B + 3 + n] = vector(F, d, lastpoly.monomial_coefficients()) lastpoly = -alpha % p - phi_p[0] = vector(F, d, lastpoly.dict()) + phi_p[0] = vector(F, d, lastpoly.monomial_coefficients()) for n in range(A): lastpoly = (lastpoly * t) % p - phi_p[1 + n] = vector(F, d, lastpoly.dict()) + phi_p[1 + n] = vector(F, d, lastpoly.monomial_coefficients()) phi_p[A + B + C + 3] = vector(F, d) phi.append(matrix(phi_p).transpose()) for (i, p) in enumerate(supports[2]): @@ -547,12 +547,12 @@ def find_point(self, supports, roots, case, solution=0): lastpoly = F(1) for n in range(A): lastpoly = (lastpoly * t) % p - phi_p[1 + n] = vector(F, d, lastpoly.dict()) + phi_p[1 + n] = vector(F, d, lastpoly.monomial_coefficients()) lastpoly = -alpha % p - phi_p[A + 1] = vector(F, d, lastpoly.dict()) + phi_p[A + 1] = vector(F, d, lastpoly.monomial_coefficients()) for n in range(B): lastpoly = (lastpoly * t) % p - phi_p[A + 2 + n] = vector(F, d, lastpoly.dict()) + phi_p[A + 2 + n] = vector(F, d, lastpoly.monomial_coefficients()) phi_p[A + B + C + 3] = vector(F, d) phi.append(matrix(phi_p).transpose()) if case == 0: diff --git a/src/sage/schemes/riemann_surfaces/riemann_surface.py b/src/sage/schemes/riemann_surfaces/riemann_surface.py index 0c3e2724229..701f6523065 100755 --- a/src/sage/schemes/riemann_surfaces/riemann_surface.py +++ b/src/sage/schemes/riemann_surfaces/riemann_surface.py @@ -358,7 +358,7 @@ def differential_basis_baker(f): return None from sage.geometry.polyhedron.constructor import Polyhedron - D = {(k[0], k[1]): v for k, v in f.dict().items()} + D = {(k[0], k[1]): v for k, v in f.monomial_coefficients().items()} P = Polyhedron(D) kT = k["t"] # here we check the additional genericity conditions: that the polynomials @@ -3044,7 +3044,7 @@ def initialise(z, i): A = PolynomialRing(self._CC, "xyz") aes = [] for mp in mp_list: - d = mp.dict() + d = mp.monomial_coefficients() mp = sum( [ d[k] * CCzg.gen(0)**k[0] * CCzg.gen(1)**k[1] diff --git a/src/sage/schemes/toric/ideal.py b/src/sage/schemes/toric/ideal.py index 93a28beafe8..4c171595e6a 100755 --- a/src/sage/schemes/toric/ideal.py +++ b/src/sage/schemes/toric/ideal.py @@ -407,7 +407,7 @@ def subtract(e, power): return tuple([l[0] - power] + l[1:]) def divide_by_x_n(p): - d_old = p.dict() + d_old = p.monomial_coefficients() power = min(e[0] for e in d_old) d_new = {subtract(exponent, power): coefficient for exponent, coefficient in d_old.items()} diff --git a/src/sage/schemes/toric/weierstrass_covering.py b/src/sage/schemes/toric/weierstrass_covering.py index 87d414d3464..82c300c1f7a 100755 --- a/src/sage/schemes/toric/weierstrass_covering.py +++ b/src/sage/schemes/toric/weierstrass_covering.py @@ -255,9 +255,9 @@ def homogenize(inhomog, degree): result = vector(ZZ, result) result.set_immutable() return result - X_dict = {homogenize(e, 2): v for e, v in X.dict().items()} - Y_dict = {homogenize(e, 3): v for e, v in Y.dict().items()} - Z_dict = {homogenize(e, 1): v for e, v in Z.dict().items()} + X_dict = {homogenize(e, 2): v for e, v in X.monomial_coefficients().items()} + Y_dict = {homogenize(e, 3): v for e, v in Y.monomial_coefficients().items()} + Z_dict = {homogenize(e, 1): v for e, v in Z.monomial_coefficients().items()} # shift to nonnegative exponents if necessary min_deg = [0] * R.ngens() for var in variables: diff --git a/src/sage/structure/parent.pyx b/src/sage/structure/parent.pyx index 44c23ff8fb0..8e8940b5846 100644 --- a/src/sage/structure/parent.pyx +++ b/src/sage/structure/parent.pyx @@ -1680,7 +1680,7 @@ cdef class Parent(sage.structure.category_object.CategoryObject): ....: ....: def _act_(self, g, a): ....: D = {} - ....: for k, v in a.dict().items(): + ....: for k, v in a.monomial_coefficients().items(): ....: nk = [0]*len(k) ....: for i in range(len(k)): ....: nk[g(i+1)-1] = k[i] diff --git a/src/sage/symbolic/expression.pyx b/src/sage/symbolic/expression.pyx index 1001cbda600..18d47b0da2c 100644 --- a/src/sage/symbolic/expression.pyx +++ b/src/sage/symbolic/expression.pyx @@ -7503,7 +7503,7 @@ cdef class Expression(Expression_abc): [[-5, 0], [6, 2]] sage: g.polynomial(QQ).list() [-5, 0, 6] - sage: g.polynomial(QQ).dict() + sage: g.polynomial(QQ).monomial_coefficients() {0: -5, 2: 6} :: From 81f9a96ddcae6681dfa6ddd5583c0800ba41d882 Mon Sep 17 00:00:00 2001 From: Martin Rubey Date: Sat, 5 Oct 2024 12:06:43 +0200 Subject: [PATCH 8/9] make dict an alias to avoid duplicating docstrings --- src/sage/rings/polynomial/laurent_polynomial.pxd | 2 +- src/sage/rings/polynomial/laurent_polynomial.pyx | 10 ++++------ src/sage/rings/polynomial/laurent_polynomial_mpair.pyx | 3 +-- .../rings/polynomial/multi_polynomial_libsingular.pyx | 3 +-- src/sage/rings/polynomial/ore_polynomial_element.pxd | 1 - src/sage/rings/polynomial/ore_polynomial_element.pyx | 9 +++++---- src/sage/rings/polynomial/polynomial_element.pyx | 3 +-- src/sage/rings/power_series_pari.pyx | 3 +-- src/sage/rings/power_series_poly.pyx | 3 +-- src/sage/rings/tate_algebra_element.pyx | 3 +-- 10 files changed, 16 insertions(+), 24 deletions(-) diff --git a/src/sage/rings/polynomial/laurent_polynomial.pxd b/src/sage/rings/polynomial/laurent_polynomial.pxd index 249e69b49e2..1937490caac 100644 --- a/src/sage/rings/polynomial/laurent_polynomial.pxd +++ b/src/sage/rings/polynomial/laurent_polynomial.pxd @@ -7,9 +7,9 @@ cdef class LaurentPolynomial(CommutativeAlgebraElement): cpdef _mul_(self, other) cpdef _floordiv_(self, other) cpdef long number_of_terms(self) except -1 - cpdef dict dict(self) cpdef dict monomial_coefficients(self) + cdef class LaurentPolynomial_univariate(LaurentPolynomial): cdef ModuleElement __u cdef long __n diff --git a/src/sage/rings/polynomial/laurent_polynomial.pyx b/src/sage/rings/polynomial/laurent_polynomial.pyx index 4b6ad584cb0..d90ce333af1 100644 --- a/src/sage/rings/polynomial/laurent_polynomial.pyx +++ b/src/sage/rings/polynomial/laurent_polynomial.pyx @@ -218,7 +218,7 @@ cdef class LaurentPolynomial(CommutativeAlgebraElement): """ return self.number_of_terms() - cpdef dict dict(self): + cpdef dict monomial_coefficients(self): """ Abstract ``dict`` method. @@ -226,15 +226,14 @@ cdef class LaurentPolynomial(CommutativeAlgebraElement): sage: R. = LaurentPolynomialRing(ZZ) sage: from sage.rings.polynomial.laurent_polynomial import LaurentPolynomial - sage: LaurentPolynomial.dict(x) + sage: LaurentPolynomial.monomial_coefficients(x) Traceback (most recent call last): ... NotImplementedError """ raise NotImplementedError - cpdef dict monomial_coefficients(self): - raise NotImplementedError + dict = monomial_coefficients def map_coefficients(self, f, new_base_ring=None): """ @@ -863,8 +862,7 @@ cdef class LaurentPolynomial_univariate(LaurentPolynomial): cdef dict d = self.__u.monomial_coefficients() return {k + self.__n: d[k] for k in d} - cpdef dict dict(self): - return self.monomial_coefficients() + dict = monomial_coefficients def coefficients(self): """ diff --git a/src/sage/rings/polynomial/laurent_polynomial_mpair.pyx b/src/sage/rings/polynomial/laurent_polynomial_mpair.pyx index 5653459f106..3da9540d905 100644 --- a/src/sage/rings/polynomial/laurent_polynomial_mpair.pyx +++ b/src/sage/rings/polynomial/laurent_polynomial_mpair.pyx @@ -814,8 +814,7 @@ cdef class LaurentPolynomial_mpair(LaurentPolynomial): self._compute_polydict() return < dict > self._prod.dict() - cpdef dict dict(self): - return self.monomial_coefficients() + dict = monomial_coefficients def _fraction_pair(self): """ diff --git a/src/sage/rings/polynomial/multi_polynomial_libsingular.pyx b/src/sage/rings/polynomial/multi_polynomial_libsingular.pyx index 0f05f3a93d9..6f105277f5b 100644 --- a/src/sage/rings/polynomial/multi_polynomial_libsingular.pyx +++ b/src/sage/rings/polynomial/multi_polynomial_libsingular.pyx @@ -3022,8 +3022,7 @@ cdef class MPolynomial_libsingular(MPolynomial_libsingular_base): p = pNext(p) return pd - def dict(self): - return self.monomial_coefficients() + dict = monomial_coefficients def iterator_exp_coeff(self, as_ETuples=True): """ diff --git a/src/sage/rings/polynomial/ore_polynomial_element.pxd b/src/sage/rings/polynomial/ore_polynomial_element.pxd index 73bc162a146..771c4d6325a 100644 --- a/src/sage/rings/polynomial/ore_polynomial_element.pxd +++ b/src/sage/rings/polynomial/ore_polynomial_element.pxd @@ -38,7 +38,6 @@ cdef class OrePolynomial_generic_dense(OrePolynomial): cdef list _mul_list(self, list A) cpdef _mul_(self, other) - cpdef dict dict(self) cpdef dict monomial_coefficients(self) cpdef list list(self, bint copy=*) diff --git a/src/sage/rings/polynomial/ore_polynomial_element.pyx b/src/sage/rings/polynomial/ore_polynomial_element.pyx index 09146960c86..768565840f6 100644 --- a/src/sage/rings/polynomial/ore_polynomial_element.pyx +++ b/src/sage/rings/polynomial/ore_polynomial_element.pyx @@ -2491,10 +2491,12 @@ cdef class OrePolynomial_generic_dense(OrePolynomial): sage: sigma = R.hom([t+1]) sage: S. = R['x',sigma] sage: a = x^2012 + t*x^1006 + t^3 + 2*t - sage: a.dict() + sage: a.monomial_coefficients() {0: t^3 + 2*t, 1006: t, 2012: 1} - sage: a.monomial_coefficients() + ``dict`` is an alias:: + + sage: a.dict() {0: t^3 + 2*t, 1006: t, 2012: 1} """ cdef dict X = {} @@ -2506,8 +2508,7 @@ cdef class OrePolynomial_generic_dense(OrePolynomial): X[i] = c return X - cpdef dict dict(self): - return self.monomial_coefficients() + dict = monomial_coefficients cpdef Integer degree(self): r""" diff --git a/src/sage/rings/polynomial/polynomial_element.pyx b/src/sage/rings/polynomial/polynomial_element.pyx index 04fb9518ab8..85ab231395a 100644 --- a/src/sage/rings/polynomial/polynomial_element.pyx +++ b/src/sage/rings/polynomial/polynomial_element.pyx @@ -4487,8 +4487,7 @@ cdef class Polynomial(CommutativePolynomial): X[i] = c return X - def dict(self): - return self.monomial_coefficients() + dict = monomial_coefficients def factor(self, **kwargs): r""" diff --git a/src/sage/rings/power_series_pari.pyx b/src/sage/rings/power_series_pari.pyx index ca79b979228..8f7ff769dd1 100644 --- a/src/sage/rings/power_series_pari.pyx +++ b/src/sage/rings/power_series_pari.pyx @@ -756,8 +756,7 @@ cdef class PowerSeries_pari(PowerSeries): """ return self.polynomial().monomial_coefficients() - def dict(self): - return self.monomial_coefficients() + dict = monomial_coefficients def _derivative(self, var=None): """ diff --git a/src/sage/rings/power_series_poly.pyx b/src/sage/rings/power_series_poly.pyx index 4f5e02df06c..309d72c8f6a 100644 --- a/src/sage/rings/power_series_poly.pyx +++ b/src/sage/rings/power_series_poly.pyx @@ -816,8 +816,7 @@ cdef class PowerSeries_poly(PowerSeries): """ return self.__f.monomial_coefficients() - def dict(self): - return self.monomial_coefficients() + dict = monomial_coefficients def _derivative(self, var=None): """ diff --git a/src/sage/rings/tate_algebra_element.pyx b/src/sage/rings/tate_algebra_element.pyx index d8aa8758b42..c2fd9cbfc8d 100644 --- a/src/sage/rings/tate_algebra_element.pyx +++ b/src/sage/rings/tate_algebra_element.pyx @@ -2213,8 +2213,7 @@ cdef class TateAlgebraElement(CommutativeAlgebraElement): self._normalize() return dict(self._poly.__repn) - def dict(self): - return self.monomial_coefficients() + dict = monomial_coefficients def coefficient(self, exponent): r""" From 38904b6cfe8a1deaa33cac7e8a3c203b594443bc Mon Sep 17 00:00:00 2001 From: Martin Rubey Date: Sat, 5 Oct 2024 12:28:20 +0200 Subject: [PATCH 9/9] replace iteritems with items in modified files --- .../free_algebra_element_letterplace.pyx | 2 +- .../polynomial/laurent_polynomial_mpair.pyx | 10 +++++----- src/sage/rings/polynomial/multi_polynomial.pyx | 16 ++++++++-------- .../polynomial/multi_polynomial_libsingular.pyx | 16 ++++++++-------- .../polynomial/multi_polynomial_ring_base.pyx | 2 +- src/sage/rings/polynomial/plural.pyx | 2 +- src/sage/rings/polynomial/polynomial_element.pyx | 6 +++--- .../polynomial/polynomial_ring_homomorphism.pyx | 4 ++-- src/sage/rings/power_series_mpoly.pyx | 4 ++-- src/sage/rings/power_series_ring_element.pyx | 2 +- src/sage/rings/tate_algebra_element.pyx | 4 +++- src/sage/symbolic/expression.pyx | 6 +++--- 12 files changed, 38 insertions(+), 36 deletions(-) diff --git a/src/sage/algebras/letterplace/free_algebra_element_letterplace.pyx b/src/sage/algebras/letterplace/free_algebra_element_letterplace.pyx index 8eae3602f9d..2a977b1a513 100644 --- a/src/sage/algebras/letterplace/free_algebra_element_letterplace.pyx +++ b/src/sage/algebras/letterplace/free_algebra_element_letterplace.pyx @@ -140,7 +140,7 @@ cdef class FreeAlgebraElement_letterplace(AlgebraElement): [((0, 0, 0, 1, 0, 0, 0, 1), 2), ((0, 1, 0, 0, 0, 0, 1, 0), 1)] """ cdef dict d = self._poly.monomial_coefficients() - yield from d.iteritems() + yield from d.items() def _repr_(self): """ diff --git a/src/sage/rings/polynomial/laurent_polynomial_mpair.pyx b/src/sage/rings/polynomial/laurent_polynomial_mpair.pyx index 3da9540d905..2384eaf5b12 100644 --- a/src/sage/rings/polynomial/laurent_polynomial_mpair.pyx +++ b/src/sage/rings/polynomial/laurent_polynomial_mpair.pyx @@ -108,7 +108,7 @@ cdef class LaurentPolynomial_mpair(LaurentPolynomial): if isinstance(x, dict): self._mon = ETuple({}, int(parent.ngens())) D = {} - for k, x_k in x.iteritems(): # ETuple-ize keys, set _mon + for k, x_k in x.items(): # ETuple-ize keys, set _mon if not isinstance(k, (tuple, ETuple)) or len(k) != parent.ngens(): self._mon = ETuple({}, int(parent.ngens())) break @@ -119,7 +119,7 @@ cdef class LaurentPolynomial_mpair(LaurentPolynomial): else: x = D if not self._mon.is_constant(): # factor out _mon - x = {k.esub(self._mon): x_k for k, x_k in x.iteritems()} + x = {k.esub(self._mon): x_k for k, x_k in x.items()} elif (isinstance(x, LaurentPolynomial_mpair) and parent.variable_names() == x.parent().variable_names()): self._mon = ( < LaurentPolynomial_mpair > x)._mon @@ -1565,11 +1565,11 @@ cdef class LaurentPolynomial_mpair(LaurentPolynomial): except ValueError: # call _derivative() recursively on coefficients return P({m: c._derivative(var) - for m, c in self.monomial_coefficients().iteritems()}) + for m, c in self.monomial_coefficients().items()}) # compute formal derivative with respect to generator cdef dict d = {} - for m, c in self.monomial_coefficients().iteritems(): + for m, c in self.monomial_coefficients().items(): if m[index] != 0: new_m = [u for u in m] new_m[index] += -1 @@ -1650,7 +1650,7 @@ cdef class LaurentPolynomial_mpair(LaurentPolynomial): if R is None: R = LaurentPolynomialRing(self.base_ring(), x) - return R({m[i]: c for m, c in self.monomial_coefficients().iteritems()}) + return R({m[i]: c for m, c in self.monomial_coefficients().items()}) def monomial_reduction(self): """ diff --git a/src/sage/rings/polynomial/multi_polynomial.pyx b/src/sage/rings/polynomial/multi_polynomial.pyx index a537334ba3f..e6cfbcec7cb 100644 --- a/src/sage/rings/polynomial/multi_polynomial.pyx +++ b/src/sage/rings/polynomial/multi_polynomial.pyx @@ -260,7 +260,7 @@ cdef class MPolynomial(CommutativePolynomial): ind = Z.index(var) except ValueError: raise ValueError("var must be one of the generators of the parent polynomial ring.") - return R({k: c for k, c in self.monomial_coefficients().iteritems() + return R({k: c for k, c in self.monomial_coefficients().items() if k[ind] < n}) def _fast_callable_(self, etb): @@ -299,7 +299,7 @@ cdef class MPolynomial(CommutativePolynomial): n = len(x) expr = etb.constant(self.base_ring().zero()) - for m, c in self.monomial_coefficients().iteritems(): + for m, c in self.monomial_coefficients().items(): monom = prod([x[i] ** m[i] for i in range(n) if m[i] != 0], etb.constant(c)) expr = expr + monom @@ -426,12 +426,12 @@ cdef class MPolynomial(CommutativePolynomial): d = self.degree(var) B = ring.base_ring() w = {remove_from_tuple(e, ind): val - for e, val in self.monomial_coefficients().iteritems() if not e[ind]} + for e, val in self.monomial_coefficients().items() if not e[ind]} v = [B(w)] # coefficients that don't involve var z = var for i in range(1,d+1): c = self.coefficient(z).monomial_coefficients() - w = {remove_from_tuple(e, ind): val for e, val in c.iteritems()} + w = {remove_from_tuple(e, ind): val for e, val in c.items()} v.append(B(w)) z *= var return ring(v) @@ -511,12 +511,12 @@ cdef class MPolynomial(CommutativePolynomial): new_map[k] -= m tmp = [0] * (len(vars) - m) try: - for ix, a in self.monomial_coefficients().iteritems(): + for ix, a in self.monomial_coefficients().items(): for k in range(len(my_vars)): tmp[new_map[k]] = ix[k] postfix = ETuple(tmp) mpoly = a._mpoly_dict_recursive(prev_vars, base_ring) - for prefix, b in mpoly.iteritems(): + for prefix, b in mpoly.items(): D[prefix + postfix] = b return D @@ -527,7 +527,7 @@ cdef class MPolynomial(CommutativePolynomial): base_ring = None tmp = [0] * len(vars) - for ix, a in self.monomial_coefficients().iteritems(): + for ix, a in self.monomial_coefficients().items(): for k in range(len(my_vars)): tmp[mapping[k]] = ix[k] if base_ring is not None: @@ -578,7 +578,7 @@ cdef class MPolynomial(CommutativePolynomial): cdef long result_mon var_name_hash = [hash(v) for v in self._parent.variable_names()] cdef long c_hash - for m, c in self.monomial_coefficients().iteritems(): + for m, c in self.monomial_coefficients().items(): # I'm assuming (incorrectly) that hashes of zero indicate that the element is 0. # This assumption is not true, but I think it is true enough for the purposes and it # it allows us to write fast code that omits terms with 0 coefficients. This is diff --git a/src/sage/rings/polynomial/multi_polynomial_libsingular.pyx b/src/sage/rings/polynomial/multi_polynomial_libsingular.pyx index 6f105277f5b..6f489e75a5a 100644 --- a/src/sage/rings/polynomial/multi_polynomial_libsingular.pyx +++ b/src/sage/rings/polynomial/multi_polynomial_libsingular.pyx @@ -855,7 +855,7 @@ cdef class MPolynomialRing_libsingular(MPolynomialRing_base): if element.parent() == self: bucket = sBucketCreate(_ring) try: - for (m,c) in element.element().dict().iteritems(): + for m, c in element.element().dict().items(): mon = p_Init(_ring) p_SetCoeff(mon, sa2si(c, _ring), _ring) for pos in m.nonzero_positions(): @@ -893,7 +893,7 @@ cdef class MPolynomialRing_libsingular(MPolynomialRing_base): if element.parent().ngens() <= self.ngens(): bucket = sBucketCreate(_ring) try: - for (m,c) in element.element().dict().iteritems(): + for m, c in element.element().dict().items(): if check: c = base_ring(c) if not c: @@ -923,7 +923,7 @@ cdef class MPolynomialRing_libsingular(MPolynomialRing_base): else: bucket = sBucketCreate(_ring) try: - for (m,c) in element.iteritems(): + for m, c in element.items(): if check: c = base_ring(c) if not c: @@ -2088,7 +2088,7 @@ cdef class MPolynomial_libsingular(MPolynomial_libsingular_base): except TypeError: # give up, evaluate functional sage_res = parent.base_ring().zero() - for m, c in self.monomial_coefficients().iteritems(): + for m, c in self.monomial_coefficients().items(): sage_res += c * mul([x[i] ** m[i] for i in m.nonzero_positions()]) else: singular_polynomial_call(&res, self._poly, _ring, coerced_x, @@ -5272,7 +5272,7 @@ cdef class MPolynomial_libsingular(MPolynomial_libsingular_base): if base_map is None: # Just use conversion base_map = codomain - for m, c in self.monomial_coefficients().iteritems(): + for m, c in self.monomial_coefficients().items(): y += base_map(c) * mul([im_gens[i] ** m[i] for i in range(n) if m[i]]) return y @@ -5400,7 +5400,7 @@ cdef class MPolynomial_libsingular(MPolynomial_libsingular_base): v = ETuple({index: 1}, len(gens)) _p = p_ISet(0, _ring) - for exp, coeff in self.monomial_coefficients().iteritems(): + for exp, coeff in self.monomial_coefficients().items(): nexp = exp.eadd(v) # new exponent mon = p_Init(_ring) p_SetCoeff(mon, sa2si(coeff / (1 + exp[index]), _ring), _ring) @@ -5906,9 +5906,9 @@ def unpickle_MPolynomial_libsingular(MPolynomialRing_libsingular R, d): rChangeCurrRing(r) bucket = sBucketCreate(r) try: - for mon,c in d.iteritems(): + for mon, c in d.items(): m = p_Init(r) - for i,e in mon.sparse_iter(): + for i, e in mon.sparse_iter(): _i = i if _i >= r.N: p_Delete(&m, r) diff --git a/src/sage/rings/polynomial/multi_polynomial_ring_base.pyx b/src/sage/rings/polynomial/multi_polynomial_ring_base.pyx index dffe6cb80c1..fd1be03bea5 100644 --- a/src/sage/rings/polynomial/multi_polynomial_ring_base.pyx +++ b/src/sage/rings/polynomial/multi_polynomial_ring_base.pyx @@ -624,7 +624,7 @@ cdef class MPolynomialRing_base(CommutativeRing): K = self.base_ring() D = {} var_range = range(len(self.variable_names())) - for ix, a in x.monomial_coefficients().iteritems(): + for ix, a in x.monomial_coefficients().items(): ix = ETuple([0 if name_mapping[t] == -1 else ix[name_mapping[t]] for t in var_range]) D[ix] = K(a) diff --git a/src/sage/rings/polynomial/plural.pyx b/src/sage/rings/polynomial/plural.pyx index 8fb9592e0b7..735d7d98041 100644 --- a/src/sage/rings/polynomial/plural.pyx +++ b/src/sage/rings/polynomial/plural.pyx @@ -1403,7 +1403,7 @@ def unpickle_NCPolynomial_plural(NCPolynomialRing_plural R, d): cdef int _i, _e p = p_ISet(0,r) rChangeCurrRing(r) - for mon,c in d.iteritems(): + for mon, c in d.items(): m = p_Init(r) for i,e in mon.sparse_iter(): _i = i diff --git a/src/sage/rings/polynomial/polynomial_element.pyx b/src/sage/rings/polynomial/polynomial_element.pyx index 85ab231395a..2449b3208ae 100644 --- a/src/sage/rings/polynomial/polynomial_element.pyx +++ b/src/sage/rings/polynomial/polynomial_element.pyx @@ -3880,7 +3880,7 @@ cdef class Polynomial(CommutativePolynomial): cdef dict D = {} cdef tuple leftovers = (0,) * (len(variables) - len(prev_variables) - 1) for k in range(len(mpolys)): - for i,a in mpolys[k].iteritems(): + for i, a in mpolys[k].items(): j = ETuple((k,) + leftovers) D[i + j] = a @@ -12687,11 +12687,11 @@ cpdef list _dict_to_list(dict x, zero): if isinstance(n, tuple): # a mpoly dict n = n[0] v = [zero] * (n+1) - for i, z in x.iteritems(): + for i, z in x.items(): v[i[0]] = z else: v = [zero] * (n+1) - for i, z in x.iteritems(): + for i, z in x.items(): v[i] = z return v diff --git a/src/sage/rings/polynomial/polynomial_ring_homomorphism.pyx b/src/sage/rings/polynomial/polynomial_ring_homomorphism.pyx index 01aca9fed01..087e520dc23 100644 --- a/src/sage/rings/polynomial/polynomial_ring_homomorphism.pyx +++ b/src/sage/rings/polynomial/polynomial_ring_homomorphism.pyx @@ -58,7 +58,7 @@ cdef class PolynomialRingHomomorphism_from_base(RingHomomorphism_from_base): P = self.codomain() f = self.underlying_map() if P.is_sparse(): - return P({a: f(b) for a, b in x.monomial_coefficients().iteritems()}) + return P({a: f(b) for a, b in x.monomial_coefficients().items()}) else: return P([f(b) for b in x]) @@ -88,7 +88,7 @@ cdef class PolynomialRingHomomorphism_from_base(RingHomomorphism_from_base): P = self.codomain() f = self.underlying_map() if P.is_sparse(): - return P({a: f(b) for a, b in x.monomial_coefficients().iteritems()}, + return P({a: f(b) for a, b in x.monomial_coefficients().items()}, *args, **kwds) else: return P([f(b) for b in x], *args, **kwds) diff --git a/src/sage/rings/power_series_mpoly.pyx b/src/sage/rings/power_series_mpoly.pyx index 44c4be93423..741b0ad94e7 100644 --- a/src/sage/rings/power_series_mpoly.pyx +++ b/src/sage/rings/power_series_mpoly.pyx @@ -58,11 +58,11 @@ cdef class PowerSeries_mpoly(PowerSeries): d = {} if isinstance(B, MPolynomialRing_base): for i in range(len(v)): - for n, c in v[i].monomial_coefficients().iteritems(): + for n, c in v[i].monomial_coefficients().items(): d[tuple(n) + (i,)] = c else: for i in range(len(v)): - for n, c in v[i].monomial_coefficients().iteritems(): + for n, c in v[i].monomial_coefficients().items(): d[(n,i)] = c self.__f = S(d) diff --git a/src/sage/rings/power_series_ring_element.pyx b/src/sage/rings/power_series_ring_element.pyx index 725927ba5ad..b1ca6ea4ab1 100644 --- a/src/sage/rings/power_series_ring_element.pyx +++ b/src/sage/rings/power_series_ring_element.pyx @@ -1045,7 +1045,7 @@ cdef class PowerSeries(AlgebraElement): else: n = int(n) v = {} - for k, x in self.monomial_coefficients().iteritems(): + for k, x in self.monomial_coefficients().items(): if k >= n: v[k-n] = x return self._parent(v, self.prec()-n) diff --git a/src/sage/rings/tate_algebra_element.pyx b/src/sage/rings/tate_algebra_element.pyx index c2fd9cbfc8d..022b5d1c880 100644 --- a/src/sage/rings/tate_algebra_element.pyx +++ b/src/sage/rings/tate_algebra_element.pyx @@ -2371,7 +2371,9 @@ cdef class TateAlgebraElement(CommutativeAlgebraElement): return elt.lift_to_precision(prec) except PrecisionError: return elt.lift_to_precision() - ans._poly = PolyDict({ e: lift_without_error(c) for (e,c) in self._poly.__repn.iteritems() }, None) + ans._poly = PolyDict({e: lift_without_error(c) + for e, c in self._poly.__repn.items()}, + None) if prec is None: prec = self._parent.precision_cap() ans._prec = max(self._prec, prec) diff --git a/src/sage/symbolic/expression.pyx b/src/sage/symbolic/expression.pyx index 18d47b0da2c..ca523ee9a95 100644 --- a/src/sage/symbolic/expression.pyx +++ b/src/sage/symbolic/expression.pyx @@ -5846,12 +5846,12 @@ cdef class Expression(Expression_abc): if kwds: # Ensure that the keys are symbolic variables. - varkwds = {self._parent.var(k): v for k,v in kwds.iteritems()} + varkwds = {self._parent.var(k): v for k,v in kwds.items()} # Check for duplicate _dict_update_check_duplicate(sdict, varkwds) cdef GExMap smap - for k, v in sdict.iteritems(): + for k, v in sdict.items(): smap.insert(make_pair((self.coerce_in(k))._gobj, (self.coerce_in(v))._gobj)) res = self._gobj.subs_map(smap, 0) @@ -5999,7 +5999,7 @@ cdef class Expression(Expression_abc): if kwds: # Ensure that the keys are functions. - funkwds = {_find_func(k): v for k,v in kwds.iteritems()} + funkwds = {_find_func(k): v for k,v in kwds.items()} # Check for duplicate _dict_update_check_duplicate(sdict, funkwds)