Ticket #9944: trac9944_faster_and_cleaner_coercion.2.patch

File trac9944_faster_and_cleaner_coercion.2.patch, 120.5 KB (added by mraum, 8 years ago)

Rebase to 4.7.1.alpha0

  • sage/categories/category.py

    # HG changeset patch
    # User Simon King <simon.king@uni-jena.de>
    # Date 1305801904 -7200
    # Node ID d39a4e5e0267dc00fa94b2df86be784b40e1904e
    # Parent 216c066ba7528d60ef6439664addd703d9670480
    #9944: Clean up coercion of polynomial rings (dense versus sparse etc).
    Improve performance of _new_constant_poly by using specialised implementations.
    Additional minor fixes.
    
    diff -r 216c066ba752 sage/categories/category.py
    a b  
    989989            Category of hom sets in Category of sets
    990990
    991991        """
    992         if hasattr(self, "HomCategory"):
     992        try: #if hasattr(self, "HomCategory"):
    993993            return self.HomCategory(self)
    994         else:
     994        except AttributeError:
    995995            return Category.join((category.hom_category() for category in self.super_categories()))
    996996
    997997    def abstract_category(self):
  • sage/categories/pushout.py

    diff -r 216c066ba752 sage/categories/pushout.py
    a b  
    565565    """
    566566    Construction functor for univariate polynomial rings.
    567567
    568     EXAMPLE:
     568    EXAMPLE::
    569569
    570570        sage: P = ZZ['t'].construction()[0]
    571571        sage: P(GF(3))
     
    577577        sage: P(f)((x+y)*P(R).0)
    578578        (-x + y)*t
    579579
     580    By trac ticket #9944, the construction functor distinguishes sparse and
     581    dense polynomial rings. Before, the following example failed::
     582
     583        sage: R.<x> = PolynomialRing(GF(5), sparse=True)
     584        sage: F,B = R.construction()
     585        sage: F(B) is R
     586        True
     587        sage: S.<x> = PolynomialRing(ZZ)
     588        sage: R.has_coerce_map_from(S)
     589        False
     590        sage: S.has_coerce_map_from(R)
     591        False
     592        sage: S.0 + R.0
     593        2*x
     594        sage: (S.0 + R.0).parent()
     595        Univariate Polynomial Ring in x over Finite Field of size 5
     596        sage: (S.0 + R.0).parent().is_sparse()
     597        False
     598
    580599    """
    581600    rank = 9
    582601
    583     def __init__(self, var, multi_variate=False):
     602    def __init__(self, var, multi_variate=False, sparse=False):
    584603        """
    585604        TESTS::
    586605
     
    603622        Functor.__init__(self, Rings(), Rings())
    604623        self.var = var
    605624        self.multi_variate = multi_variate
     625        self.sparse = sparse
    606626
    607627    def _apply_functor(self, R):
    608628        """
     
    616636
    617637        """
    618638        from sage.rings.polynomial.polynomial_ring_constructor import PolynomialRing
    619         return PolynomialRing(R, self.var)
     639        return PolynomialRing(R, self.var, sparse=self.sparse)
    620640
    621641    def __cmp__(self, other):
    622642        """
     
    667687        if isinstance(other, MultiPolynomialFunctor):
    668688            return other.merge(self)
    669689        elif self == other:
    670             return self
     690            # i.e., they only differ in sparsity
     691            if not self.sparse:
     692                return self
     693            return other
    671694        else:
    672695            return None
    673696
     
    22442267            Q = R.quo(I,names=self.names)
    22452268        except IndexError: # That may happen!
    22462269            raise CoercionException, "Can not apply this quotient functor to %s"%R
    2247         if self.as_field and hasattr(Q, 'field'):
    2248             Q = Q.field()
     2270        if self.as_field:# and hasattr(Q, 'field'):
     2271            try:
     2272                Q = Q.field()
     2273            except AttributeError:
     2274                pass
    22492275        return Q
    22502276
    22512277    def __cmp__(self, other):
     
    26762702            sage: F(QQ)       # indirect doctest
    26772703            Algebraic Field
    26782704        """
    2679         if hasattr(R,'construction'):
     2705        try:
    26802706            c = R.construction()
    26812707            if c is not None and c[0]==self:
    26822708                return R
     2709        except AttributeError:
     2710            pass
    26832711        return R.algebraic_closure()
    26842712
    26852713    def merge(self, other):
  • sage/modular/cusps.py

    diff -r 216c066ba752 sage/modular/cusps.py
    a b  
    3333from sage.structure.element import Element, is_InfinityElement
    3434from sage.modular.modsym.p1list import lift_to_sl2z_llong
    3535from sage.matrix.all import is_Matrix
     36from sage.misc.cachefunc import cached_method
    3637
    3738class Cusps_class(ParentWithBase):
    3839    """
     
    148149        else:
    149150            return self._coerce_try(x, QQ)
    150151
     152    @cached_method
     153    def zero_element(self):
     154        """
     155        Return the zero cusp.
     156
     157        NOTE:
     158
     159        The existence of this method is assumed by some
     160        parts of Sage's coercion model.
     161
     162        EXAMPLE::
     163
     164            sage: Cusps.zero_element()
     165            0
     166
     167        """
     168        return Cusp(0, parent=self)
     169
    151170Cusps = Cusps_class()
    152171   
    153172
  • sage/modular/cusps_nf.py

    diff -r 216c066ba752 sage/modular/cusps_nf.py
    a b  
    8787from sage.rings.integer_ring import IntegerRing
    8888from sage.structure.parent_base import ParentWithBase
    8989from sage.structure.element import Element, is_InfinityElement
     90from sage.misc.cachefunc import cached_method
    9091
    9192_nfcusps_cache = {}
    9293
     
    331332
    332333    def __call__(self, x):
    333334        """
    334         Coerce x into the set of cusps of a number field.
     335        Convert x into the set of cusps of a number field.
    335336
    336337        EXAMPLES::
    337338
     
    353354        """
    354355        return NFCusp(self.number_field(), x, parent=self)
    355356
     357    @cached_method
     358    def zero_element(self):
     359        """
     360        Return the zero cusp.
     361
     362        NOTE:
     363
     364        This method just exists to make some general algorithms work.
     365        It is not intended that the returned cusp is an additive
     366        neutral element.
     367
     368        EXAMPLE::
     369
     370             sage: k.<a> = NumberField(x^2 + 5)
     371             sage: kCusps = NFCusps(k)
     372             sage: kCusps.zero_element()
     373             Cusp [0: 1] of Number Field in a with defining polynomial x^2 + 5
     374
     375        """
     376        return self(0)
     377
    356378    def number_field(self):
    357379        """
    358380        Return the number field that this set of cusps is attached to.
  • sage/modular/overconvergent/genus0.py

    diff -r 216c066ba752 sage/modular/overconvergent/genus0.py
    a b  
    176176
    177177from sage.matrix.all        import matrix, MatrixSpace, diagonal_matrix
    178178from sage.misc.misc         import verbose
     179from sage.misc.cachefunc    import cached_method
    179180from sage.modular.all       import (DirichletGroup, trivial_character, EtaProduct,
    180181                                    j_invariant_qexp, hecke_operator_on_qexp)
    181182from sage.modular.arithgroup.all import (Gamma1, is_Gamma0, is_Gamma1)
     
    621622
    622623    #####################################
    623624    # Element construction and coercion #
     625    #   (unfortunately not using        #
     626    #    the new coercion model)        #
    624627    #####################################
    625628
    626629    def __call__(self, input):
     
    721724
    722725        else:
    723726            raise TypeError, "Don't know how to create an overconvergent modular form from %s" % input
    724        
     727
     728    @cached_method
     729    def zero_element(self):
     730        """
     731        Return the zero of this space.
     732
     733        EXAMPLE::
     734
     735            sage: K.<w> = Qp(13).extension(x^2-13); M = OverconvergentModularForms(13, 20, radius=1/2, base_ring=K)
     736            sage: K.zero_element()
     737            0
     738        """
     739        return self(0)
     740
    725741    def _coerce_from_ocmf(self, f):
    726742        r"""
    727743        Try to convert the overconvergent modular form `f` into an element of self. An error will be raised if this is
  • sage/modular/overconvergent/weightspace.py

    diff -r 216c066ba752 sage/modular/overconvergent/weightspace.py
    a b  
    6969from sage.misc.misc import sxrange
    7070from sage.rings.padics.padic_generic_element import pAdicGenericElement
    7171from sage.misc.misc import verbose
     72from sage.misc.cachefunc import cached_method
    7273import weakref
    7374
    7475_wscache = {}
     
    198199        else:
    199200            return ArbitraryWeight(self, arg1, arg2)
    200201
     202    @cached_method
     203    def zero_element(self):
     204        """
     205        Return the zero of this weight space.
     206
     207        EXAMPLES::
     208
     209            sage: W = pAdicWeightSpace(17)
     210            sage: W.zero_element()
     211            0
     212        """
     213        return self(0)
     214
    201215    def prime(self):
    202216        r"""
    203217        Return the prime `p` such that this is a `p`-adic weight space.
  • sage/modules/free_module_homspace.py

    diff -r 216c066ba752 sage/modules/free_module_homspace.py
    a b  
    7474import sage.modules.free_module_morphism
    7575import sage.matrix.all as matrix
    7676import free_module_morphism
     77from inspect import isfunction
    7778
    7879from matrix_morphism import MatrixMorphism
    7980
     
    9596    def __call__(self, A, check=True):
    9697        """
    9798        INPUT:
    98             A -- either a matrix or a list/tuple of images of generators
    99             check -- bool (default: True)
     99
     100        - A -- either a matrix or a list/tuple of images of generators,
     101          or a function returning elements of the codomain for elements
     102          of the domain.
     103        - check -- bool (default: True)
    100104
    101105        If A is a matrix, then it is the matrix of this linear
    102106        transformation, with respect to the basis for the domain and
     
    104108        identity morphism.
    105109
    106110        EXAMPLES::
     111
    107112            sage: V = (QQ^3).span_of_basis([[1,1,0],[1,0,2]])
    108113            sage: H = V.Hom(V); H
    109114            Set of Morphisms from ...
     
    119124            True
    120125            sage: phi(V.0) == V.1
    121126            True
     127
     128        The following tests against a bug that was fixed in trac
     129        ticket #9944. The method ``zero()`` calls this hom space with
     130        a function, not with a matrix, and that case had previously
     131        not been taken care of::
     132
     133            sage: V = span([[1/2,1,1],[3/2,2,1],[0,0,1]],ZZ)
     134            sage: V.Hom(V).zero()   # indirect doctest
     135            Free module morphism defined by the matrix
     136            [0 0 0]
     137            [0 0 0]
     138            [0 0 0]
     139            Domain: Free module of degree 3 and rank 3 over Integer Ring
     140            Echelon ...
     141            Codomain: Free module of degree 3 and rank 3 over Integer Ring
     142            Echelon ...
     143
    122144        """
    123145        if not matrix.is_Matrix(A):
    124146            # Compute the matrix of the morphism that sends the
    125147            # generators of the domain to the elements of A.
    126148            C = self.codomain()
    127             try:
    128                 v = [C(a) for a in A]
    129                 A = matrix.matrix([C.coordinates(a) for a in v])               
    130             except TypeError:
    131                 pass
     149            if isfunction(A):
     150                try:
     151                    v = [C(A(g)) for g in self.domain().gens()]
     152                    A = matrix.matrix([C.coordinates(a) for a in v])
     153                except TypeError, msg:
     154                    # Let us hope that FreeModuleMorphism knows to handle that case
     155                    pass
     156            else:
     157                try:
     158                    v = [C(a) for a in A]
     159                    A = matrix.matrix([C.coordinates(a) for a in v])
     160                except TypeError, msg:
     161                    # Let us hope that FreeModuleMorphism knows to handle that case
     162                    pass
    132163        return free_module_morphism.FreeModuleMorphism(self, A)
    133164
    134165    def _matrix_space(self):
     
    137168        the homomorphisms in this free module homspace.
    138169       
    139170        OUTPUT:
    140             - matrix space
     171
     172        - matrix space
    141173
    142174        EXAMPLES::
    143175       
     
    158190        Return a basis for this space of free module homomorphisms.
    159191
    160192        OUTPUT:
    161             - tuple
     193
     194        - tuple
    162195
    163196        EXAMPLES::
    164197
  • sage/rings/finite_rings/element_givaro.pyx

    diff -r 216c066ba752 sage/rings/finite_rings/element_givaro.pyx
    a b  
    44Sage includes the Givaro finite field library, for highly optimized
    55arithmetic in finite fields.
    66
    7 NOTES: The arithmetic is performed by the Givaro C++ library which
    8 uses Zech logs internally to represent finite field elements. This
     7NOTES:
     8
     9The arithmetic is performed by the Givaro C++ library which uses Zech
     10logs internally to represent finite field elements. This
    911implementation is the default finite extension field implementation in
    1012Sage for the cardinality $< 2^{16}$, as it is vastly faster than the
    1113PARI implementation which uses polynomials to represent finite field
    1214elements. Some functionality in this class however is implemented
    1315using the PARI implementation.
    1416
    15 EXAMPLES:
     17EXAMPLES::
     18
    1619    sage: k = GF(5); type(k)
    1720    <class 'sage.rings.finite_rings.finite_field_prime_modn.FiniteField_prime_modn_with_category'>
    1821    sage: k = GF(5^2,'c'); type(k)
     
    3134    <class 'sage.rings.finite_rings.finite_field_givaro.FiniteField_givaro_with_category'>
    3235
    3336AUTHORS:
    34      -- Martin Albrecht <malb@informatik.uni-bremen.de> (2006-06-05)
    35      -- William Stein (2006-12-07): editing, lots of docs, etc.
    36      -- Robert Bradshaw (2007-05-23): is_square/sqrt, pow.
     37
     38- Martin Albrecht <malb@informatik.uni-bremen.de> (2006-06-05)
     39- William Stein (2006-12-07): editing, lots of docs, etc.
     40- Robert Bradshaw (2007-05-23): is_square/sqrt, pow.
     41
    3742"""
    3843
    3944
     
    410415                e = e % self.characteristic()
    411416                res = self.objectptr.initi(res,int(e))
    412417
     418        elif e is None:
     419            e_int = 0
     420            res = self.objectptr.initi(res,e_int)
     421
    413422        elif PY_TYPE_CHECK(e, float):
    414423            res = self.objectptr.initd(res,e)
    415424           
  • sage/rings/finite_rings/finite_field_givaro.py

    diff -r 216c066ba752 sage/rings/finite_rings/finite_field_givaro.py
    a b  
    203203        Coerces several data types to self.
    204204
    205205        INPUT:
    206             e -- data to coerce
     206       
     207        e -- data to coerce
    207208
    208209        EXAMPLES:
    209210
    210             FiniteField_givaroElement are accepted where the parent
    211             is either self, equals self or is the prime subfield
     211        FiniteField_givaroElement are accepted where the parent
     212        is either self, equals self or is the prime subfield::
    212213       
    213214            sage: k = GF(2**8, 'a')
    214215            sage: k.gen() == k(k.gen())
    215216            True
    216217
    217 
    218             Floats, ints, longs, Integer are interpreted modulo characteristic
     218        Floats, ints, longs, Integer are interpreted modulo characteristic::
    219219           
    220220            sage: k(2)
    221221            0
     
    224224            sage: k(float(2.0))
    225225            0
    226226           
    227             Rational are interpreted as
    228                              self(numerator)/self(denominator).
    229             Both may not be >= self.characteristic().
     227        Rational are interpreted as self(numerator)/self(denominator).
     228        Both may not be >= self.characteristic().
     229        ::
    230230
    231231            sage: k = GF(3**8, 'a')
    232232            sage: k(1/2) == k(1)/k(2)
    233233            True
    234234
    235             Free module elements over self.prime_subfield() are interpreted 'little endian'
     235        Free module elements over self.prime_subfield() are interpreted 'little endian'::
    236236           
    237237            sage: k = GF(2**8, 'a')
    238238            sage: e = k.vector_space().gen(1); e
     
    240240            sage: k(e)
    241241            a
    242242
    243             Strings are evaluated as polynomial representation of elements in self
     243        'None' yields zero::
     244
     245            sage: k(None)
     246            0
     247
     248        Strings are evaluated as polynomial representation of elements in self::
    244249
    245250            sage: k('a^2+1')
    246251            a^2 + 1
    247252
    248253        Univariate polynomials coerce into finite fields by evaluating
    249         the polynomial at the field's generator:
     254        the polynomial at the field's generator::
     255
    250256            sage: from sage.rings.finite_rings.finite_field_givaro import FiniteField_givaro
    251257            sage: R.<x> = QQ[]
    252258            sage: k, a = FiniteField_givaro(5^2, 'a').objgen()
     
    269275            q^2 + 2*q + 4
    270276
    271277
    272         Multivariate polynomials only coerce if constant:
     278        Multivariate polynomials only coerce if constant::
     279
    273280            sage: R = k['x,y,z']; R
    274281            Multivariate Polynomial Ring in x, y, z over Finite Field in a of size 5^2
    275282            sage: k(R(2))
     
    281288            ZeroDivisionError: division by zero in finite field.
    282289
    283290       
    284             PARI elements are interpreted as finite field elements; this PARI flexibility
    285             is (absurdly!) liberal:
     291        PARI elements are interpreted as finite field elements; this PARI flexibility
     292        is (absurdly!) liberal::
    286293
    287294            sage: k = GF(2**8, 'a')
    288295            sage: k(pari('Mod(1,2)'))
     
    292299            sage: k(pari('Mod(1,3)*a^20'))
    293300            a^7 + a^5 + a^4 + a^2
    294301
    295             GAP elements need to be finite field elements:
     302        GAP elements need to be finite field elements::
    296303
    297304            sage: from sage.rings.finite_rings.finite_field_givaro import FiniteField_givaro
    298305            sage: x = gap('Z(13)')
  • sage/rings/polynomial/infinite_polynomial_element.py

    diff -r 216c066ba752 sage/rings/polynomial/infinite_polynomial_element.py
    a b  
    565565            Infinite polynomial ring in x over Rational Field
    566566
    567567        """
    568         if x._p not in self.base_ring():
     568#        if x._p not in self.base_ring():
     569        try:
     570            p = self.base_ring()(x._p)
     571        except TypeError:
    569572            raise NotImplementedError, "Fraction Fields of Infinite Polynomial Rings are not implemented"
    570         divisor = self.base_ring().one_element()/x._p # use induction...
     573        divisor = self.base_ring().one_element()/p # use induction...
    571574        OUTP = self.parent().tensor_with_ring(divisor.base_ring())
    572575        return OUTP(self)*OUTP(divisor)
    573576
  • sage/rings/polynomial/laurent_polynomial_ring.py

    diff -r 216c066ba752 sage/rings/polynomial/laurent_polynomial_ring.py
    a b  
    273273        # LaurentPolynomialRing(base_ring, names (list or tuple), order='degrevlex'):       
    274274        names = arg1
    275275        n = len(names)
    276         R = _multi_variate(base_ring, names, n, sparse, order)       
     276        R = _multi_variate(base_ring, names, n, sparse, order)
    277277
    278278    if arg1 is None and arg2 is None:
    279279        raise TypeError, "you *must* specify the indeterminates (as not None)."
     
    347347            prepend_string += 'k'
    348348        else:
    349349            break
    350     R = _multi_variate_poly(base_ring, names, 1, sparse, 'degrevlex')
     350    R = _multi_variate_poly(base_ring, names, 1, sparse, 'degrevlex', None)
    351351    P = LaurentPolynomialRing_mpair(R, prepend_string, names)
    352352    _save_in_cache(key, P)
    353353    return P
     
    386386                break
    387387        else:
    388388            break
    389     R = _multi_variate_poly(base_ring, names, n, sparse, order)
     389    R = _multi_variate_poly(base_ring, names, n, sparse, order, None)
    390390    P = LaurentPolynomialRing_mpair(R, prepend_string, names)
    391391    _save_in_cache(key, P)
    392392    return P
     
    542542            Composite map:
    543543              From: Rational Field
    544544              To:   Multivariate Laurent Polynomial Ring in x, y over Rational Field
    545               Defn:   Call morphism:
     545              Defn:   Polynomial base injection morphism:
    546546                      From: Rational Field
    547547                      To:   Multivariate Polynomial Ring in x, y over Rational Field
    548548                    then
  • sage/rings/polynomial/multi_polynomial_element.py

    diff -r 216c066ba752 sage/rings/polynomial/multi_polynomial_element.py
    a b  
    335335            x = polydict.PolyDict(x, parent.base_ring()(0), remove_zero=True)
    336336        MPolynomial_element.__init__(self, parent, x)
    337337
     338    def _new_constant_poly(self, x, P):
     339        """
     340        Quickly create a new constant polynomial with value x in parent P.
     341
     342        ASSUMPTION:
     343
     344        x must be an element of the base ring of P. That assumption is
     345        not verified.
     346
     347        EXAMPLE::
     348
     349            sage: R.<x,y> = QQ['t'][]
     350            sage: x._new_constant_poly(R.base_ring()(2),R)
     351            2
     352
     353        """
     354        return MPolynomial_polydict(P, {P._zero_tuple:x})
     355
    338356    def __neg__(self):
    339357        """
    340358        EXAMPLES::
  • sage/rings/polynomial/multi_polynomial_libsingular.pxd

    diff -r 216c066ba752 sage/rings/polynomial/multi_polynomial_libsingular.pxd
    a b  
    44from sage.rings.polynomial.multi_polynomial_ring_generic cimport MPolynomialRing_generic
    55from sage.structure.parent cimport Parent
    66
     7cdef class MPolynomialRing_libsingular
     8
    79cdef class MPolynomial_libsingular(MPolynomial):
    810    cdef poly *_poly
    911    cpdef _repr_short_(self)
    1012    cpdef is_constant(self)
    1113    cpdef _homogenize(self, int var)
     14    cpdef MPolynomial_libsingular _new_constant_poly(self, x, MPolynomialRing_libsingular P)
    1215
    1316cdef class MPolynomialRing_libsingular(MPolynomialRing_generic):
    1417    cdef object __singular
    1518    cdef object __macaulay2
    1619    cdef object __m2_set_ring_cache
    1720    cdef object __minpoly
     21    cdef poly *_one_element_poly
    1822    cdef ring *_ring
    1923    cdef int _cmp_c_impl(left, Parent right) except -2
    2024
  • sage/rings/polynomial/multi_polynomial_libsingular.pyx

    diff -r 216c066ba752 sage/rings/polynomial/multi_polynomial_libsingular.pyx
    a b  
    299299
    300300        TEST:
    301301
    302         Make sure that a faster conversion map from the base ring is used;
     302        Make sure that a faster coercion map from the base ring is used;
    303303        see trac ticket #9944::
    304304
    305305            sage: R.<x,y> = PolynomialRing(ZZ)
    306             sage: R.convert_map_from(R.base_ring())
     306            sage: R.coerce_map_from(R.base_ring())
    307307            Polynomial base injection morphism:
    308308              From: Integer Ring
    309309              To:   Multivariate Polynomial Ring in x, y over Integer Ring
     
    315315        self.__ngens = n
    316316        self._ring = singular_ring_new(base_ring, n, self._names, order)
    317317        self._one_element = <MPolynomial_libsingular>new_MP(self,p_ISet(1, self._ring))
     318        self._one_element_poly = (<MPolynomial_libsingular>self._one_element)._poly
    318319        self._zero_element = <MPolynomial_libsingular>new_MP(self,NULL)
    319320        # This polynomial ring should belong to Algebras(base_ring).
    320321        # Algebras(...).parent_class, which was called from MPolynomialRing_generic.__init__,
     
    324325        # wipe the memory and construct the conversion from scratch.
    325326        from sage.rings.polynomial.polynomial_element import PolynomialBaseringInjection
    326327        base_inject = PolynomialBaseringInjection(base_ring, self)
    327         self.register_conversion(base_inject)
     328        self.register_coercion(base_inject)
    328329
    329330    def __dealloc__(self):
    330331        r"""
     
    773774
    774775            return new_MP(self, _p)
    775776
    776         if hasattr(element,'_polynomial_'):
     777        try: #if hasattr(element,'_polynomial_'):
    777778            # SymbolicVariable
    778779            return element._polynomial_(self)
     780        except AttributeError:
     781            pass
    779782
    780783        if is_Macaulay2Element(element):
    781784            return self(element.external_string())
     
    17201723        if self._parent is not <ParentWithBase>None and (<MPolynomialRing_libsingular>self._parent)._ring != NULL and self._poly != NULL:
    17211724            p_Delete(&self._poly, (<MPolynomialRing_libsingular>self._parent)._ring)
    17221725
     1726    cpdef MPolynomial_libsingular _new_constant_poly(self, x, MPolynomialRing_libsingular P):
     1727        r"""
     1728        Quickly create a new constant polynomial with value x in the parent P.
     1729
     1730        ASSUMPTION:
     1731
     1732        The value x must be an element of the base ring. That assumption is
     1733        not verified.
     1734
     1735        EXAMPLE::
     1736
     1737            sage: R.<x,y> = QQ[]
     1738            sage: x._new_constant_poly(2/1,R)
     1739            2
     1740
     1741        """
     1742        if not x:
     1743            return <MPolynomial_libsingular>new_MP(P, NULL)
     1744        cdef ring *_ring = P._ring
     1745        cdef poly *_p
     1746        singular_polynomial_rmul(&_p, P._one_element_poly, x, _ring)
     1747        return new_MP(P,_p)
     1748
    17231749    def __call__(self, *x, **kwds):
    17241750        """
    17251751        Evaluate this multi-variate polynomial at ``x``, where ``x``
  • sage/rings/polynomial/multi_polynomial_ring.py

    diff -r 216c066ba752 sage/rings/polynomial/multi_polynomial_ring.py
    a b  
    159159        if n:
    160160            from sage.rings.polynomial.polynomial_element import PolynomialBaseringInjection
    161161            base_inject = PolynomialBaseringInjection(base_ring, self)
    162             self.register_conversion(base_inject)
     162            self.register_coercion(base_inject)
    163163
    164164    def _monomial_order_function(self):
    165165        return self.__monomial_order_function
  • sage/rings/polynomial/padics/polynomial_padic_capped_relative_dense.py

    diff -r 216c066ba752 sage/rings/polynomial/padics/polynomial_padic_capped_relative_dense.py
    a b  
    3737            (1 + O(13^7))*t + (2 + O(13^7))
    3838        """
    3939        Polynomial.__init__(self, parent, is_gen=is_gen)
     40        parentbr = parent.base_ring()
    4041        from sage.rings.polynomial.polynomial_ring_constructor import PolynomialRing
    4142        if construct:
    4243            (self._poly, self._valbase, self._relprecs, self._normalized, self._valaddeds, self._list) = x #the last two of these may be None
     
    4546            self._poly = PolynomialRing(ZZ, parent.variable_name()).gen()
    4647            self._valbase = 0
    4748            self._valaddeds = [infinity, 0]
    48             self._relprecs = [infinity, parent.base_ring().precision_cap()]
     49            self._relprecs = [infinity, parentbr.precision_cap()]
    4950            self._normalized = True
    5051            self._list = None
    5152            return
     
    7576            elif x.base_ring() is ZZ:
    7677                self._poly = x
    7778                self._valbase = Integer(0)
    78                 p = parent.base_ring().prime()
    79                 self._relprecs = [c.valuation(p) + parent.base_ring().precision_cap() for c in x.list()]
     79                p = parentbr.prime()
     80                self._relprecs = [c.valuation(p) + parentbr.precision_cap() for c in x.list()]
    8081                self._comp_valaddeds()
    8182                self._normalized = len(self._valaddeds) == 0 or (min(self._valaddeds) == 0)
    8283                self._list = None
     
    8485                    self._adjust_prec_info(absprec, relprec)
    8586                return
    8687            else:
    87                 x = [parent.base_ring()(a) for a in x.list()]
     88                x = [parentbr(a) for a in x.list()]
    8889                check = False
    8990        elif isinstance(x, dict):
    90             zero = parent.base_ring()(0)
     91            zero = parentbr.zero_element()
    9192            n = max(x.keys())
    9293            v = [zero for _ in xrange(n + 1)]
    9394            for i, z in x.iteritems():
    9495                v[i] = z
    9596            x = v
    9697        elif isinstance(x, pari_gen):
    97             x = [parent.base_ring()(w) for w in x.Vecrev()]
     98            x = [parentbr(w) for w in x.Vecrev()]
    9899            check = False
    99100        #The default behavior if we haven't already figured out what the type is is to assume it coerces into the base_ring as a constant polynomial
    100101        elif not isinstance(x, list):
    101102            x = [x] # constant polynomial
    102        
     103
     104        # In contrast to other polynomials, the zero element is not distinguished
     105        # by having its list empty. Instead, it has list [0]
     106        if not x:
     107            x = [parentbr.zero_element()]
    103108        if check:
    104             x = [parent.base_ring()(z) for z in x]
     109            x = [parentbr(z) for z in x]
    105110
    106111        # Remove this -- for p-adics this is terrible, since it kills any non exact zero.
    107112        #if len(x) == 1 and not x[0]:
     
    125130            if not absprec is infinity or not relprec is infinity:
    126131                self._adjust_prec_info(absprec, relprec)
    127132
     133    def _new_constant_poly(self, a, P):
     134        """
     135        Create a new constant polynomial in parent P with value a.
     136
     137        ASSUMPTION:
     138
     139        The value a must be an element of the base ring of P. That
     140        assumption is not verified.
     141
     142        EXAMPLE::
     143
     144            sage: R.<t> = Zp(5)[]
     145            sage: t._new_constant_poly(O(5),R)
     146            (O(5))
     147
     148        """
     149        return self.__class__(P,[a], check=False)
     150
    128151    def _normalize(self):
    129152        # Currently slow: need to optimize
    130153        if not self._normalized:
  • sage/rings/polynomial/polynomial_compiled.pyx

    diff -r 216c066ba752 sage/rings/polynomial/polynomial_compiled.pyx
    a b  
    114114    def __repr__(self):
    115115        return "CompiledPolynomialFunction(%s)"%(self._dag)
    116116
     117    def __call__(self, x):
     118        return self.eval(x)
     119
    117120    cdef object eval(CompiledPolynomialFunction self, object x):
    118121        cdef object temp
    119122        try:
  • sage/rings/polynomial/polynomial_element.pxd

    diff -r 216c066ba752 sage/rings/polynomial/polynomial_element.pxd
    a b  
    55
    66from sage.structure.element import Element, CommutativeAlgebraElement
    77from sage.structure.element cimport Element, CommutativeAlgebraElement, ModuleElement
     8from sage.structure.parent cimport Parent
    89from polynomial_compiled import CompiledPolynomialFunction
    910from polynomial_compiled cimport CompiledPolynomialFunction
    1011
     
    1516    cpdef Polynomial truncate(self, long n)
    1617    cdef long _hash_c(self)
    1718    cpdef constant_coefficient(self)
    18     cpdef Polynomial _new_constant_poly(self, a)
     19    cpdef Polynomial _new_constant_poly(self, a, Parent P)
    1920
    2021    # UNSAFE, only call from an inplace operator
    2122    # may return a new element if not possible to modify inplace
    2223    cdef _inplace_truncate(self, long n)
    2324
    2425cdef class Polynomial_generic_dense(Polynomial):
    25     cdef Polynomial_generic_dense _new_c(self, list coeffs)
     26    cdef Polynomial_generic_dense _new_c(self, list coeffs, Parent P)
    2627    cdef list __coeffs
    2728    cdef void __normalize(self)
    2829#    cdef _dict_to_list(self, x, zero)
    29    
     30
     31cpdef Polynomial_generic_dense _new_constant_dense_poly(list coeffs, Parent P, sample)
     32
    3033#cdef class Polynomial_generic_sparse(Polynomial):
    3134#    cdef object __coeffs # a python dict (for now)
  • sage/rings/polynomial/polynomial_element.pyx

    diff -r 216c066ba752 sage/rings/polynomial/polynomial_element.pyx
    a b  
    8585
    8686from sage.rings.integer cimport Integer
    8787from sage.rings.ideal import is_Ideal
     88from sage.rings.polynomial.polynomial_ring import is_PolynomialRing
    8889
    8990from sage.categories.map cimport Map
    9091from sage.categories.morphism cimport Morphism
     
    159160    import sage.rings.complex_interval_field
    160161    is_ComplexIntervalField = sage.rings.complex_interval_field.is_ComplexIntervalField
    161162
     163
    162164cdef class Polynomial(CommutativeAlgebraElement):
    163165    """
    164166    A polynomial.
     
    300302        #         that could be in derived class.
    301303        #         Note that we are guaranteed that right is in the base ring, so this could be fast.
    302304        if left == 0:
    303             return self.parent()(0)
     305            return self.parent().zero_element()
    304306        return self.parent()(left) * self
    305307   
    306308    cpdef ModuleElement _rmul_(self, RingElement right):
     
    320322        #         that could be in derived class.
    321323        #         Note that we are guaranteed that right is in the base ring, so this could be fast.
    322324        if right == 0:
    323             return self.parent()(0)
     325            return self.parent().zero_element()
    324326        return self * self.parent()(right)
    325327
    326328    def subs(self, *x, **kwds):
     
    546548        """
    547549        cdef long i, d = self.degree()
    548550
    549         if len(kwds) >= 1:
     551        if kwds:
    550552            P = self.parent()
    551553            name = P.variable_name()
    552554            if kwds.has_key(name):
     
    587589        result = self[d]
    588590        if len(x) > 1:
    589591            other_args = x[1:]
    590             if hasattr(result, '__call__'):
     592            try: #if hasattr(result, '__call__'):
    591593                result = result(other_args)
    592             else:
     594            except TypeError: #else:
    593595                raise TypeError, "Wrong number of arguments"
    594596
    595597        if d == -1:
    596598            try:
     599                return a.parent().zero_element()
     600            except AttributeError:
     601                pass
     602            try: # for things like the interface to the PARI C library
    597603                return a.parent()(0)
    598604            except AttributeError:
    599605                return result
    600606
    601607        if d == 0:
    602608            try:
     609                return a.parent().one_element() * result
     610            except AttributeError:
     611                pass
     612            try: # for things like the interface to the PARI C library
    603613                return a.parent()(1) * result
    604614            except AttributeError:
    605615                return result
     
    961971            sage: ~f
    962972            1/(x - 90283)
    963973        """
    964         return self.parent()(1)/self
     974        return self.parent().one_element()/self
    965975
    966976    def inverse_of_unit(self):
    967977        """
     
    10761086            for i in range(n+1):
    10771087                for j in range(n-1):
    10781088                    M[i+j, j+n] = m[i]
    1079             v = vector(R, [R(1)] + [R(0)]*(2*n-2)) # the constant polynomial 1
     1089            v = vector(R, [R.one_element()] + [R.zero_element()]*(2*n-2)) # the constant polynomial 1
    10801090            if M.is_invertible():
    10811091                x = M.solve_right(v) # there has to be a better way to solve
    10821092                return a.parent()(list(x)[0:n])
     
    11221132            (t^4 + O(t^5))*s^4 + (2*t^3 + O(t^4))*s^3 + (3*t^2 + O(t^3))*s^2 + (2*t + O(t^2))*s + 1           
    11231133        """
    11241134        if right == 0 or self == 0:
    1125             return self._parent(0)
     1135            return self._parent.zero_element()
    11261136
    11271137        if self._parent.is_exact():
    11281138            return self._mul_karatsuba(right)
     
    14111421            P = self.parent()
    14121422            R = P.base_ring()
    14131423            if P.is_sparse():
    1414                 v = {right:R(1)}
     1424                v = {right:R.one_element()}
    14151425            else:
    1416                 v = [R(0)]*right + [R(1)]
     1426                v = [R.zero_element()]*right + [R.one_element()]
    14171427            r = self.parent()(v, check=False)
    14181428        else:
    14191429            r = generic_power(self, right)
     
    17331743        x = self.list()
    17341744        cdef Py_ssize_t i, j
    17351745        cdef Py_ssize_t d = len(x)-1
    1736         zero = self._parent.base_ring()(0)
     1746        zero = self._parent.base_ring().zero_element()
    17371747        two = self._parent.base_ring()(2)
    17381748        coeffs = [zero] * (2 * d + 1)
    17391749        for i from 0 <= i <= d:
     
    23262336            return self
    23272337        cdef Py_ssize_t n, degree = self.degree()
    23282338        if degree == 0:
    2329             return self.parent()(0)
     2339            return self.parent().zero_element()
    23302340        coeffs = self.list()
    23312341        return self._parent([n*coeffs[n] for n from 1 <= n <= degree])
    23322342   
     
    23662376        """
    23672377        cdef Py_ssize_t n, degree = self.degree()
    23682378        if degree < 0:
    2369             return self.parent()(0)
     2379            return self.parent().zero_element()
    23702380
    23712381        coeffs = self.list()
    23722382        v = [0, coeffs[0]] + [coeffs[n]/(n+1) for n from 1 <= n <= degree]
     
    29562966        else:
    29572967            # Otherwise we have to adjust for
    29582968            # the content ignored by PARI.
    2959             content_fix = R.base_ring()(1)
     2969            content_fix = R.base_ring().one_element()
    29602970            for f, e in F:
    29612971                if not f.is_monic():
    29622972                    content_fix *= f.leading_coefficient()**e
    29632973            unit //= content_fix
    29642974            if not unit.is_unit():
    29652975                F.append((R(unit), ZZ(1)))
    2966                 unit = R.base_ring()(1)
     2976                unit = R.base_ring().one_element()
    29672977       
    29682978        if not n is None:
    29692979            pari.set_real_precision(n)  # restore precision
     
    34363446        """
    34373447        return self[0]
    34383448
    3439     cpdef Polynomial _new_constant_poly(self, a):
    3440         """
    3441         Create a new constant polynomial from a, which MUST be an element of the base ring.
    3442         """
    3443         return self._parent._element_constructor(a)
     3449    cpdef Polynomial _new_constant_poly(self, a, Parent P):
     3450        """
     3451        Create a new constant polynomial from a in P, which MUST be an
     3452        element of the base ring of P (this is not checked).
     3453
     3454        EXAMPLE::
     3455
     3456            sage: R.<w> = PolynomialRing(GF(9,'a'), sparse=True)
     3457            sage: a = w._new_constant_poly(0, R); a
     3458            0
     3459            sage: a.coeffs()
     3460            []
     3461
     3462        """
     3463        if a:
     3464            return self.__class__(P,[a], check=False) #P._element_constructor(a, check=False)
     3465        return self.__class__(P,[], check=False)
    34443466
    34453467    def is_monic(self):
    34463468        """
     
    37443766        if n < 0:
    37453767            raise ValueError, "n must be at least 0"
    37463768        if len(v) < n:
    3747             z = self._parent.base_ring()(0)
     3769            z = self._parent.base_ring().zero_element()
    37483770            return v + [z]*(n - len(v))
    37493771        else:
    37503772            return v[:int(n)]
     
    51735195        """
    51745196        if other.is_zero():
    51755197            R = self.parent()
    5176             return self, R(1), R(0)
     5198            return self, R.one_element(), R.zero_element()
    51775199        # Algorithm 3.2.2 of Cohen, GTM 138
    51785200        R = self.parent()
    51795201        A = self
    51805202        B = other
    5181         U = R(1)
     5203        U = R.one_element()
    51825204        G = A
    5183         V1 = R(0)
     5205        V1 = R.zero_element()
    51845206        V3 = B
    51855207        while not V3.is_zero():
    51865208            Q, R = G.quo_rem(V3)
     
    53055327        if n == 0 or self.degree() < 0:
    53065328            return self   # safe because immutable.
    53075329        if n > 0:
    5308             output = [self.base_ring()(0)] * n
     5330            output = [self.base_ring().zero_element()] * n
    53095331            output.extend(self.coeffs())
    53105332            return self._parent(output, check=False)
    53115333        if n < 0:
     
    53275349       
    53285350        EXAMPLES::
    53295351       
    5330             sage: R.<x> = ZZ[]; S.<y> = R[]
     5352            sage: R.<x> = ZZ[]; S.<y> = PolynomialRing(R, sparse=True)
    53315353            sage: f = y^3 + x*y -3*x; f
    53325354            y^3 + x*y - 3*x
    53335355            sage: f.truncate(2)
     
    53375359            sage: f.truncate(0)
    53385360            0
    53395361        """
    5340         return <Polynomial>self._parent(self[:n], check=False)
     5362        # We must not have check=False, since 0 must not have __coeffs = [0].
     5363        return <Polynomial>self._parent(self[:n])#, check=False)
    53415364
    53425365    cdef _inplace_truncate(self, long prec):
    53435366        return self.truncate(prec)
     
    55455568    t0 = bd
    55465569    return _karatsuba_sum(t0,_karatsuba_sum(t1,t2))
    55475570
     5571cpdef Polynomial_generic_dense _new_constant_dense_poly(list coeffs, Parent P, sample):
     5572    cdef Polynomial_generic_dense f = <Polynomial_generic_dense>PY_NEW_SAME_TYPE(sample)
     5573    f._parent = P
     5574    f.__coeffs = coeffs
     5575    return f
     5576
     5577
    55485578cdef class Polynomial_generic_dense(Polynomial):
    55495579    """
    55505580    A generic dense polynomial.
     
    55605590    """
    55615591    def __init__(self, parent, x=None, int check=1, is_gen=False, int construct=0, **kwds):
    55625592        Polynomial.__init__(self, parent, is_gen=is_gen)
    5563 
    55645593        if x is None:
    55655594            self.__coeffs = []
    55665595            return
     5596
    55675597        R = parent.base_ring()
    5568        
     5598        if PY_TYPE_CHECK(x, list):
     5599            if check:
     5600                self.__coeffs = [R(t) for t in x]
     5601                self.__normalize()
     5602            else:
     5603                self.__coeffs = x
     5604            return
     5605
    55695606        if sage.rings.fraction_field_element.is_FractionFieldElement(x):
    55705607            if x.denominator() != 1:
    55715608                raise TypeError, "denominator must be 1"
     
    55755612        if PY_TYPE_CHECK(x, Polynomial):
    55765613            if (<Element>x)._parent is self._parent:
    55775614                x = list(x.list())
    5578             elif (<Element>x)._parent is R or (<Element>x)._parent == R:
     5615            elif R.has_coerce_map_from((<Element>x)._parent):# is R or (<Element>x)._parent == R:
     5616                try:
     5617                    if x.is_zero():
     5618                        self.__coeffs = []
     5619                        return
     5620                except (AttributeError, TypeError):
     5621                    pass
    55795622                x = [x]
    55805623            else:
    5581                 x = [R(a, **kwds) for a in x.list()]
    5582                 check = 0
    5583                
    5584         elif PY_TYPE_CHECK(x, list):
    5585             pass
    5586            
     5624                self.__coeffs = [R(a, **kwds) for a in x.list()]
     5625                if check:
     5626                    self.__normalize()
     5627                return
     5628
    55875629        elif PY_TYPE_CHECK(x, int) and x == 0:
    55885630            self.__coeffs = []
    55895631            return
    5590                                
     5632
    55915633        elif isinstance(x, dict):
    5592             x = self._dict_to_list(x, R(0))
     5634            x = self._dict_to_list(x, R.zero_element())
    55935635           
    55945636        elif isinstance(x, pari_gen):
    55955637            x = [R(w, **kwds) for w in x.Vecrev()]
    5596             check = 1
     5638            check = 0
    55975639        elif not isinstance(x, list):
     5640            # We trust that the element constructors do not send x=0
     5641#            if x:
    55985642            x = [x]   # constant polynomials
     5643#            else:
     5644#                x = []    # zero polynomial
    55995645        if check:
    56005646            self.__coeffs = [R(z, **kwds) for z in x]
     5647            self.__normalize()
    56015648        else:
    56025649            self.__coeffs = x
    5603         if check:
    5604             self.__normalize()
    5605        
    5606     cdef Polynomial_generic_dense _new_c(self, list coeffs):
     5650
     5651    cdef Polynomial_generic_dense _new_c(self, list coeffs, Parent P):
    56075652        cdef Polynomial_generic_dense f = <Polynomial_generic_dense>PY_NEW_SAME_TYPE(self)
    5608         f._parent = self._parent
     5653        f._parent = P
    56095654        f.__coeffs = coeffs
    56105655        return f
    56115656   
    5612     cpdef Polynomial _new_constant_poly(self, a):
    5613         """
    5614         Create a new constant polynomial from a, which MUST be an element of the base ring.
    5615        
    5616         EXAMPLES:
     5657    cpdef Polynomial _new_constant_poly(self, a, Parent P):
     5658        """
     5659        Create a new constant polynomial in P with value a.
     5660
     5661        ASSUMPTION:
     5662
     5663        The given value **must** be an element of the base ring. That
     5664        assumption is not verified.
     5665       
     5666        EXAMPLES::
     5667
    56175668            sage: S.<y> = QQ[]
    56185669            sage: R.<x> = S[]
    5619             sage: x._new_constant_poly(y+1)
     5670            sage: x._new_constant_poly(y+1, R)
    56205671            y + 1
    5621             sage: parent(x._new_constant_poly(y+1))
     5672            sage: parent(x._new_constant_poly(y+1, R))
    56225673            Univariate Polynomial Ring in x over Univariate Polynomial Ring in y over Rational Field
    56235674        """
    56245675        if a:
    5625             return self._new_c([a])
     5676            return self._new_c([a],P)
    56265677        else:
    5627             return self._new_c([])
     5678            return self._new_c([],P)
    56285679           
    56295680    def __reduce__(self):
    56305681        """
     
    56775728            0
    56785729        """
    56795730        if n < 0 or n >= len(self.__coeffs):
    5680             return self.base_ring()(0)
     5731            return self.base_ring().zero_element()
    56815732        return self.__coeffs[n]
    56825733
    56835734    def __getslice__(self, Py_ssize_t i, j):
     
    56985749            i = 0
    56995750            zeros = []
    57005751        elif i > 0:
    5701             zeros = [self._parent.base_ring()(0)] * i
     5752            zeros = [self._parent.base_ring().zero_element()] * i
    57025753        return self._parent(zeros + self.__coeffs[i:j])
    57035754
    57045755    def _unsafe_mutate(self, n, value):
     
    57295780        elif n < 0:
    57305781            raise IndexError, "polynomial coefficient index must be nonnegative"
    57315782        elif value != 0:
    5732             zero = self.base_ring()(0)
     5783            zero = self.base_ring().zero_element()
    57335784            for _ in xrange(len(self.__coeffs), n):
    57345785                self.__coeffs.append(zero)
    57355786            self.__coeffs.append(value)
     
    57505801            sage: f.quo_rem(1+2*x)
    57515802            (4*x^2 + 4*x + 5/2, -3/2)
    57525803        """
    5753         if right.parent() == self.parent():
     5804        P = (<Element>self)._parent
     5805        if right.parent() == P:
    57545806            return Polynomial.__floordiv__(self, right)
    5755         d = self.parent().base_ring()(right)
    5756         cdef Polynomial_generic_dense res = self._new_c([c // d for c in self.__coeffs])
     5807        d = P.base_ring()(right)
     5808        cdef Polynomial_generic_dense res = self._new_c([c // d for c in self.__coeffs], P)
    57575809        res.__normalize()
    57585810        return res
    57595811       
     
    57725824            min = len(x)
    57735825        cdef list low = [x[i] + y[i] for i from 0 <= i < min]
    57745826        if len(x) == len(y):
    5775             res = self._new_c(low)
     5827            res = self._new_c(low, self._parent)
    57765828            res.__normalize()
    57775829            return res
    57785830        else:
    5779             return self._new_c(low + high)
     5831            return self._new_c(low + high, self._parent)
    57805832           
    57815833    cpdef ModuleElement _iadd_(self, ModuleElement right):
    57825834        cdef Py_ssize_t check=0, i, min
     
    58085860            min = len(x)
    58095861        low = [x[i] - y[i] for i from 0 <= i < min]
    58105862        if len(x) == len(y):
    5811             res = self._new_c(low)
     5863            res = self._new_c(low, self._parent)
    58125864            res.__normalize()
    58135865            return res
    58145866        else:
    5815             return self._new_c(low + high)
     5867            return self._new_c(low + high, self._parent)
    58165868       
    58175869    cpdef ModuleElement _isub_(self, ModuleElement right):
    58185870        cdef Py_ssize_t check=0, i, min
     
    58355887        if c._parent is not (<Element>self.__coeffs[0])._parent:
    58365888            c = (<Element>self.__coeffs[0])._parent._coerce_c(c)
    58375889        v = [c * a for a in self.__coeffs]
    5838         cdef Polynomial_generic_dense res = self._new_c(v)
    5839         if not v[len(v)-1]:
    5840             res.__normalize()
     5890        cdef Polynomial_generic_dense res = self._new_c(v, self._parent)
     5891        #if not v[len(v)-1]:
     5892        # "normalize" checks this anyway...
     5893        res.__normalize()
    58415894        return res
    58425895       
    58435896    cpdef ModuleElement _lmul_(self, RingElement c):
     
    58465899        if c._parent is not (<Element>self.__coeffs[0])._parent:
    58475900            c = (<Element>self.__coeffs[0])._parent._coerce_c(c)
    58485901        v = [a * c for a in self.__coeffs]
    5849         cdef Polynomial_generic_dense res = self._new_c(v)
    5850         if not v[len(v)-1]:
    5851             res.__normalize()
     5902        cdef Polynomial_generic_dense res = self._new_c(v, self._parent)
     5903        #if not v[len(v)-1]:
     5904        # "normalize" checks this anyway...
     5905        res.__normalize()
    58525906        return res
    58535907       
    58545908    cpdef ModuleElement _ilmul_(self, RingElement c):
     
    58785932            t
    58795933        """
    58805934        if len(self.__coeffs) == 0:
    5881             return self.base_ring()(0)
     5935            return self.base_ring().zero_element()
    58825936        else:
    58835937            return self.__coeffs[0]
    58845938
     
    59445998        if n == 0 or self.degree() < 0:
    59455999            return self
    59466000        if n > 0:
    5947             output = [self.base_ring()(0)] * n
     6001            output = [self.base_ring().zero_element()] * n
    59486002            output.extend(self.__coeffs)
    5949             return self._new_c(output)
     6003            return self._new_c(output, self._parent)
    59506004        if n < 0:
    59516005            if n > len(self.__coeffs) - 1:
    59526006                return self._parent([])
    59536007            else:
    5954                 return self._new_c(self.__coeffs[-int(n):])
     6008                return self._new_c(self.__coeffs[-int(n):], self._parent)
    59556009   
    59566010    cpdef Polynomial truncate(self, long n):
    59576011        r"""
     
    59806034            sage: type(f)
    59816035            <type 'sage.rings.polynomial.polynomial_element.Polynomial_generic_dense'>
    59826036        """
    5983         if n < len(self.__coeffs):
    5984             while n > 0 and not self.__coeffs[n-1]:
    5985                 n -= 1
    5986         return self._new_c(self.__coeffs[:n])
     6037        l = len(self.__coeffs)
     6038        if n > l:
     6039            n = l
     6040        while n > 0 and not self.__coeffs[n-1]:
     6041            n -= 1
     6042        return self._new_c(self.__coeffs[:n], self._parent)
    59876043
    59886044    cdef _inplace_truncate(self, long n):
    59896045        if n < len(self.__coeffs):
     
    60016057    """
    60026058    This class is used for conversion from a polynomial ring to its base ring.
    60036059   
    6004     It calls the constant_coefficient method, which can be optimized for
    6005     a particular polynomial type.
     6060    Since trac ticket #9944, it calls the constant_coefficient method,
     6061    which can be optimized for a particular polynomial type.
     6062
     6063    EXAMPLES::
     6064
     6065        sage: P0.<y_1> = GF(3)[]
     6066        sage: P1.<y_2,y_1,y_0> = GF(3)[]
     6067        sage: P0(-y_1)    # indirect doctest
     6068        2*y_1
     6069        sage: phi = GF(3).convert_map_from(P0); phi
     6070        Generic map:
     6071          From: Univariate Polynomial Ring in y_1 over Finite Field of size 3
     6072          To:   Finite Field of size 3
     6073        sage: type(phi)
     6074        <type 'sage.rings.polynomial.polynomial_element.ConstantPolynomialSection'>
     6075        sage: phi(P0.one_element())
     6076        1
     6077        sage: phi(y_1)
     6078        Traceback (most recent call last):
     6079        ...
     6080        TypeError: not a constant polynomial
     6081
    60066082    """
    60076083    cpdef Element _call_(self, x):
    60086084        """
     
    60236099            TypeError: not a constant polynomial
    60246100        """
    60256101        if x.degree() <= 0:
    6026             return <Element>((<Polynomial>x).constant_coefficient())
     6102            try:
     6103                return <Element>(x.constant_coefficient())
     6104            except AttributeError:
     6105                return <Element>((<Polynomial>x).constant_coefficient())
    60276106        else:
    60286107            raise TypeError, "not a constant polynomial"
    60296108
     
    60326111    This class is used for conversion from a ring to a polynomial
    60336112    over that ring.
    60346113   
    6035     If the polynomial ring has a One and if the elements provide an
    6036     ``_rmul_`` method, and ``_rmul_`` does *not* return None (which is
    6037     the case for `p`-adics) then conversion is obtained by multiplying
    6038     the base ring element with the One by means of `_rmul_`.
    6039 
    6040     Otherwise It calls the _new_constant_poly method on the generator,
    6041     which should be optimized for a particular polynomial type, but
    6042     often isn't.
     6114    It calls the _new_constant_poly method on the generator,
     6115    which should be optimized for a particular polynomial type.
    60436116
    60446117    Technically, it should be a method of the polynomial ring, but
    6045     few polynomial rings are cython classes.
    6046 
    6047     NOTE:
    6048 
    6049     We use `_rmul_` and not `_lmul_` since for many polynomial rings
    6050     `_lmul_` simply calls `_rmul_`.
     6118    few polynomial rings are cython classes, and so, as a method
     6119    of a cython polynomial class, it is faster.
    60516120
    60526121    EXAMPLES:
    60536122
    6054     We demonstrate that different polynomial ring classes use
    6055     polynomial base injection maps::
     6123    We demonstrate that most polynomial ring classes use
     6124    polynomial base injection maps for coercion. They are
     6125    supposed to be the fastest maps for that purpose. See
     6126    trac ticket #9944::
    60566127
    60576128        sage: R.<x> = Qp(3)[]
    6058         sage: R.convert_map_from(R.base_ring())
     6129        sage: R.coerce_map_from(R.base_ring())
    60596130        Polynomial base injection morphism:
    60606131          From: 3-adic Field with capped relative precision 20
    60616132          To:   Univariate Polynomial Ring in x over 3-adic Field with capped relative precision 20
    60626133        sage: R.<x,y> = Qp(3)[]
    6063         sage: R.convert_map_from(R.base_ring())
     6134        sage: R.coerce_map_from(R.base_ring())
    60646135        Polynomial base injection morphism:
    60656136          From: 3-adic Field with capped relative precision 20
    60666137          To:   Multivariate Polynomial Ring in x, y over 3-adic Field with capped relative precision 20
    60676138        sage: R.<x,y> = QQ[]
    6068         sage: R.convert_map_from(R.base_ring())
     6139        sage: R.coerce_map_from(R.base_ring())
    60696140        Polynomial base injection morphism:
    60706141          From: Rational Field
    60716142          To:   Multivariate Polynomial Ring in x, y over Rational Field
    60726143        sage: R.<x> = QQ[]
    6073         sage: R.convert_map_from(R.base_ring())
     6144        sage: R.coerce_map_from(R.base_ring())
    60746145        Polynomial base injection morphism:
    60756146          From: Rational Field
    60766147          To:   Univariate Polynomial Ring in x over Rational Field
    60776148
    60786149    By trac ticket #9944, there are now only very few exceptions::
    60796150
    6080         sage: PolynomialRing(QQ,names=[]).convert_map_from(QQ)
     6151        sage: PolynomialRing(QQ,names=[]).coerce_map_from(QQ)
    60816152        Call morphism:
    60826153          From: Rational Field
    60836154          To:   Multivariate Polynomial Ring in no variables over Rational Field
     
    60856156    """
    60866157   
    60876158    cdef RingElement _an_element
    6088     cdef object _one_rmul_
     6159    cdef object _new_constant_poly_
    60896160   
    60906161    def __init__(self, domain, codomain):
    60916162        """
     
    61116182            (1 + 2 + O(2^20))*t
    61126183
    61136184        """
    6114         assert domain is codomain.base_ring(), "domain must be basering"
     6185        assert codomain.base_ring() is domain, "domain must be basering"
    61156186        Morphism.__init__(self, domain, codomain)
    61166187        self._an_element = codomain.gen()
    61176188        self._repr_type_str = "Polynomial base injection"
    6118         if domain is codomain: # some rings are base rings of themselves!
    6119             return
    6120         try:
    6121             one = codomain._element_constructor_(domain.one_element())
    6122         except (AttributeError, NotImplementedError, TypeError):
    6123             # perhaps it uses the old model?
    6124             try:
    6125                 one = codomain._coerce_c(domain.one_element())
    6126             except (AttributeError, NotImplementedError, TypeError):
    6127                 return
    6128         try:
    6129             one_rmul_ = one._rmul_
    6130         except AttributeError:
    6131             return
    6132         # For the p-adic fields, _lmul_ and _rmul_ return None!!!
    6133         # To work around, we need to test its sanity before we try
    6134         # to use it.
    6135         try:
    6136             if one_rmul_(domain.one_element()) is None:
    6137                 return
    6138             self._one_rmul_ = one_rmul_
    6139         except TypeError:
    6140             pass
    6141    
     6189        self._new_constant_poly_ = self._an_element._new_constant_poly
     6190
    61426191    cpdef Element _call_(self, x):
    61436192        """
    61446193        TESTS:
     
    61526201            sage: parent(m(2))
    61536202            Univariate Polynomial Ring in x over Integer Ring
    61546203        """
    6155         if self._one_rmul_ is not None:
    6156             return self._one_rmul_(x)
    6157         return self._an_element._new_constant_poly(<Element>x)
     6204        return self._new_constant_poly_(x, self._codomain)
    61586205   
    61596206    cpdef Element _call_with_args(self, x, args=(), kwds={}):
    61606207        """
     
    61646211            sage: m(1 + O(5^11), absprec = 5)   # indirect doctest
    61656212            (1 + O(5^11))
    61666213        """
    6167         return self._codomain._element_constructor(x, *args, **kwds)
     6214        try:
     6215            return self._codomain._element_constructor_(x, *args, **kwds)
     6216        except AttributeError:
     6217            # if there is no element constructor,
     6218            # there is a custom call method.
     6219            return self._codomain(x, *args, **kwds)
    61686220
    61696221    def section(self):
    61706222        """
  • sage/rings/polynomial/polynomial_element_generic.py

    diff -r 216c066ba752 sage/rings/polynomial/polynomial_element_generic.py
    a b  
    8888                w = {}
    8989                for n, c in x.dict().iteritems():
    9090                    w[n] = R(c)
    91                 #raise TypeError, "Cannot coerce %s into %s."%(x, parent)
     91                # The following line has been added in trac ticket #9944.
     92                # Apparently, the "else" case has never occured before.
     93                x = w 
    9294        elif isinstance(x, list):
    9395            y = {}
    9496            for i in xrange(len(x)):
     
    418420            x^100000 + 4*x^75000 + 3*x
    419421
    420422        AUTHOR:
     423
    421424        - David Harvey (2006-08-05)
    422425        """
    423426        output = dict(self.__coeffs)
  • sage/rings/polynomial/polynomial_integer_dense_flint.pxd

    diff -r 216c066ba752 sage/rings/polynomial/polynomial_integer_dense_flint.pxd
    a b  
    66
    77from sage.rings.polynomial.polynomial_element cimport Polynomial
    88from sage.rings.integer cimport Integer
     9from sage.structure.parent cimport Parent
    910
    1011cdef class Polynomial_integer_dense_flint(Polynomial):
    1112    cdef fmpz_poly_t __poly
  • sage/rings/polynomial/polynomial_integer_dense_flint.pyx

    diff -r 216c066ba752 sage/rings/polynomial/polynomial_integer_dense_flint.pyx
    a b  
    8080        x._is_gen = 0
    8181        return x
    8282
     83    cpdef Polynomial _new_constant_poly(self, a, Parent P):
     84        r"""
     85        Quickly creates a new constant polynomial with value a in parent P
     86
     87        ASSUMPTION:
     88
     89        The given value has to be in the base ring of P. This assumption is not
     90        verified.
     91
     92        EXAMPLE::
     93
     94            sage: R.<x> = ZZ[]
     95            sage: x._new_constant_poly(2,R)
     96            2
     97
     98        """
     99        cdef Polynomial_integer_dense_flint x = PY_NEW(Polynomial_integer_dense_flint)
     100        x._parent = P
     101        x._is_gen = 0
     102        if not PY_TYPE_CHECK(a, Integer):
     103            a = ZZ(a)
     104        fmpz_poly_set_coeff_mpz(x.__poly, 0, (<Integer>a).value)
     105        return x
    83106                                           
    84107    def __init__(self, parent, x=None, check=True, is_gen=False,
    85108            construct=False):
  • sage/rings/polynomial/polynomial_rational_flint.pxd

    diff -r 216c066ba752 sage/rings/polynomial/polynomial_rational_flint.pxd
    a b  
    1212include "../../libs/flint/fmpq_poly.pxd"
    1313
    1414from sage.rings.polynomial.polynomial_element cimport Polynomial
     15from sage.structure.parent cimport Parent
    1516
    1617cdef class Polynomial_rational_flint(Polynomial):
    1718    cdef fmpq_poly_t __poly
  • sage/rings/polynomial/polynomial_rational_flint.pyx

    diff -r 216c066ba752 sage/rings/polynomial/polynomial_rational_flint.pyx
    a b  
    101101        res._is_gen = 0
    102102        return res
    103103
     104    cpdef Polynomial _new_constant_poly(self, x, Parent P):
     105        r"""
     106        Quickly creates a new constant polynomial with value x in parent P
     107
     108        ASSUMPTION:
     109
     110        x must be a rational or convertible to an int.
     111
     112        EXAMPLE::
     113
     114        sage: R.<x> = QQ[]
     115            sage: x._new_constant_poly(2/1,R)
     116            2
     117            sage: x._new_constant_poly(2,R)
     118            2
     119            sage: x._new_constant_poly("2",R)
     120            2
     121            sage: x._new_constant_poly("2.1",R)
     122            Traceback (most recent call last):
     123            ...
     124            ValueError: invalid literal for int() with base 10: '2.1'
     125
     126        """
     127        cdef Polynomial_rational_flint res = PY_NEW(Polynomial_rational_flint)
     128        res._parent = P
     129        res._is_gen = <char>0
     130        if PY_TYPE_CHECK(x, int):
     131            fmpq_poly_set_si(res.__poly, <int> x)
     132       
     133        elif PY_TYPE_CHECK(x, Integer):
     134            fmpq_poly_set_mpz(res.__poly, (<Integer> x).value)
     135
     136        elif PY_TYPE_CHECK(x, Rational):
     137            fmpq_poly_set_mpq(res.__poly, (<Rational> x).value)
     138
     139        else:
     140            fmpq_poly_set_si(res.__poly, int(x))
     141        return res
     142
     143
    104144    def __cinit__(self):
    105145        """
    106146        Initialises the underlying data structure.
  • sage/rings/polynomial/polynomial_real_mpfr_dense.pyx

    diff -r 216c066ba752 sage/rings/polynomial/polynomial_real_mpfr_dense.pyx
    a b  
    4242            sage: from sage.rings.polynomial.polynomial_real_mpfr_dense import PolynomialRealDense
    4343            sage: PolynomialRealDense(RR['x'], [1, int(2), RR(3), 4/1, pi])
    4444            3.14159265358979*x^4 + 4.00000000000000*x^3 + 3.00000000000000*x^2 + 2.00000000000000*x + 1.00000000000000
     45            sage: PolynomialRealDense(RR['x'], None)
     46            0
     47
    4548        """
    4649        Polynomial.__init__(self, parent, is_gen=is_gen)
    4750        self._base_ring = parent._base
    4851        cdef Py_ssize_t i, degree
    4952        cdef int prec = self._base_ring.__prec
    5053        cdef mp_rnd_t rnd = self._base_ring.rnd
     54        if x is None:
     55            self._coeffs = <mpfr_t*>sage_malloc(sizeof(mpfr_t)) # degree zero
     56            mpfr_init2(self._coeffs[0], prec)
     57            mpfr_set_si(self._coeffs[0], PyInt_AS_LONG(int(0)), rnd)
     58            self._normalize()
     59            return
    5160        if is_gen:
    5261            x = [0, 1]
    5362        elif isinstance(x, (int, float, Integer, Rational, RealNumber)):
  • sage/rings/polynomial/polynomial_ring.py

    diff -r 216c066ba752 sage/rings/polynomial/polynomial_ring.py
    a b  
    1414
    1515- Martin Albrecht (2006-08-25): removed it again as it isn't needed anymore
    1616
     17- Simon King (2011-05): Dense and sparse polynomial rings must not be equal.
     18
    1719EXAMPLES:
     20
    1821Creating a polynomial ring injects the variable into the interpreter namespace::
    1922
    2023    sage: z = QQ['z'].0
     
    3235    sage: k = PolynomialRing(ZZ,'y', sparse=True); loads(dumps(k))
    3336    Sparse Univariate Polynomial Ring in y over Integer Ring
    3437
    35 The rings of sparse and dense polynomials in the same variable are
    36 canonically isomorphic::
    37 
    38     sage: PolynomialRing(ZZ,'y', sparse=True) == PolynomialRing(ZZ,'y')
    39     True
     38Rings with different variable names are not equal::
    4039
    4140    sage: QQ['y'] < QQ['x']
    4241    False
     
    5857    sage: g * f
    5958    w^2 + (i + j)*w - k
    6059
     60Trac ticket #9944 introduced some changes related with
     61coercion. Previously, a dense and a sparse polynomial ring with the
     62same variable name over the same base ring evaluated equal, but of
     63course they were not identical.Coercion maps are cached - but if a
     64coercion to a dense ring is requested and a coercion to a sparse ring
     65is returned instead (since the cache keys are equal!), all hell breaks
     66loose.
     67
     68Therefore, the coercion between rings of sparse and dense polynomials
     69works as follows::
     70
     71    sage: R.<x> = PolynomialRing(QQ, sparse=True)
     72    sage: S.<x> = QQ[]
     73    sage: S == R
     74    False
     75    sage: S.has_coerce_map_from(R)
     76    True
     77    sage: R.has_coerce_map_from(S)
     78    False
     79    sage: (R.0+S.0).parent()
     80    Univariate Polynomial Ring in x over Rational Field
     81    sage: (S.0+R.0).parent()
     82    Univariate Polynomial Ring in x over Rational Field
     83
     84It may be that one has rings of dense or sparse polynomials over
     85different base rings. In that situation, coercion works by means of
     86the :func:`~sage.categories.pushout.pushout` formalism::
     87
     88    sage: R.<x> = PolynomialRing(GF(5), sparse=True)
     89    sage: S.<x> = PolynomialRing(ZZ)
     90    sage: R.has_coerce_map_from(S)
     91    False
     92    sage: S.has_coerce_map_from(R)
     93    False
     94    sage: S.0 + R.0
     95    2*x
     96    sage: (S.0 + R.0).parent()
     97    Univariate Polynomial Ring in x over Finite Field of size 5
     98    sage: (S.0 + R.0).parent().is_sparse()
     99    False
     100
     101Similarly, there is a coercion from the (non-default) NTL
     102implementation for univariate polynomials over the integers
     103to the default FLINT implementation, but not vice versa::
     104
     105    sage: R.<x> = PolynomialRing(ZZ, implementation = 'NTL')
     106    sage: S.<x> = PolynomialRing(ZZ, implementation = 'FLINT')
     107    sage: (S.0+R.0).parent() is S
     108    True
     109    sage: (R.0+S.0).parent() is S
     110    True
     111
    61112TESTS::
    62113
    63114    sage: K.<x>=FractionField(QQ['x'])
     
    108159from sage.rings.integer_ring import is_IntegerRing, IntegerRing
    109160from sage.rings.integer import Integer
    110161from sage.libs.pari.all import pari_gen
     162
    111163import sage.misc.defaults
    112164import sage.misc.latex as latex
    113165from sage.misc.prandom import randint
     166from sage.misc.cachefunc import cached_method
     167
    114168from sage.rings.real_mpfr import is_RealField
    115169from polynomial_real_mpfr_dense import PolynomialRealDense
    116170from sage.rings.polynomial.polynomial_singular_interface import PolynomialRing_singular_repr
     
    233287       
    234288    def _element_constructor_(self, x=None, check=True, is_gen = False, construct=False, **kwds):
    235289        r"""
    236         Coerce ``x`` into this univariate polynomial ring,
     290        Convert ``x`` into this univariate polynomial ring,
    237291        possibly non-canonically.
    238292       
    239293        Stacked polynomial rings coerce into constants if possible. First,
     
    287341            -y
    288342
    289343        TESTS:
     344
    290345        This shows that the issue at trac #4106 is fixed::
    291346       
    292347            sage: x = var('x')
     
    296351            x
    297352        """
    298353        C = self._polynomial_class
     354        if isinstance(x, list):
     355            return C(self, x, check=check, is_gen=False,construct=construct)
    299356        if isinstance(x, Element):
    300357            P = x.parent()
    301358            if P is self:
    302359                return x
     360            elif P is self.base_ring():
     361                # It *is* the base ring, hence, we should not need to check.
     362                # Moreover, if x is equal to zero then we usually need to
     363                # provide [] to the polynomial class, not [x], if we don't want
     364                # to check (normally, polynomials like to strip trailing zeroes).
     365                # However, in the padic case, we WANT that trailing
     366                # zeroes are not stripped, because O(5)==0, but still it must
     367                # not be forgotten. It should be the job of the __init__ method
     368                # to decide whether to strip or not to strip.
     369                return C(self, [x], check=False, is_gen=False,
     370                         construct=construct)
    303371            elif P == self.base_ring():
    304372                return C(self, [x], check=True, is_gen=False,
    305                         construct=construct)
     373                         construct=construct)
     374               
    306375            elif self.base_ring().has_coerce_map_from(P):
    307376                return C(self, [x], check=True, is_gen=False,
    308377                        construct=construct)
    309         if hasattr(x, '_polynomial_'):
    310             return x._polynomial_(self)       
     378        try: #if hasattr(x, '_polynomial_'):
     379            return x._polynomial_(self)
     380        except AttributeError:
     381            pass
    311382        if isinstance(x, SingularElement) and self._has_singular:
    312383            self._singular_().set_ring()
    313384            try:
     
    333404                raise TypeError, "denominator must be a unit"
    334405            if x.type() != 't_POL':
    335406                x = x.Polrev()
    336 
    337407        return C(self, x, check, is_gen, construct=construct, **kwds)
    338408
    339409    def is_integral_domain(self, proof = True):
     
    352422           
    353423    def construction(self):
    354424        from sage.categories.pushout import PolynomialFunctor
    355         return PolynomialFunctor(self.variable_name()), self.base_ring()
     425        return PolynomialFunctor(self.variable_name(), sparse=self.__is_sparse), self.base_ring()
    356426
    357427    def completion(self, p, prec=20, extras=None):
    358428        """
     
    393463        - any ring that canonically coerces to the base ring of this ring.
    394464       
    395465        - polynomial rings in the same variable over any base ring that
    396           canonically coerces to the base ring of this ring
     466          canonically coerces to the base ring of this ring.
     467
     468        Caveat: There is no coercion from a dense into a sparse
     469        polynomial ring. So, when adding a dense and a sparse
     470        polynomial, the result will be dense. See trac ticket #9944.
    397471       
    398472        EXAMPLES::
    399473       
     
    420494                      Polynomial base injection morphism:
    421495                      From: Rational Field
    422496                      To:   Univariate Polynomial Ring in x over Rational Field
     497
     498        Here we test against the change in the coercions introduced
     499        in trac ticket #9944::
     500
     501            sage: R.<x> = PolynomialRing(QQ, sparse=True)
     502            sage: S.<x> = QQ[]
     503            sage: (R.0+S.0).parent()
     504            Univariate Polynomial Ring in x over Rational Field
     505            sage: (S.0+R.0).parent()
     506            Univariate Polynomial Ring in x over Rational Field
     507
    423508        """
    424509        # handle constants that canonically coerce into self.base_ring()
    425510        # first, if possible
     
    434519        # coerces into self.base_ring()
    435520        try:
    436521            if is_PolynomialRing(P):
     522                if self.__is_sparse and not P.is_sparse():
     523                    return False
    437524                if P.variable_name() == self.variable_name():
    438525                    if P.base_ring() is self.base_ring() and \
    439526                            self.base_ring() is ZZ_sage:
     
    566653            # of the polynomial ring canonically coerce into codomain.
    567654            # Since poly rings are free, any image of the gen
    568655            # determines a homomorphism
    569             codomain.coerce(self.base_ring()(1))
     656            codomain.coerce(self.base_ring().one_element())
    570657        except TypeError:
    571658            return False
    572659        return True
    573660
    574     def __cmp__(left, right):
    575         c = cmp(type(left),type(right))
    576         if c: return c
    577         return cmp((left.base_ring(), left.variable_name()), (right.base_ring(), right.variable_name()))
     661#    Polynomial rings should be unique parents. Hence,
     662#    no need for __cmp__. Or actually, having a __cmp__
     663#    method that identifies a dense with a sparse ring
     664#    is a bad bad idea!
     665#    def __cmp__(left, right):
     666#        c = cmp(type(left),type(right))
     667#        if c: return c
     668#        return cmp((left.base_ring(), left.variable_name()), (right.base_ring(), right.variable_name()))
     669
     670    def __hash__(self):
     671        # should be faster than just relying on the string representation
     672        try:
     673            return self._cached_hash
     674        except AttributeError:
     675            pass
     676        h = self._cached_hash = hash((self.base_ring(),self.variable_name()))
     677        return h
    578678
    579679    def _repr_(self):
     680        try:
     681            return self._cached_repr
     682        except AttributeError:
     683            pass
    580684        s = "Univariate Polynomial Ring in %s over %s"%(
    581685                self.variable_name(), self.base_ring())
    582686        if self.is_sparse():
    583687            s = "Sparse " + s
     688        self._cached_repr = s
    584689        return s
    585690
    586691    def _latex_(self):
     
    9691074        Refer to monics() for full documentation.
    9701075        """
    9711076        base = self.base_ring()
    972         for coeffs in sage.misc.mrange.xmrange_iter([[base(1)]]+[base]*of_degree):
     1077        for coeffs in sage.misc.mrange.xmrange_iter([[base.one_element()]]+[base]*of_degree):
    9731078            # Each iteration returns a *new* list!
    9741079            # safe to mutate the return
    9751080            coeffs.reverse()
     
    9881093        Refer to polynomials() for full documentation.
    9891094        """
    9901095        base = self.base_ring()
     1096        base0 = base.zero_element()
    9911097        for leading_coeff in base:
    992             if leading_coeff != base(0):
     1098            if leading_coeff != base0:
    9931099                for lt1 in sage.misc.mrange.xmrange_iter([base]*(of_degree)):
    9941100                    # Each iteration returns a *new* list!
    9951101                    # safe to mutate the return
     
    12081314                    element_class = Polynomial_integer_dense_flint
    12091315                    self._implementation_names = (None, 'FLINT')
    12101316                else:
    1211                     raise ValueError, "Unknown implementation %s for ZZ[x]"
     1317                    raise ValueError, "Unknown implementation %s for ZZ[x]"%implementation
    12121318        PolynomialRing_commutative.__init__(self, base_ring, name=name,
    12131319                sparse=sparse, element_class=element_class)
    12141320   
  • sage/rings/polynomial/polynomial_ring_constructor.py

    diff -r 216c066ba752 sage/rings/polynomial/polynomial_ring_constructor.py
    a b  
    44This module provides the function :func:`PolynomialRing`, which constructs
    55rings of univariate and multivariate polynomials, and implements caching to
    66prevent the same ring being created in memory multiple times (which is
    7 wasteful).
     7wasteful and breaks the general assumption in Sage that parents are unique).
    88
    99There is also a function :func:`BooleanPolynomialRing_constructor`, used for
    1010constructing Boolean polynomial rings, which are not technically polynomial
     
    8181    - ``implementation`` -- string or None; selects an implementation in cases
    8282      where Sage includes multiple choices (currently `\ZZ[x]` can be
    8383      implemented with 'NTL' or 'FLINT'; default is 'FLINT')
     84
     85    NOTE:
     86
     87    The following rules were introduced in trac ticket #9944, in order
     88    to preserve the "unique parent assumption" in Sage (i.e., if two
     89    parents evaluate equal then they should actually be identical).
     90
     91    - In the multivariate case, a dense representation is not supported. Hence,
     92      the argument ``sparse=False`` is silently ignored in that case.
     93    - If the given implementation does not exist for rings with the given number
     94      of generators and the given sparsity, then an error results.
    8495                 
    8596    OUTPUT:
    8697
     
    106117
    107118        You can't just globally change the names of those variables.
    108119        This is because objects all over Sage could have pointers to
    109         that polynomial ring. ::
     120        that polynomial ring.
     121        ::
    110122
    111123            sage: R._assign_names(['z','w'])
    112124            Traceback (most recent call last):
     
    120132            ...     
    121133            z^2 - 2*w^2
    122134
    123         After the ``with`` block the names revert to what they were before. ::
     135        After the ``with`` block the names revert to what they were before.
     136        ::
    124137
    125138            sage: print f
    126139            x^2 - 2*y^2
     
    189202       integers, one based on NTL and one based on FLINT.  The default
    190203       is FLINT. Note that FLINT uses a "more dense" representation for
    191204       its polynomials than NTL, so in particular, creating a polynomial
    192        like 2^1000000 * x^1000000 in FLINT may be unwise. ::
     205       like 2^1000000 * x^1000000 in FLINT may be unwise.
     206       ::
    193207
    194208        sage: ZxNTL = PolynomialRing(ZZ, 'x', implementation='NTL'); ZxNTL
    195209        Univariate Polynomial Ring in x over Integer Ring (using NTL)
     
    206220        sage: xFLINT.parent()
    207221        Univariate Polynomial Ring in x over Integer Ring
    208222
    209        There is a coercion between the two rings, so the values can be
    210        mixed in a single expression. ::
     223       There is a coercion from the non-default to the default
     224       implementation, so the values can be mixed in a single
     225       expression::
    211226
    212227        sage: (xNTL + xFLINT^2)
    213228        x^2 + x
    214229
    215        Unfortunately, it is unpredictable whether the result of such an
    216        expression will use the NTL or FLINT implementation. ::
     230       The result of such an expression will use the default, i.e.,
     231       the FLINT implementation::
    217232
    218         sage: (xNTL + xFLINT^2).parent()        # random output
     233        sage: (xNTL + xFLINT^2).parent()
    219234        Univariate Polynomial Ring in x over Integer Ring
    220235
    221236    2. ``PolynomialRing(base_ring, names,   order='degrevlex')``
     
    299314        Defining x2, x3, x5, x7, x11, x13, x17, x19, x23, x29, x31, x37, x41, x43, x47, x53, x59, x61, x67, x71, x73, x79, x83, x89, x97       
    300315        sage: (x2 + x41 + x71)^2
    301316        x2^2 + 2*x2*x41 + x41^2 + 2*x2*x71 + 2*x41*x71 + x71^2
     317
     318    TESTS:
     319
     320    We test here some changes introduced in #9944.
     321
     322    If there is no dense implementation for the given number of
     323    variables, then requesting a dense ring results yields the
     324    corresponding sparse ring::
     325
     326        sage: R.<x,y> = QQ[]
     327        sage: S.<x,y> = PolynomialRing(QQ, sparse=False)
     328        sage: R is S
     329        True
     330
     331    If the requested implementation is not known or not supported for
     332    the given number of variables and the given sparsity, then an
     333    error results::
     334
     335        sage: R.<x> = PolynomialRing(ZZ, implementation='Foo')
     336        Traceback (most recent call last):
     337        ...
     338        ValueError: Unknown implementation Foo for ZZ[x]
     339        sage: R.<x,y> = PolynomialRing(ZZ, implementation='FLINT')
     340        Traceback (most recent call last):
     341        ...
     342        ValueError: The FLINT implementation is not known for multivariate polynomial rings
     343
     344    The following corner case used to result in a warning message from
     345    ``libSingular``, and the generators of the resulting polynomial
     346    ring were not zero::
     347
     348        sage: R = Integers(1)['x','y']
     349        sage: R.0 == 0
     350        True
     351
    302352    """
    303353    import sage.rings.polynomial.polynomial_ring as m
    304354
     
    332382            raise TypeError, "You *must* specify the names of the variables."
    333383        n = int(arg2)
    334384        names = arg1
    335         R = _multi_variate(base_ring, names, n, sparse, order)
     385        R = _multi_variate(base_ring, names, n, sparse, order, implementation)
    336386
    337387    elif isinstance(arg1, str) or (isinstance(arg1, (list,tuple)) and len(arg1) == 1):
    338388        if not ',' in arg1:
     
    347397                raise TypeError, "invalid input to PolynomialRing function; please see the docstring for that function"
    348398            names = arg1.split(',')
    349399            n = len(names)
    350             R = _multi_variate(base_ring, names, n, sparse, order)
     400            R = _multi_variate(base_ring, names, n, sparse, order, implementation)
    351401    elif isinstance(arg1, (list, tuple)):
    352402            # PolynomialRing(base_ring, names (list or tuple), order='degrevlex'):       
    353403            names = arg1
    354404            n = len(names)
    355             R = _multi_variate(base_ring, names, n, sparse, order)       
     405            R = _multi_variate(base_ring, names, n, sparse, order, implementation)       
    356406
    357407    if arg1 is None and arg2 is None:
    358408        raise TypeError, "you *must* specify the indeterminates (as not None)."
     
    376426
    377427def _get_from_cache(key):
    378428    try:
    379         if _cache.has_key(key):
    380             return _cache[key] #()
     429        return _cache[key] #()
    381430    except TypeError, msg:
    382         raise TypeError, 'key = %s\n%s'%(key,msg)       
    383     return None
     431        raise TypeError, 'key = %s\n%s'%(key,msg)
     432    except KeyError:
     433        return None
    384434
    385435def _save_in_cache(key, R):
    386436    try:
     
    393443def _single_variate(base_ring, name, sparse, implementation):
    394444    import sage.rings.polynomial.polynomial_ring as m
    395445    name = normalize_names(1, name)
    396     key = (base_ring, name, sparse, implementation)
     446    key = (base_ring, name, sparse, implementation if not sparse else None)
    397447    R = _get_from_cache(key)
    398448    if not R is None: return R
    399449
     
    437487        _save_in_cache(key, R)
    438488    return R
    439489
    440 def _multi_variate(base_ring, names, n, sparse, order):
     490def _multi_variate(base_ring, names, n, sparse, order, implementation):
     491#    if not sparse:
     492#        raise ValueError, "A dense representation of multivariate polynomials is not supported"
     493    sparse = False
     494    # "True" would be correct, since there is no dense implementation of
     495    # multivariate polynomials. However, traditionally, "False" is used in the key,
     496    # even though it is meaningless.
     497
     498    if implementation is not None:
     499        raise ValueError, "The %s implementation is not known for multivariate polynomial rings"%implementation
     500
    441501    names = normalize_names(n, names)
    442502
    443503    import sage.rings.polynomial.multi_polynomial_ring as m
     
    460520            except ( TypeError, NotImplementedError ):
    461521                R = m.MPolynomialRing_polydict_domain(base_ring, n, names, order)
    462522    else:
    463         try:
    464             R = MPolynomialRing_libsingular(base_ring, n, names, order)
    465         except ( TypeError, NotImplementedError ):
     523        if not base_ring.is_zero():
     524            try:
     525                R = MPolynomialRing_libsingular(base_ring, n, names, order)
     526            except ( TypeError, NotImplementedError ):
     527                R = m.MPolynomialRing_polydict(base_ring, n, names, order)
     528        else:
    466529            R = m.MPolynomialRing_polydict(base_ring, n, names, order)
    467 
    468530    _save_in_cache(key, R)
    469531    return R
    470532
  • sage/rings/polynomial/polynomial_template.pxi

    diff -r 216c066ba752 sage/rings/polynomial/polynomial_template.pxi
    a b  
    147147            _parent = get_cparent(parent)
    148148
    149149            celement_construct(&self.x, get_cparent(parent))
    150 
    151150            gen = celement_new(_parent)
    152151            monomial = celement_new(_parent)
    153152
     
    156155
    157156            for deg, coef in x.iteritems():
    158157                celement_pow(monomial, gen, deg, NULL, _parent)
    159                 celement_mul(monomial, &(<Polynomial_template>parent(coef)).x, monomial, _parent)
     158                celement_mul(monomial, &(<Polynomial_template>self.__class__(parent, coef)).x, monomial, _parent)
    160159                celement_add(&self.x, &self.x, monomial, _parent)
    161160
    162161            celement_delete(gen, _parent)
  • sage/rings/polynomial/polynomial_zmod_flint.pxd

    diff -r 216c066ba752 sage/rings/polynomial/polynomial_zmod_flint.pxd
    a b  
    33     pass
    44
    55from sage.libs.flint.zmod_poly cimport zmod_poly_t, zmod_poly_struct
     6from sage.structure.parent cimport Parent
    67
    78ctypedef zmod_poly_struct celement
    89
  • sage/rings/polynomial/polynomial_zmod_flint.pyx

    diff -r 216c066ba752 sage/rings/polynomial/polynomial_zmod_flint.pyx
    a b  
    112112        e._parent = self._parent
    113113        return e
    114114
     115    cpdef Polynomial _new_constant_poly(self, x, Parent P):
     116        r"""
     117        Quickly creates a new constant polynomial with value x in parent P.
     118
     119        ASSUMPTION:
     120
     121        x must convertible to an int.
     122
     123        The modulus of P must coincide with the modulus of this element.
     124        That assumption is not verified!
     125
     126        EXAMPLE::
     127
     128            sage: R.<x> = GF(3)[]
     129            sage: x._new_constant_poly(4,R)
     130            1
     131            sage: x._new_constant_poly('4',R)
     132            1
     133            sage: x._new_constant_poly('4.1',R)
     134            Traceback (most recent call last):
     135            ...
     136            ValueError: invalid literal for int() with base 10: '4.1'
     137
     138        """
     139        cdef Polynomial_template r = <Polynomial_template>PY_NEW(self.__class__)
     140        r._parent = P
     141        zmod_poly_init(&r.x, zmod_poly_modulus(&self.x))
     142        celement_set_si(&r.x, int(x), get_cparent(P))
     143        return r
    115144
    116145    cdef _set_list(self, x):
    117146        """
  • sage/rings/polynomial/polynomial_zz_pex.pyx

    diff -r 216c066ba752 sage/rings/polynomial/polynomial_zz_pex.pyx
    a b  
    7777            sage: R.<x> = PolynomialRing(K,implementation='NTL')
    7878            sage: x^2+a
    7979            x^2 + a
     80
     81        TEST:
     82
     83        The following tests against a bug that was fixed in trac ticket #9944.
     84        With the ring definition above, we now have::
     85
     86            sage: R([3,'1234'])
     87            1234*x + 3
     88            sage: R([3,'12e34'])
     89            Traceback (most recent call last):
     90            ...
     91            TypeError: unable to convert '12e34' into the base ring
     92            sage: R([3,x])
     93            Traceback (most recent call last):
     94            ...
     95            TypeError: unable to convert x into the base ring
     96
    8097        """
    8198        cdef cparent _parent
    8299        cdef ntl_ZZ_pE d
     
    97114            celement_construct(&self.x, _parent)
    98115            K = parent.base_ring()
    99116            for i,e in enumerate(x):
    100                 if not hasattr(e,'polynomial'):
     117                try:
     118                    e_polynomial = e.polynomial()
     119                except (AttributeError, TypeError):
     120                    # A type error may occur, since sometimes
     121                    # e.polynomial expects an additional argument
    101122                    try:
    102                         e = K.coerce(e)
    103                     except:
    104                         TypeError("unable to coerce this value to the base ring")
    105                 d = parent._modulus.ZZ_pE(list(e.polynomial()))
     123                        # self(x) is supposed to be a conversion,
     124                        # not necessarily a coercion. So, we must
     125                        # not do K.coerce(e) but K(e).
     126                        e = K(e) # K.coerce(e)
     127                        e_polynomial = e.polynomial()
     128                    except TypeError:
     129                        raise TypeError, "unable to convert %s into the base ring"%repr(e)
     130                d = parent._modulus.ZZ_pE(list(e_polynomial))
    106131                ZZ_pEX_SetCoeff(self.x, i, d.x)
    107132            return
    108133               
  • sage/rings/power_series_poly.pyx

    diff -r 216c066ba752 sage/rings/power_series_poly.pyx
    a b  
    4646                prec = (<PowerSeries_poly>f)._prec
    4747                f = R((<PowerSeries_poly>f).__f)
    4848            else:
     49                if f:
     50                    f = R(f, check=check)
     51                else:
     52                    f = R(None)
     53        else:
     54            if f:
    4955                f = R(f, check=check)
    50         else:
    51             f = R(f, check=check)
     56            else: # None is supposed to yield zero
     57                f = R(None)
    5258
    5359        self.__f = f
    5460        if check and not (prec is infinity):
     
    7985       
    8086            sage: A.<z> = RR[[]]
    8187            sage: f = z - z^3 + O(z^10)
    82             sage: f == loads(dumps(f)) # uses __reduce__
     88            sage: f == loads(dumps(f)) # indirect doctest
    8389            True
    8490        """
    8591        # do *not* delete old versions.
  • sage/rings/power_series_ring_element.pyx

    diff -r 216c066ba752 sage/rings/power_series_ring_element.pyx
    a b  
    18641864
    18651865    g = _solve_linear_de(R, N, L2, a, b, f0)
    18661866
    1867     term1 = R(g, check=False)
    1868     term2 = R(a[:L], check=False)
     1867    term1 = R(g)  # we must not have check=False, since otherwise [..., 0, 0] is not stripped
     1868    term2 = R(a[:L]) #, check=False)
    18691869    product = (term1 * term2).list()
    18701870
    18711871    # todo: perhaps next loop could be made more efficient
  • sage/rings/qqbar.py

    diff -r 216c066ba752 sage/rings/qqbar.py
    a b  
    375375    R.<x> = QQbar[]
    376376    v1 = AA(2)
    377377    v2 = QQbar(sqrt(v1))
    378     v3 = sqrt(QQbar(3))
    379     v4 = v2*v3
    380     v5 = (1 - v2)*(1 - v3) - 1 - v4
    381     v6 = QQbar(sqrt(v1))
    382     si1 = v6*v3
    383     cp = AA.common_polynomial(x^2 + ((1 - v6)*(1 + v3) - 1 + si1)*x - si1)
    384     v7 = QQbar.polynomial_root(cp, RIF(-RR(1.7320508075688774), -RR(1.7320508075688772)))
    385     v8 = 1 - v7
    386     v9 = v5 + (v8 - 1)
    387     v10 = -1 - v3 - QQbar.polynomial_root(cp, RIF(-RR(1.7320508075688774), -RR(1.7320508075688772)))
    388     v11 = 1 + v10
    389     v12 = v8*(v5 + v4) - (v5 - v4*v7)
    390     si2 = v4*v7
    391     AA.polynomial_root(AA.common_polynomial(x^4 + (v9 + (v11 - 1))*x^3 + (v12 + (v11*v9 - v9))*x^2 + (v11*(v12 - si2) - (v12 - si2*v10))*x - si2*v10), RIF(RR(0.99999999999999989), RR(1.0000000000000002)))
     378    v3 = QQbar(3)
     379    v4 = sqrt(v3)
     380    v5 = v2*v4
     381    v6 = (1 - v2)*(1 - v4) - 1 - v5
     382    v7 = QQbar(sqrt(v1))
     383    v8 = sqrt(v3)
     384    si1 = v7*v8
     385    cp = AA.common_polynomial(x^2 + ((1 - v7)*(1 + v8) - 1 + si1)*x - si1)
     386    v9 = QQbar.polynomial_root(cp, RIF(-RR(1.7320508075688774), -RR(1.7320508075688772)))
     387    v10 = 1 - v9
     388    v11 = v6 + (v10 - 1)
     389    v12 = -1 - v4 - QQbar.polynomial_root(cp, RIF(-RR(1.7320508075688774), -RR(1.7320508075688772)))
     390    v13 = 1 + v12
     391    v14 = v10*(v6 + v5) - (v6 - v5*v9)
     392    si2 = v5*v9
     393    AA.polynomial_root(AA.common_polynomial(x^4 + (v11 + (v13 - 1))*x^3 + (v14 + (v13*v11 - v11))*x^2 + (v13*(v14 - si2) - (v14 - si2*v12))*x - si2*v12), RIF(RR(0.99999999999999989), RR(1.0000000000000002)))
    392394    sage: one
    393395    1
    394396
  • sage/rings/ring.pyx

    diff -r 216c066ba752 sage/rings/ring.pyx
    a b  
    361361                break
    362362
    363363        if len(gens) == 0:
    364             gens = [self(0)]
     364            gens = [self.zero_element()]
    365365
    366366        if coerce:
    367367            #print [type(g) for g in gens]
     
    492492            True
    493493        """
    494494        if self._zero_ideal is None:
    495             I = Ring.ideal(self, [self(0)], coerce=False)
     495            I = Ring.ideal(self, [self.zero_element()], coerce=False)
    496496            self._zero_ideal = I
    497497            return I
    498498        return self._zero_ideal
  • sage/schemes/elliptic_curves/monsky_washnitzer.py

    diff -r 216c066ba752 sage/schemes/elliptic_curves/monsky_washnitzer.py
    a b  
    13871387        answer mod `p^{\mathrm{prec}}` at the end.
    13881388 
    13891389 
    1390   OUTPUT: 2x2 matrix of frobenius on Monsky-Washnitzer cohomology,
     1390  OUTPUT:
     1391
     1392  2x2 matrix of frobenius on Monsky-Washnitzer cohomology,
    13911393  with entries in the coefficient ring of Q.
    13921394 
    1393   EXAMPLES: A simple example::
     1395  EXAMPLES:
     1396
     1397  A simple example::
    13941398 
    13951399      sage: p = 5
    13961400      sage: prec = 3
  • sage/schemes/hyperelliptic_curves/hyperelliptic_padic_field.py

    diff -r 216c066ba752 sage/schemes/hyperelliptic_curves/hyperelliptic_padic_field.py
    a b  
    3535       
    3636
    3737        INPUT:
    38             - P and Q points on self in the same residue disc
     38
     39        - P and Q points on self in the same residue disc
    3940       
    4041        OUTPUT:
    41             Returns a point $X(t) = ( x(t) : y(t) : z(t) )$ such that
     42       
     43        Returns a point $X(t) = ( x(t) : y(t) : z(t) )$ such that
     44
    4245            (1) $X(0) = P$ and $X(1) = Q$ if $P, Q$ are not in the infinite disc
    4346            (2) $X(P[0]^g}/P[1]) = P$ and $X(Q[0]^g/Q[1]) = Q$ if $P, Q$ are in the infinite disc
    4447       
    45         EXAMPLES:
     48        EXAMPLES::
     49
    4650            sage: R.<x> = QQ['x']   
    4751            sage: H = HyperellipticCurve(x^3-10*x+9)
    4852            sage: K = Qp(5,8)
    4953            sage: HK = H.change_ring(K)
    5054
    51         A non-Weierstrass disc:
     55        A non-Weierstrass disc::
     56
    5257            sage: P = HK(0,3)
    5358            sage: Q = HK(5, 3 + 3*5^2 + 2*5^3 + 3*5^4 + 2*5^5 + 2*5^6 + 3*5^7 + O(5^8))
    5459            sage: x,y,z, = HK.local_analytic_interpolation(P,Q)
    5560            sage: x(0) == P[0], x(1) == Q[0], y(0) == P[1], y(1) == Q[1]
    5661            (True, True, True, True)
    5762           
    58         A finite Weierstrass disc
     63        A finite Weierstrass disc::
     64
    5965            sage: P = HK.lift_x(1 + 2*5^2)
    6066            sage: Q = HK.lift_x(1 + 3*5^2)
    6167            sage: x,y,z = HK.local_analytic_interpolation(P,Q)
    6268            sage: x(0) == P[0], x(1) == Q[0], y(0) == P[1], y(1) == Q[1]
    6369            (True, True, True, True)
    6470
    65         The infinite disc
     71        The infinite disc::
     72
    6673            sage: P = HK.lift_x(5^-2)
    6774            sage: Q = HK.lift_x(4*5^-2)
    6875            sage: x,y,z = HK.local_analytic_interpolation(P,Q)
     
    7784            sage: y(Q[0]/Q[1]) == Q[1]
    7885            True
    7986
    80         An error if points are not in the same disc:
     87        An error if points are not in the same disc::
     88
    8189            sage: x,y,z = HK.local_analytic_interpolation(P,HK(1,0))
    8290            Traceback (most recent call last):
    8391            ...
    8492            ValueError: (5^-2 + O(5^6) : 5^-3 + 4*5^2 + 5^3 + 3*5^4 + O(5^5) : 1 + O(5^8)) and (1 + O(5^8) : 0 : 1 + O(5^8)) are not in the same residue disc
    8593           
    8694        AUTHORS:
    87             - Robert Bradshaw (2007-03)
    88             - Jennifer Balakrishnan (2010-02)
     95
     96        - Robert Bradshaw (2007-03)
     97        - Jennifer Balakrishnan (2010-02)
    8998        """
    9099        prec = self.base_ring().precision_cap()
    91100        if self.is_same_disc(P,Q) == False:
     
    118127        that is, the point at infinity and those points in the suport
    119128        of the divisor of $y$
    120129
    121         EXAMPLES:
     130        EXAMPLES::
     131
    122132            sage: K = pAdicField(11, 5)
    123133            sage: x = polygen(K)             
    124134            sage: C = HyperellipticCurve(x^5 + 33/16*x^4 + 3/4*x^3 + 3/8*x^2 - 1/4*x + 1/16)
     
    134144        """
    135145        Checks if $P$ is in a Weierstrass disc
    136146
    137         EXAMPLES:
     147        EXAMPLES::
     148
    138149            sage: R.<x> = QQ['x']
    139150            sage: H = HyperellipticCurve(x^3-10*x+9)
    140151            sage: K = Qp(5,8)
     
    154165            True
    155166
    156167        AUTHOR:
    157             - Jennifer Balakrishnan (2010-02)
     168
     169        - Jennifer Balakrishnan (2010-02)
    158170        """
    159171        if (P[1].valuation() == 0 and P != self(0,1,0)):
    160172            return False
     
    165177        """
    166178        Checks if $P$ is a Weierstrass point (i.e., fixed by the hyperelliptic involution)
    167179       
    168         EXAMPLES:
     180        EXAMPLES::
     181
    169182            sage: R.<x> = QQ['x']
    170183            sage: H = HyperellipticCurve(x^3-10*x+9)
    171184            sage: K = Qp(5,8)
     
    185198            False
    186199
    187200        AUTHOR:
    188             - Jennifer Balakrishnan (2010-02)
     201
     202        - Jennifer Balakrishnan (2010-02)
    189203
    190204        """
    191205        if (P[1] == 0 or P[2] ==0):
     
    198212        Given $Q$ a point on self in a Weierstrass disc, finds the
    199213        center of the Weierstrass disc (if defined over self.base_ring())
    200214       
    201         EXAMPLES:
     215        EXAMPLES::
     216
    202217            sage: R.<x> = QQ['x']
    203218            sage: H = HyperellipticCurve(x^3-10*x+9)
    204219            sage: K = Qp(5,8)
     
    217232            (0 : 1 + O(5^8) : 0)
    218233       
    219234        AUTHOR:
    220             - Jennifer Balakrishnan
     235
     236        - Jennifer Balakrishnan
    221237        """
    222238        if self.is_in_weierstrass_disc(Q) == False:
    223239            raise ValueError, "%s is not in a Weierstrass disc"%Q
     
    230246        """
    231247        Gives the residue disc of $P$
    232248       
    233         EXAMPLES:
     249        EXAMPLES::
     250
    234251            sage: R.<x> = QQ['x']       
    235252            sage: H = HyperellipticCurve(x^3-10*x+9)
    236253            sage: K = Qp(5,8)
     
    249266            (0 : 1 : 0)
    250267       
    251268        AUTHOR:
    252            - Jennifer Balakrishnan
     269
     270        - Jennifer Balakrishnan
    253271        """
    254272        xPv = P[0].valuation()
    255273        yPv = P[1].valuation()
     
    274292        """
    275293        Checks if $P,Q$ are in same residue disc
    276294       
    277         EXAMPLES:
     295        EXAMPLES::
     296
    278297            sage: R.<x> = QQ['x']
    279298            sage: H = HyperellipticCurve(x^3-10*x+9)
    280299            sage: K = Qp(5,8)
     
    295314            return False
    296315           
    297316    def tiny_integrals(self, F, P, Q):
    298         """
     317        r"""
    299318        Evaluate the integrals of $f_i dx/2y$ from $P$ to $Q$ for each $f_i$ in $F$
    300319        by formally integrating a power series in a local parameter $t$
    301320       
    302321        $P$ and $Q$ MUST be in the same residue disk for this result to make sense.
    303322
    304323        INPUT:
    305             - F a list of functions $f_i$
    306             - P a point on self
    307             - Q a point on self (in the same residue disc as P)
     324
     325        - F a list of functions $f_i$
     326        - P a point on self
     327        - Q a point on self (in the same residue disc as P)
    308328
    309329        OUTPUT:
    310             The integrals $\int_P^Q f_i dx/2y$
    311330
    312         EXAMPLES:
     331        The integrals $\int_P^Q f_i dx/2y$
     332
     333        EXAMPLES::
     334
    313335            sage: K = pAdicField(17, 5)
    314336            sage: E = EllipticCurve(K, [-31/3, -2501/108]) # 11a
    315337            sage: P = E(K(14/3), K(11/2))
     
    318340            sage: E.tiny_integrals([1,x],P, TP) == E.tiny_integrals_on_basis(P,TP)
    319341            True
    320342
     343        ::
     344
    321345            sage: K = pAdicField(11, 5)
    322346            sage: x = polygen(K)
    323347            sage: C = HyperellipticCurve(x^5 + 33/16*x^4 + 3/4*x^3 + 3/8*x^2 - 1/4*x + 1/16)
     
    326350            sage: C.tiny_integrals([1],P,Q)
    327351            (3*11^3 + 7*11^4 + 4*11^5 + 7*11^6 + 5*11^7 + O(11^8))
    328352
    329         Note that this fails if the points are not in the same residue disc:
     353        Note that this fails if the points are not in the same residue disc::
     354
    330355            sage: S = C(0,1/4)
    331356            sage: C.tiny_integrals([1,x,x^2,x^3],P,S)
    332357            Traceback (most recent call last):
     
    354379        return vector(integrals)
    355380       
    356381    def tiny_integrals_on_basis(self, P, Q):
    357         """
     382        r"""
    358383        Evaluate the integrals $\{\int_P^Q x^i dx/2y \}_{i=0}^{2g-1}$
    359384        by formally integrating a power series in a local parameter $t$.
    360385        $P$ and $Q$ MUST be in the same residue disc for this result to make sense.
    361386
    362387        INPUT:
    363             - P a point on self
    364             - Q a point on self (in the same residue disc as P)
     388
     389        - P a point on self
     390        - Q a point on self (in the same residue disc as P)
    365391
    366392        OUTPUT:
    367             The integrals $\{\int_P^Q x^i dx/2y \}_{i=0}^{2g-1}$
    368393
    369         EXAMPLES:
     394        The integrals $\{\int_P^Q x^i dx/2y \}_{i=0}^{2g-1}$
     395
     396        EXAMPLES::
     397
    370398            sage: K = pAdicField(17, 5)
    371399            sage: E = EllipticCurve(K, [-31/3, -2501/108]) # 11a
    372400            sage: P = E(K(14/3), K(11/2))
    373401            sage: TP = E.teichmuller(P);
    374402            sage: E.tiny_integrals_on_basis(P, TP)
    375403            (17 + 14*17^2 + 17^3 + 8*17^4 + O(17^5), 16*17 + 5*17^2 + 8*17^3 + 14*17^4 + O(17^5))
     404
     405        ::
    376406           
    377407            sage: K = pAdicField(11, 5)
    378408            sage: x = polygen(K)
     
    383413            (3*11^3 + 7*11^4 + 4*11^5 + 7*11^6 + 5*11^7 + O(11^8), 3*11 + 10*11^2 + 8*11^3 + 9*11^4 + 7*11^5 + O(11^6), 4*11^-1 + 2 + 6*11 + 6*11^2 + 7*11^3 + O(11^4), 11^-3 + 6*11^-2 + 2*11^-1 + 2 + O(11^2))
    384414           
    385415           
    386         Note that this fails if the points are not in the same residue disc:
     416        Note that this fails if the points are not in the same residue disc::
     417
    387418            sage: S = C(0,1/4)
    388419            sage: C.tiny_integrals_on_basis(P,S)
    389420            Traceback (most recent call last):
     
    400431
    401432               
    402433    def teichmuller(self, P):
    403         """
     434        r"""
    404435        Find a Teichm\:uller point in the same residue class of $P$.
    405436       
    406437        Because this lift of frobenius acts as $x \mapsto x^p$, 
    407438        take the Teichmuller lift of $x$ and then find a matching $y$
    408439        from that.
    409440       
    410         EXAMPLES:
     441        EXAMPLES::
     442
    411443            sage: K = pAdicField(7, 5)
    412444            sage: E = EllipticCurve(K, [-31/3, -2501/108]) # 11a
    413445            sage: P = E(K(14/3), K(11/2))
     
    431463       
    432464                   
    433465    def coleman_integrals_on_basis(self, P, Q, algorithm=None):
    434         """
     466        r"""
    435467        Computes the Coleman integrals $\{\int_P^Q x^i dx/2y \}_{i=0}^{2g-1}$ 
    436468
    437469        INPUT:
    438             - P point on self
    439             - Q point on self
    440             - algorithm (optional) = None (uses Frobenius) or teichmuller (uses Teichmuller points)
     470
     471        - P point on self
     472        - Q point on self
     473        - algorithm (optional) = None (uses Frobenius) or teichmuller (uses Teichmuller points)
    441474
    442475        OUTPUT:
    443             the Coleman integrals $\{\int_P^Q x^i dx/2y \}_{i=0}^{2g-1}$ 
     476
     477        the Coleman integrals $\{\int_P^Q x^i dx/2y \}_{i=0}^{2g-1}$ 
    444478                               
    445         EXAMPLES:
     479        EXAMPLES::
     480
    446481            sage: K = pAdicField(11, 5)
    447482            sage: x = polygen(K)
    448483            sage: C = HyperellipticCurve(x^5 + 33/16*x^4 + 3/4*x^3 + 3/8*x^2 - 1/4*x + 1/16)
     
    453488            sage: C.coleman_integrals_on_basis(P, Q, algorithm='teichmuller')
    454489            (10*11 + 6*11^3 + 2*11^4 + O(11^5), 11 + 9*11^2 + 7*11^3 + 9*11^4 + O(11^5), 3 + 10*11 + 5*11^2 + 9*11^3 + 4*11^4 + O(11^5), 3 + 11 + 5*11^2 + 4*11^4 + O(11^5))
    455490
     491        ::
     492
    456493            sage: K = pAdicField(11,5)
    457494            sage: x = polygen(K)
    458495            sage: C = HyperellipticCurve(x^5 + 33/16*x^4 + 3/4*x^3 + 3/8*x^2 - 1/4*x + 1/16)
     
    460497            sage: Q = C.lift_x(3*11^(-2))
    461498            sage: C.coleman_integrals_on_basis(P, Q)
    462499            (3*11^3 + 7*11^4 + 4*11^5 + 7*11^6 + 5*11^7 + O(11^8), 3*11 + 10*11^2 + 8*11^3 + 9*11^4 + 7*11^5 + O(11^6), 4*11^-1 + 2 + 6*11 + 6*11^2 + 7*11^3 + O(11^4), 11^-3 + 6*11^-2 + 2*11^-1 + 2 + O(11^2))
    463            
     500
     501        ::
     502
    464503            sage: R = C(0,1/4)
    465504            sage: a = C.coleman_integrals_on_basis(P,R)  # long time (7s on sage.math, 2011)
    466505            sage: b = C.coleman_integrals_on_basis(R,Q)  # long time (9s on sage.math, 2011)
     
    468507            sage: a+b == c  # long time
    469508            True
    470509
     510        ::
     511
    471512            sage: R.<x> = QQ['x']
    472513            sage: H = HyperellipticCurve(x^3-10*x+9)
    473514            sage: K = Qp(5,8)
     
    495536            (0, 0)
    496537           
    497538        AUTHORS:
    498             - Robert Bradshaw (2007-03): non-Weierstrass points
    499             - Jennifer Balakrishnan and Robert Bradshaw (2010-02): Weierstrass points
     539
     540        - Robert Bradshaw (2007-03): non-Weierstrass points
     541        - Jennifer Balakrishnan and Robert Bradshaw (2010-02): Weierstrass points
    500542        """
    501543        import sage.schemes.elliptic_curves.monsky_washnitzer as monsky_washnitzer
    502544        from sage.misc.profiler import Profiler
     
    623665        """
    624666        Returns the invariant differential $dx/2y$ on self
    625667
    626         EXAMPLES:
     668        EXAMPLES::
     669
    627670            sage: R.<x> = QQ['x']
    628671            sage: H = HyperellipticCurve(x^3+1)
    629672            sage: K = Qp(5,8)
     
    631674            sage: w = HK.invariant_differential(); w
    632675            (((1+O(5^8)))*1) dx/2y
    633676
     677        ::
     678
    634679            sage: K = pAdicField(11, 6)
    635680            sage: x = polygen(K)
    636681            sage: C = HyperellipticCurve(x^5 + 33/16*x^4 + 3/4*x^3 + 3/8*x^2 - 1/4*x + 1/16)
     
    644689        return MW.invariant_differential()
    645690       
    646691    def coleman_integral(self, w, P, Q, algorithm = 'None'):
    647         """
     692        r"""
    648693        Returns the Coleman integral $\int_P^Q w$
    649694       
    650695        INPUT:
    651             - w differential (if one of P,Q is Weierstrass, w must be odd)
    652             - P point on self
    653             - Q point on self
    654             - algorithm (optional) = None (uses Frobenius) or teichmuller (uses Teichmuller points)
     696
     697        - w differential (if one of P,Q is Weierstrass, w must be odd)
     698        - P point on self
     699        - Q point on self
     700        - algorithm (optional) = None (uses Frobenius) or teichmuller (uses Teichmuller points)
    655701
    656702        OUTPUT:
    657             the Coleman integral $\int_P^Q w$
     703
     704        the Coleman integral $\int_P^Q w$
    658705
    659706        EXAMPLES:
     707
    660708        Example of Leprevost from Kiran Kedlaya
    661709        The first two should be zero as $(P-Q) = 30(P-Q)$ in the Jacobian
    662         and $dx/2y$ and $x dx/2y$ are holomorphic.
     710        and $dx/2y$ and $x dx/2y$ are holomorphic.
     711        ::
    663712       
    664713            sage: K = pAdicField(11, 6)
    665714            sage: x = polygen(K)
     
    674723            O(11^6)
    675724            sage: C.coleman_integral(x^2*w, P, Q)
    676725            7*11 + 6*11^2 + 3*11^3 + 11^4 + 5*11^5 + O(11^6)
    677        
     726
     727        ::
     728
    678729            sage: p = 71; m = 4
    679730            sage: K = pAdicField(p, m)
    680731            sage: x = polygen(K)
     
    690741            21*71 + 67*71^2 + 27*71^3 + O(71^4)
    691742            sage: w.integrate(P, R) + w.integrate(P1, R1)
    692743            O(71^4)
    693        
    694         A simple example, integrating dx:
    695    
     744
     745        A simple example, integrating dx::
     746
    696747            sage: R.<x> = QQ['x']
    697748            sage: E= HyperellipticCurve(x^3-4*x+4)
    698749            sage: K = Qp(5,10)
     
    704755            5 + 2*5^2 + 5^3 + 3*5^4 + 4*5^5 + 2*5^6 + 3*5^7 + 3*5^9 + O(5^10)
    705756            sage: Q[0] - P[0]
    706757            5 + 2*5^2 + 5^3 + 3*5^4 + 4*5^5 + 2*5^6 + 3*5^7 + 3*5^9 + O(5^10)
    707        
    708         Yet another example:
     758
     759        Yet another example::
    709760
    710761            sage: R.<x> = QQ['x']
    711762            sage: H = HyperellipticCurve(x*(x-1)*(x+9))
     
    723774            sage: HK.coleman_integral(b,P,Q)
    724775            7 + 7^2 + 4*7^3 + 5*7^4 + 3*7^5 + 7^6 + 5*7^7 + 3*7^8 + 4*7^9 + 4*7^10 + O(7^11)
    725776
     777        ::
     778
    726779            sage: R.<x> = QQ['x']
    727780            sage: H = HyperellipticCurve(x^3+1)
    728781            sage: K = Qp(5,8)
     
    739792            3*5 + 2*5^2 + 2*5^3 + 5^4 + 4*5^6 + 5^7 + O(5^9)
    740793            sage: HK.coleman_integral(w,P,Q)
    741794            3*5 + 2*5^2 + 2*5^3 + 5^4 + 4*5^6 + 5^7 + O(5^9)     
    742        
    743         Integrals involving Weierstrass points:
     795
     796        Integrals involving Weierstrass points::
    744797
    745798            sage: R.<x> = QQ['x']
    746799            sage: H = HyperellipticCurve(x^3-10*x+9)
     
    770823            5^2 + 4*5^3 + 2*5^4 + 2*5^5 + 3*5^6 + 2*5^7 + 4*5^8 + O(5^9)
    771824
    772825        AUTHORS:
    773             - Robert Bradshaw (2007-03)
    774             - Kiran Kedlaya (2008-05)
    775             - Jennifer Balakrishnan (2010-02)
     826
     827        - Robert Bradshaw (2007-03)
     828        - Kiran Kedlaya (2008-05)
     829        - Jennifer Balakrishnan (2010-02)
    776830
    777831        """
    778832        # TODO: implement Jacobians and show the relationship directly
     
    810864        """
    811865        Returns the $p$-th power lift of Frobenius of $P$
    812866
    813         EXAMPLES:
     867        EXAMPLES::
     868
    814869            sage: K = Qp(11, 5)
    815870            sage: R.<x> = K[]
    816871            sage: E = HyperellipticCurve(x^5 - 21*x - 20)
    817872            sage: P = E.lift_x(2)
    818873            sage: E.frobenius(P)
    819874            (2 + 10*11 + 5*11^2 + 11^3 + O(11^5) : 5 + 9*11 + 2*11^2 + 2*11^3 + O(11^5) : 1 + O(11^5))
    820 
    821875            sage: Q = E.teichmuller(P); Q
    822876            (2 + 10*11 + 4*11^2 + 9*11^3 + 11^4 + O(11^5) : 5 + 9*11 + 6*11^2 + 11^3 + 6*11^4 + O(11^5) : 1 + O(11^5))
    823877            sage: E.frobenius(Q)
    824878            (2 + 10*11 + 4*11^2 + 9*11^3 + 11^4 + O(11^5) : 5 + 9*11 + 6*11^2 + 11^3 + 6*11^4 + O(11^5) : 1 + O(11^5))
    825879
     880        ::
     881
    826882            sage: R.<x> = QQ[]
    827883            sage: H = HyperellipticCurve(x^5-23*x^3+18*x^2+40*x)
    828884            sage: Q = H(0,0)
     
    845901            1 + O(a^100))
    846902
    847903        AUTHORS:
    848             - Robert Bradshaw and Jennifer Balakrishnan (2010-02)
     904
     905        - Robert Bradshaw and Jennifer Balakrishnan (2010-02)
    849906        """
    850907        try:
    851908            _frob = self._frob
     
    895952            return _frob(P)
    896953   
    897954    def newton_sqrt(self,f,x0, prec):
    898         """
    899         NOTE: this function should eventually be moved to $p$-adic power series ring
     955        r"""
     956        Takes the square root of the power series $f$ by Newton's method
     957
     958        NOTE:
     959
     960        this function should eventually be moved to $p$-adic power series ring
    900961       
    901         takes the square root of the power series $f$ by Newton's method
    902962       
    903963        INPUT:
    904             - f power series wtih coefficients in $\Q_p$ or an extension
    905             - x0 seeds the Newton iteration
    906             - prec precision
     964
     965        - f power series wtih coefficients in $\Q_p$ or an extension
     966        - x0 seeds the Newton iteration
     967        - prec precision
    907968
    908969        OUTPUT:
    909             the square root of $f$
    910970
    911         EXAMPLES:
     971        the square root of $f$
     972
     973        EXAMPLES::
     974
    912975            sage: R.<x> = QQ['x']
    913976            sage: H = HyperellipticCurve(x^5-23*x^3+18*x^2+40*x)
    914977            sage: Q = H(0,0)
     
    924987            O(a^122)
    925988
    926989        AUTHOR:
    927             - Jennifer Balakrishnan
     990
     991        - Jennifer Balakrishnan
    928992
    929993        """
    930994        z = x0
     
    9451009            return z
    9461010   
    9471011    def curve_over_ram_extn(self,deg):
    948         """
     1012        r"""
    9491013        Returns self over $\Q_p(p^(1/deg))$
    9501014       
    9511015        INPUT:
    952             - deg: the degree of the ramified extension
     1016
     1017        - deg: the degree of the ramified extension
    9531018       
    9541019        OUTPUT:
    955             self over $\Q_p(p^(1/deg))$
    9561020
    957         EXAMPLES:
     1021        self over $\Q_p(p^(1/deg))$
     1022
     1023        EXAMPLES::
     1024
    9581025            sage: R.<x> = QQ['x']
    9591026            sage: H = HyperellipticCurve(x^5-23*x^3+18*x^2+40*x)
    9601027            sage: K = Qp(11,5)
     
    9641031            Hyperelliptic Curve over Eisenstein Extension of 11-adic Field with capped relative precision 5 in a defined by (1 + O(11^5))*x^2 + (O(11^6))*x + (10*11 + 10*11^2 + 10*11^3 + 10*11^4 + 10*11^5 + O(11^6)) defined by (1 + O(a^10))*y^2 = (1 + O(a^10))*x^5 + (10 + 8*a^2 + 10*a^4 + 10*a^6 + 10*a^8 + O(a^10))*x^3 + (7 + a^2 + O(a^10))*x^2 + (7 + 3*a^2 + O(a^10))*x
    9651032       
    9661033        AUTHOR:
    967             - Jennifer Balakrishnan
     1034
     1035        - Jennifer Balakrishnan
    9681036           
    9691037        """
    9701038        from sage.schemes.hyperelliptic_curves.constructor import HyperellipticCurve
     
    9851053        Given self over an extension field, find a point in the disc of $P$ near the boundary
    9861054       
    9871055        INPUT:
    988              - curve_over_extn: self over a totally ramified extension
    989              - P: Weierstrass point
     1056
     1057        - curve_over_extn: self over a totally ramified extension
     1058        - P: Weierstrass point
    9901059       
    9911060        OUTPUT:
    992             a point in the disc of $P$ near the boundary
     1061
     1062        a point in the disc of $P$ near the boundary
    9931063       
    994         EXAMPLES:
     1064        EXAMPLES::
     1065
    9951066            sage: R.<x> = QQ['x']
    9961067            sage: H = HyperellipticCurve(x^3-10*x+9)
    9971068            sage: K = Qp(3,6)
     
    10041075            (1 + 2*a^2 + 2*a^6 + 2*a^18 + a^32 + a^34 + a^36 + 2*a^38 + 2*a^40 + a^42 + 2*a^44 + a^48 + 2*a^50 + 2*a^52 + a^54 + a^56 + 2*a^60 + 2*a^62 + a^70 + 2*a^72 + a^76 + 2*a^78 + a^82 + a^88 + a^96 + 2*a^98 + 2*a^102 + a^104 + 2*a^106 + a^108 + 2*a^110 + a^112 + 2*a^116 + a^126 + 2*a^130 + 2*a^132 + a^144 + 2*a^148 + 2*a^150 + a^152 + 2*a^154 + a^162 + a^164 + a^166 + a^168 + a^170 + a^176 + a^178 + O(a^180) : a + O(a^181) : 1 + O(a^180))
    10051076       
    10061077        AUTHOR:
    1007             - Jennifer Balakrishnan
     1078
     1079        - Jennifer Balakrishnan
    10081080       
    10091081        """
    10101082        J = curve_over_extn.base_ring()
     
    10141086        return curve_over_extn(x(a),y(a))
    10151087
    10161088    def P_to_S(self, P, S):
    1017         """
     1089        r"""
    10181090        Given a finite Weierstrass point $P$ and a point $S$
    10191091        in the same disc, computes the Coleman integrals $\{\int_P^S x^i dx/2y \}_{i=0}^{2g-1}$ 
    10201092       
    10211093        INPUT:
    1022             - P: finite Weierstrass point
    1023             - S: point in disc of P
     1094
     1095        - P: finite Weierstrass point
     1096        - S: point in disc of P
    10241097       
    10251098        OUTPUT:
    1026             Coleman integrals $\{\int_P^S x^i dx/2y \}_{i=0}^{2g-1}$       
     1099
     1100        Coleman integrals $\{\int_P^S x^i dx/2y \}_{i=0}^{2g-1}$       
    10271101       
    1028         EXAMPLES:
     1102        EXAMPLES::
     1103
    10291104            sage: R.<x> = QQ['x']
    10301105            sage: H = HyperellipticCurve(x^3-10*x+9)
    10311106            sage: K = Qp(5,4)
     
    10371112            (2*a + 4*a^3 + 2*a^11 + 4*a^13 + 2*a^17 + 2*a^19 + a^21 + 4*a^23 + a^25 + 2*a^27 + 2*a^29 + 3*a^31 + 4*a^33 + O(a^35), a^-5 + 2*a + 2*a^3 + a^7 + 3*a^11 + a^13 + 3*a^15 + 3*a^17 + 2*a^19 + 4*a^21 + 4*a^23 + 4*a^25 + 2*a^27 + a^29 + a^31 + 3*a^33 + O(a^35))
    10381113
    10391114        AUTHOR:
    1040             - Jennifer Balakrishnan
     1115
     1116        - Jennifer Balakrishnan
    10411117       
    10421118        """
    10431119        prec = self.base_ring().precision_cap()
     
    10501126        return vector(val)
    10511127
    10521128    def coleman_integral_P_to_S(self,w,P,S):
    1053         """
     1129        r"""
    10541130        Given a finite Weierstrass point $P$ and a point $S$
    10551131        in the same disc, computes the Coleman integral $\int_P^S w$
    10561132       
    10571133        INPUT:
    1058             - w: differential
    1059             - P: Weierstrass point
    1060             - S: point in the same disc of P (S is defined over an extension of $\Q_p$; coordinates
    1061                  of S are given in terms of uniformizer $a$)
     1134
     1135        - w: differential
     1136        - P: Weierstrass point
     1137        - S: point in the same disc of P (S is defined over an extension of $\Q_p$; coordinates
     1138          of S are given in terms of uniformizer $a$)
    10621139       
    10631140        OUTPUT:
    1064             Coleman integral $\int_P^S w$ in terms of $a$
     1141
     1142        Coleman integral $\int_P^S w$ in terms of $a$
    10651143       
    1066         EXAMPLES:
     1144        EXAMPLES::
     1145
    10671146            sage: R.<x> = QQ['x']
    10681147            sage: H = HyperellipticCurve(x^3-10*x+9)
    10691148            sage: K = Qp(5,4)
     
    10791158            True
    10801159       
    10811160        AUTHOR:
    1082             - Jennifer Balakrishnan
     1161
     1162        - Jennifer Balakrishnan
    10831163       
    10841164        """
    10851165        prec = self.base_ring().precision_cap()
     
    10921172        return int_sing_a
    10931173
    10941174    def S_to_Q(self,S,Q):
    1095         """
     1175        r"""
    10961176        Given $S$ a point on self over an extension field, computes the
    10971177        Coleman integrals $\{\int_S^Q x^i dx/2y \}_{i=0}^{2g-1}$       
    10981178
    10991179        **one should be able to feed $S,Q$ into coleman_integral,
    1100         but currently that segfaults
     1180        but currently that segfaults**
    11011181       
    11021182        INPUT:
    1103             - S: a point with coordinates in an extension of $\Q_p$ (with unif. a)
    1104             - Q: a non-Weierstrass point defined over $\Q_p$
     1183
     1184        - S: a point with coordinates in an extension of $\Q_p$ (with unif. a)
     1185        - Q: a non-Weierstrass point defined over $\Q_p$
    11051186       
    11061187        OUTPUT:
    1107             the Coleman integrals $\{\int_S^Q x^i dx/2y \}_{i=0}^{2g-1}$ in terms of $a$
     1188
     1189        the Coleman integrals $\{\int_S^Q x^i dx/2y \}_{i=0}^{2g-1}$ in terms of $a$
    11081190       
    1109         EXAMPLES:
     1191        EXAMPLES::
     1192
    11101193            sage: R.<x> = QQ['x']
    11111194            sage: H = HyperellipticCurve(x^3-10*x+9)
    11121195            sage: K = Qp(5,6)
     
    11261209            (2*5^2 + 5^4 + 5^5 + 3*5^6 + O(5^7), 5 + 2*5^2 + 4*5^3 + 2*5^4 + 5^6 + O(5^7))
    11271210       
    11281211        AUTHOR:
    1129             - Jennifer Balakrishnan
     1212
     1213        - Jennifer Balakrishnan
    11301214       
    11311215        """
    11321216        FS = self.frobenius(S)
     
    11741258        return B*(b-S_to_FS-FQ_to_Q)
    11751259                         
    11761260    def coleman_integral_S_to_Q(self,w,S,Q):
    1177         """           
     1261        r"""           
    11781262        Computes the Coleman integral $\int_S^Q w$
    11791263
    11801264        **one should be able to feed $S,Q$ into coleman_integral,
    1181         but currently that segfaults
     1265        but currently that segfaults**
    11821266
    11831267        INPUT:
    1184             - w: a differential
    1185             - S: a point with coordinates in an extension of \Q_p
    1186             - Q: a non-Weierstrass point defined over \Q_p
     1268
     1269        - w: a differential
     1270        - S: a point with coordinates in an extension of $\Q_p$
     1271        - Q: a non-Weierstrass point defined over $\Q_p$
    11871272
    11881273        OUTPUT:
    1189             the Coleman integral $\int_S^Q w$
    11901274
    1191         EXAMPLES:
     1275        the Coleman integral $\int_S^Q w$
     1276
     1277        EXAMPLES::
     1278
    11921279            sage: R.<x> = QQ['x']
    11931280            sage: H = HyperellipticCurve(x^3-10*x+9)
    11941281            sage: K = Qp(5,6)
     
    12071294            3 + O(5^6)
    12081295       
    12091296        AUTHOR:
    1210             - Jennifer Balakrishnan
     1297
     1298        - Jennifer Balakrishnan
    12111299           
    12121300        """
    12131301        import sage.schemes.elliptic_curves.monsky_washnitzer as monsky_washnitzer
     
    12271315            return const + dot
    12281316       
    12291317    def coleman_integral_from_weierstrass_via_boundary(self, w, P, Q, d):
    1230         """
     1318        r"""
    12311319        Computes the Coleman integral $\int_P^Q w$ via a boundary point
    12321320        in the disc of $P$, defined over a degree $d$ extension
    12331321
    12341322        INPUT:
    1235             - w: a differential
    1236             - P: a Weierstrass point
    1237             - Q: a non-Weierstrass point
    1238             - d: degree of extension where coordinates of boundary point lie
     1323
     1324        - w: a differential
     1325        - P: a Weierstrass point
     1326        - Q: a non-Weierstrass point
     1327        - d: degree of extension where coordinates of boundary point lie
    12391328
    12401329        OUTPUT:
    1241             the Coleman integral $\int_P^Q w$, written in terms of the uniformizer
    1242             $a$ of the degree $d$ extension
    12431330
    1244         EXAMPLES:
     1331        the Coleman integral $\int_P^Q w$, written in terms of the uniformizer
     1332        $a$ of the degree $d$ extension
     1333
     1334        EXAMPLES::
     1335
    12451336            sage: R.<x> = QQ['x']
    12461337            sage: H = HyperellipticCurve(x^3-10*x+9)
    12471338            sage: K = Qp(5,6)
     
    12601351            2*5^2 + 5^4 + 5^5 + 3*5^6 + O(5^7)
    12611352       
    12621353        AUTHOR:
    1263             - Jennifer Balakrishnan
     1354
     1355        - Jennifer Balakrishnan
    12641356
    12651357        """
    12661358        HJ = self.curve_over_ram_extn(d)
  • sage/structure/coerce.pyx

    diff -r 216c066ba752 sage/structure/coerce.pyx
    a b  
    10991099            (Call morphism:
    11001100              From: Multivariate Polynomial Ring in x, y over Integer Ring
    11011101              To:   Multivariate Polynomial Ring in x, y over Real Double Field,
    1102              Call morphism:
     1102             Polynomial base injection morphism:
    11031103              From: Real Double Field
    11041104              To:   Multivariate Polynomial Ring in x, y over Real Double Field)
    11051105             
  • sage/structure/coerce_actions.pyx

    diff -r 216c066ba752 sage/structure/coerce_actions.pyx
    a b  
    226226            Left scalar multiplication by Rational Field on Univariate Polynomial Ring in x over Integer Ring
    227227            sage: LeftModuleAction(QQ, ZZ['x']['y'])
    228228            Left scalar multiplication by Rational Field on Univariate Polynomial Ring in y over Univariate Polynomial Ring in x over Integer Ring
     229
     230        The following tests against a problem that was relevant during work on
     231        trac ticket #9944::
     232
     233            sage: R.<x> = PolynomialRing(ZZ)
     234            sage: S.<x> = PolynomialRing(ZZ, sparse=True)
     235            sage: 1/R.0
     236            1/x
     237            sage: 1/S.0
     238            1/x
     239
    229240        """
    230241        Action.__init__(self, G, S, not PY_TYPE_CHECK(self, RightModuleAction), operator.mul)
    231242        if not isinstance(G, Parent):
     
    265276        # At this point, we can assert it is safe to call _Xmul_c
    266277        the_ring = G if self.connecting is None else self.connecting.codomain()
    267278        the_set = S if self.extended_base is None else self.extended_base
    268         assert the_ring is the_set.base(), "BUG in coercion model"
     279        assert the_ring is the_set.base(), "BUG in coercion model\n    Apparently there are two versions of\n        %s\n    in the cache."%the_ring
    269280
    270281        g = G.an_element()
    271282        a = S.an_element()
  • sage/structure/element.pyx

    diff -r 216c066ba752 sage/structure/element.pyx
    a b  
    766766            sage: (v+w).__nonzero__()
    767767            False
    768768        """
    769         return self != self._parent(0)
     769        return self != self._parent.zero_element()
    770770
    771771    def is_zero(self):
    772772        """
     
    12781278cdef class RingElement(ModuleElement):
    12791279    ##################################################
    12801280    def is_one(self):
    1281         return self == self._parent(1)
     1281        return self == self._parent.one_element()
    12821282
    12831283    ##################################
    12841284    # Fast long add/sub path.
  • sage/structure/parent_old.pyx

    diff -r 216c066ba752 sage/structure/parent_old.pyx
    a b  
    1010
    1111
    1212TESTS:
     13
    1314This came up in some subtle bug once.
     15::
     16
    1417    sage: gp(2) + gap(3)
    1518    5     
    1619"""
     
    102105              To:   Multivariate Polynomial Ring in q, t over Rational Field
    103106              Defn:   Native morphism:
    104107                      From: Set of Python objects of type 'int'
    105                       To:   Integer Ring
     108                      To:   Rational Field
    106109                    then
    107                       Call morphism:
    108                       From: Integer Ring
     110                      Polynomial base injection morphism:
     111                      From: Rational Field
    109112                      To:   Multivariate Polynomial Ring in q, t over Rational Field
    110113        """
    111114        check_old_coerce(self)