Ejemplo n.º 1
0
def _single_variate(base_ring, name, sparse, implementation):
    import sage.rings.polynomial.polynomial_ring as m
    name = normalize_names(1, name)
    key = (base_ring, name, sparse, implementation if not sparse else None)
    R = _get_from_cache(key)
    if not R is None:
        return R

    if isinstance(base_ring, ring.CommutativeRing):
        if is_IntegerModRing(base_ring) and not sparse:
            n = base_ring.order()
            if n.is_prime():
                R = m.PolynomialRing_dense_mod_p(base_ring,
                                                 name,
                                                 implementation=implementation)
            elif n > 1:
                R = m.PolynomialRing_dense_mod_n(base_ring,
                                                 name,
                                                 implementation=implementation)
            else:  # n == 1!
                R = m.PolynomialRing_integral_domain(
                    base_ring, name)  # specialized code breaks in this case.

        elif is_FiniteField(base_ring) and not sparse:
            R = m.PolynomialRing_dense_finite_field(
                base_ring, name, implementation=implementation)

        elif isinstance(base_ring, padic_base_leaves.pAdicFieldCappedRelative):
            R = m.PolynomialRing_dense_padic_field_capped_relative(
                base_ring, name)

        elif isinstance(base_ring, padic_base_leaves.pAdicRingCappedRelative):
            R = m.PolynomialRing_dense_padic_ring_capped_relative(
                base_ring, name)

        elif isinstance(base_ring, padic_base_leaves.pAdicRingCappedAbsolute):
            R = m.PolynomialRing_dense_padic_ring_capped_absolute(
                base_ring, name)

        elif isinstance(base_ring, padic_base_leaves.pAdicRingFixedMod):
            R = m.PolynomialRing_dense_padic_ring_fixed_mod(base_ring, name)

        elif base_ring.is_field(proof=False):
            R = m.PolynomialRing_field(base_ring, name, sparse)

        elif base_ring.is_integral_domain(proof=False):
            R = m.PolynomialRing_integral_domain(base_ring, name, sparse,
                                                 implementation)
        else:
            R = m.PolynomialRing_commutative(base_ring, name, sparse)
    else:
        R = m.PolynomialRing_general(base_ring, name, sparse)

    if hasattr(R, '_implementation_names'):
        for name in R._implementation_names:
            real_key = key[0:3] + (name, )
            _save_in_cache(real_key, R)
    else:
        _save_in_cache(key, R)
    return R
Ejemplo n.º 2
0
def _single_variate(base_ring, names, sparse):
    """
    EXAMPLES::

        sage: from sage.rings.polynomial.laurent_polynomial_ring import _single_variate
        sage: _single_variate(QQ, ('x',), False)
        Univariate Laurent Polynomial Ring in x over Rational Field
    """
    ############################################################
    # This should later get moved to an actual single variate  #
    # implementation with valuation tracking,                  #
    # but I don't want to right now.                           #
    ############################################################
    # We need to come up with a name for the inverse that is easy to search
    # for in a string *and* doesn't overlap with the name that we already have.
    # For now, I'm going to use a name mangling with checking method.
    names = normalize_names(1, names)
    key = (base_ring, names, sparse)
    P = _get_from_cache(key)
    if P is not None:
        return P
    prepend_string = "qk"
    while True:
        if prepend_string in names:
            prepend_string += 'k'
        else:
            break
    R = _multi_variate_poly(base_ring, names, 1, sparse, 'degrevlex', None)
    P = LaurentPolynomialRing_mpair(R, prepend_string, names)
    _save_in_cache(key, P)
    return P
Ejemplo n.º 3
0
    def create_key_and_extra_args(self,
                                  order,
                                  name=None,
                                  modulus=None,
                                  names=None,
                                  impl=None,
                                  proof=None,
                                  **kwds):
        """
        EXAMPLES::
        
            sage: GF.create_key_and_extra_args(9, 'a')
            ((9, ('a',), 'conway', None, '{}', 3, 2, True), {})
            sage: GF.create_key_and_extra_args(9, 'a', foo='value')
            ((9, ('a',), 'conway', None, "{'foo': 'value'}", 3, 2, True), {'foo': 'value'})
        """
        from sage.structure.proof.all import WithProof, arithmetic
        if proof is None: proof = arithmetic()
        with WithProof('arithmetic', proof):
            order = int(order)
            if order <= 1:
                raise ValueError("the order of a finite field must be > 1.")

            if arith.is_prime(order):
                name = None
                modulus = None
                p = integer.Integer(order)
                n = integer.Integer(1)
            elif arith.is_prime_power(order):
                if not names is None: name = names
                name = normalize_names(1, name)

                p, n = arith.factor(order)[0]

                if modulus is None or modulus == "default":
                    if exists_conway_polynomial(p, n):
                        modulus = "conway"
                    else:
                        if p == 2:
                            modulus = "minimal_weight"
                        else:
                            modulus = "random"
                elif modulus == "random":
                    modulus += str(random.randint(0, 1 << 128))

                if isinstance(modulus, (list, tuple)):
                    modulus = FiniteField(p)['x'](modulus)
                # some classes use 'random' as the modulus to
                # generate a random modulus, but we don't want
                # to cache it
                elif sage.rings.polynomial.polynomial_element.is_Polynomial(
                        modulus):
                    modulus = modulus.change_variable_name('x')
                elif not isinstance(modulus, str):
                    raise ValueError("Modulus parameter not understood.")
            else:  # Neither a prime, nor a prime power
                raise ValueError(
                    "the order of a finite field must be a prime power.")

            return (order, name, modulus, impl, str(kwds), p, n, proof), kwds
Ejemplo n.º 4
0
def _single_variate(base_ring, names, sparse):
    """
    EXAMPLES::

        sage: from sage.rings.polynomial.laurent_polynomial_ring import _single_variate
        sage: _single_variate(QQ, ('x',), False)
        Univariate Laurent Polynomial Ring in x over Rational Field
    """
    ############################################################
    # This should later get moved to an actual single variate  #
    # implementation with valuation tracking,                  #
    # but I don't want to right now.                           #
    ############################################################
    # We need to come up with a name for the inverse that is easy to search
    # for in a string *and* doesn't overlap with the name that we already have.
    # For now, I'm going to use a name mangling with checking method.
    names = normalize_names(1, names)
    key = (base_ring, names, sparse)
    P = _get_from_cache(key)
    if P is not None:
        return P
    prepend_string = "qk"
    while True:
        if prepend_string in names:
            prepend_string += 'k'
        else:
            break
    R = _multi_variate_poly(base_ring, names, 1, sparse, 'degrevlex', None)
    P = LaurentPolynomialRing_mpair(R, prepend_string, names)
    _save_in_cache(key, P)
    return P
Ejemplo n.º 5
0
def AffineSpace(n, R=None, names='x'):
    r"""
    Return affine space of dimension `n` over the ring `R`.

    EXAMPLES:

    The dimension and ring can be given in either order::

        sage: AffineSpace(3, QQ, 'x')
        Affine Space of dimension 3 over Rational Field
        sage: AffineSpace(5, QQ, 'x')
        Affine Space of dimension 5 over Rational Field
        sage: A = AffineSpace(2, QQ, names='XY'); A
        Affine Space of dimension 2 over Rational Field
        sage: A.coordinate_ring()
        Multivariate Polynomial Ring in X, Y over Rational Field

    Use the divide operator for base extension::

        sage: AffineSpace(5, names='x')/GF(17)
        Affine Space of dimension 5 over Finite Field of size 17

    The default base ring is `\ZZ`::

        sage: AffineSpace(5, names='x')
        Affine Space of dimension 5 over Integer Ring

    There is also an affine space associated to each polynomial ring::

        sage: R = GF(7)['x,y,z']
        sage: A = AffineSpace(R); A
        Affine Space of dimension 3 over Finite Field of size 7
        sage: A.coordinate_ring() is R
        True
    """
    if is_MPolynomialRing(n) and R is None:
        R = n
        A = AffineSpace(R.ngens(), R.base_ring(), R.variable_names())
        A._coordinate_ring = R
        return A
    if isinstance(R, (int, long, Integer)):
        n, R = R, n
    if R is None:
        R = ZZ  # default is the integers
    if names is None:
        if n == 0:
            names = ''
        else:
            raise TypeError(
                "You must specify the variables names of the coordinate ring.")
    names = normalize_names(n, names)
    if R in _Fields:
        if is_FiniteField(R):
            return AffineSpace_finite_field(n, R, names)
        else:
            return AffineSpace_field(n, R, names)
    return AffineSpace_generic(n, R, names)
Ejemplo n.º 6
0
def AffineSpace(n, R=None, names='x'):
    r"""
    Return affine space of dimension `n` over the ring `R`.

    EXAMPLES:

    The dimension and ring can be given in either order::

        sage: AffineSpace(3, QQ, 'x')
        Affine Space of dimension 3 over Rational Field
        sage: AffineSpace(5, QQ, 'x')
        Affine Space of dimension 5 over Rational Field
        sage: A = AffineSpace(2, QQ, names='XY'); A
        Affine Space of dimension 2 over Rational Field
        sage: A.coordinate_ring()
        Multivariate Polynomial Ring in X, Y over Rational Field

    Use the divide operator for base extension::

        sage: AffineSpace(5, names='x')/GF(17)
        Affine Space of dimension 5 over Finite Field of size 17

    The default base ring is `\ZZ`::

        sage: AffineSpace(5, names='x')
        Affine Space of dimension 5 over Integer Ring

    There is also an affine space associated to each polynomial ring::

        sage: R = GF(7)['x,y,z']
        sage: A = AffineSpace(R); A
        Affine Space of dimension 3 over Finite Field of size 7
        sage: A.coordinate_ring() is R
        True
    """
    if is_MPolynomialRing(n) and R is None:
        R = n
        A = AffineSpace(R.ngens(), R.base_ring(), R.variable_names())
        A._coordinate_ring = R
        return A
    if isinstance(R, (int, long, Integer)):
        n, R = R, n
    if R is None:
        R = ZZ  # default is the integers
    if names is None:
        if n == 0:
            names = ''
        else:
            raise TypeError("You must specify the variables names of the coordinate ring.")
    names = normalize_names(n, names)
    if R in _Fields:
        if is_FiniteField(R):
            return AffineSpace_finite_field(n, R, names)
        else:
            return AffineSpace_field(n, R, names)
    return AffineSpace_generic(n, R, names)
Ejemplo n.º 7
0
    def __init__(self, n, R=ZZ, names=None):
        """
        EXAMPLES::

            sage: ProjectiveSpace(3, Zp(5), 'y')
            Projective Space of dimension 3 over 5-adic Ring with capped relative precision 20
        """
        names = normalize_names(n + 1, names)
        AmbientSpace.__init__(self, n, R)
        self._assign_names(names)
Ejemplo n.º 8
0
    def __init__(self, n, R, names):
        """
        EXAMPLES::

            sage: AffineSpace(3, Zp(5), 'y')
            Affine Space of dimension 3 over 5-adic Ring with capped relative precision 20
        """
        names = normalize_names(n, names)
        AmbientSpace.__init__(self, n, R)
        self._assign_names(names)
Ejemplo n.º 9
0
    def __init__(self, n, R=ZZ, names=None):
        """
        EXAMPLES::

            sage: ProjectiveSpace(3, Zp(5), 'y')
            Projective Space of dimension 3 over 5-adic Ring with capped relative precision 20
        """
        names = normalize_names(n+1, names)
        AmbientSpace.__init__(self, n, R)
        self._assign_names(names)
Ejemplo n.º 10
0
    def create_key_and_extra_args(self, order, name=None, modulus=None, names=None, impl=None, proof=None, **kwds):
        """
        EXAMPLES::

            sage: GF.create_key_and_extra_args(9, 'a')
            ((9, ('a',), 'conway', None, '{}', 3, 2, True), {})
            sage: GF.create_key_and_extra_args(9, 'a', foo='value')
            ((9, ('a',), 'conway', None, "{'foo': 'value'}", 3, 2, True), {'foo': 'value'})
        """
        from sage.structure.proof.all import WithProof, arithmetic

        if proof is None:
            proof = arithmetic()
        with WithProof("arithmetic", proof):
            order = int(order)
            if order <= 1:
                raise ValueError("the order of a finite field must be > 1.")

            if arith.is_prime(order):
                name = None
                modulus = None
                p = integer.Integer(order)
                n = integer.Integer(1)
            elif arith.is_prime_power(order):
                if not names is None:
                    name = names
                name = normalize_names(1, name)

                p, n = arith.factor(order)[0]

                if modulus is None or modulus == "default":
                    if exists_conway_polynomial(p, n):
                        modulus = "conway"
                    else:
                        if p == 2:
                            modulus = "minimal_weight"
                        else:
                            modulus = "random"
                elif modulus == "random":
                    modulus += str(random.randint(0, 1 << 128))

                if isinstance(modulus, (list, tuple)):
                    modulus = FiniteField(p)["x"](modulus)
                # some classes use 'random' as the modulus to
                # generate a random modulus, but we don't want
                # to cache it
                elif sage.rings.polynomial.polynomial_element.is_Polynomial(modulus):
                    modulus = modulus.change_variable_name("x")
                elif not isinstance(modulus, str):
                    raise ValueError("Modulus parameter not understood.")
            else:  # Neither a prime, nor a prime power
                raise ValueError("the order of a finite field must be a prime power.")

            return (order, name, modulus, impl, str(kwds), p, n, proof), kwds
Ejemplo n.º 11
0
    def create_key_and_extra_args(self,
                                  order,
                                  name=None,
                                  modulus=None,
                                  names=None,
                                  impl=None,
                                  proof=None,
                                  **kwds):
        """
        EXAMPLES::

            sage: GF.create_key_and_extra_args(9, 'a')
            ((9, ('a',), x^2 + 2*x + 2, None, '{}', 3, 2, True), {})
            sage: GF.create_key_and_extra_args(9, 'a', foo='value')
            ((9, ('a',), x^2 + 2*x + 2, None, "{'foo': 'value'}", 3, 2, True), {'foo': 'value'})
        """
        from sage.structure.proof.all import WithProof, arithmetic
        if proof is None: proof = arithmetic()
        with WithProof('arithmetic', proof):
            order = int(order)
            if order <= 1:
                raise ValueError("the order of a finite field must be > 1.")

            if arith.is_prime(order):
                name = None
                modulus = None
                p = integer.Integer(order)
                n = integer.Integer(1)
            elif arith.is_prime_power(order):
                if not names is None: name = names
                name = normalize_names(1, name)

                p, n = arith.factor(order)[0]

                if modulus is None or isinstance(modulus, str):
                    # A string specifies an algorithm to find a suitable modulus.
                    if modulus == "default":  # for backward compatibility
                        modulus = None
                    modulus = GF(p)['x'].irreducible_element(n,
                                                             algorithm=modulus)
                elif isinstance(modulus, (list, tuple)):
                    modulus = GF(p)['x'](modulus)
                elif sage.rings.polynomial.polynomial_element.is_Polynomial(
                        modulus):
                    modulus = modulus.change_variable_name('x')
                else:
                    raise TypeError("wrong type for modulus parameter")
            else:
                raise ValueError(
                    "the order of a finite field must be a prime power.")

            return (order, name, modulus, impl, str(kwds), p, n, proof), kwds
def _single_variate(base_ring, name, sparse, implementation):
    import sage.rings.polynomial.polynomial_ring as m

    name = normalize_names(1, name)
    key = (base_ring, name, sparse, implementation if not sparse else None)
    R = _get_from_cache(key)
    if not R is None:
        return R

    if isinstance(base_ring, ring.CommutativeRing):
        if is_IntegerModRing(base_ring) and not sparse:
            n = base_ring.order()
            if n.is_prime():
                R = m.PolynomialRing_dense_mod_p(base_ring, name, implementation=implementation)
            elif n > 1:
                R = m.PolynomialRing_dense_mod_n(base_ring, name, implementation=implementation)
            else:  # n == 1!
                R = m.PolynomialRing_integral_domain(base_ring, name)  # specialized code breaks in this case.

        elif is_FiniteField(base_ring) and not sparse:
            R = m.PolynomialRing_dense_finite_field(base_ring, name, implementation=implementation)

        elif isinstance(base_ring, padic_base_leaves.pAdicFieldCappedRelative):
            R = m.PolynomialRing_dense_padic_field_capped_relative(base_ring, name)

        elif isinstance(base_ring, padic_base_leaves.pAdicRingCappedRelative):
            R = m.PolynomialRing_dense_padic_ring_capped_relative(base_ring, name)

        elif isinstance(base_ring, padic_base_leaves.pAdicRingCappedAbsolute):
            R = m.PolynomialRing_dense_padic_ring_capped_absolute(base_ring, name)

        elif isinstance(base_ring, padic_base_leaves.pAdicRingFixedMod):
            R = m.PolynomialRing_dense_padic_ring_fixed_mod(base_ring, name)

        elif base_ring.is_field(proof=False):
            R = m.PolynomialRing_field(base_ring, name, sparse)

        elif base_ring.is_integral_domain(proof=False):
            R = m.PolynomialRing_integral_domain(base_ring, name, sparse, implementation)
        else:
            R = m.PolynomialRing_commutative(base_ring, name, sparse)
    else:
        R = m.PolynomialRing_general(base_ring, name, sparse)

    if hasattr(R, "_implementation_names"):
        for name in R._implementation_names:
            real_key = key[0:3] + (name,)
            _save_in_cache(real_key, R)
    else:
        _save_in_cache(key, R)
    return R
Ejemplo n.º 13
0
def FreeAbelianMonoid(index_set=None, names=None, **kwds):
    """
    Return a free abelian monoid on `n` generators or with the generators
    indexed by a set `I`.

    We construct free abelian monoids by specifing either:

    - the number of generators and/or the names of the generators
    - the indexing set for the generators (this ignores the other two inputs)

    INPUT:

    - ``index_set`` -- an indexing set for the generators; if an integer,
      then this becomes `\{0, 1, \ldots, n-1\}`

    -  ``names`` -- names of generators

    OUTPUT:

    A free abelian monoid.

    EXAMPLES::

        sage: F.<a,b,c,d,e> = FreeAbelianMonoid(); F
        Free abelian monoid on 5 generators (a, b, c, d, e)
        sage: FreeAbelianMonoid(index_set=ZZ)
        Free abelian monoid indexed by Integer Ring
    """
    if isinstance(index_set,
                  str):  # Swap args (this works if names is None as well)
        names, index_set = index_set, names

    if index_set is None and names is not None:
        if isinstance(names, str):
            index_set = names.count(',')
        else:
            index_set = len(names)

    if index_set not in ZZ:
        if names is not None:
            names = normalize_names(len(names), names)
        from sage.monoids.indexed_free_monoid import IndexedFreeAbelianMonoid
        return IndexedFreeAbelianMonoid(index_set, names=names, **kwds)

    if names is None:
        raise ValueError("names must be specified")
    return FreeAbelianMonoid_factory(index_set, names)
Ejemplo n.º 14
0
def FreeAbelianMonoid(index_set=None, names=None, **kwds):
    """
    Return a free abelian monoid on `n` generators or with the generators
    indexed by a set `I`.

    We construct free abelian monoids by specifing either:

    - the number of generators and/or the names of the generators
    - the indexing set for the generators (this ignores the other two inputs)

    INPUT:

    - ``index_set`` -- an indexing set for the generators; if an integer,
      then this becomes `\{0, 1, \ldots, n-1\}`

    -  ``names`` -- names of generators

    OUTPUT:

    A free abelian monoid.

    EXAMPLES::

        sage: F.<a,b,c,d,e> = FreeAbelianMonoid(); F
        Free abelian monoid on 5 generators (a, b, c, d, e)
        sage: FreeAbelianMonoid(index_set=ZZ)
        Free abelian monoid indexed by Integer Ring
    """
    if isinstance(index_set, str): # Swap args (this works if names is None as well)
        names, index_set = index_set, names

    if index_set is None and names is not None:
        if isinstance(names, str):
            index_set = names.count(',')
        else:
            index_set = len(names)

    if index_set not in ZZ:
        if names is not None:
            names = normalize_names(len(names), names)
        from sage.monoids.indexed_free_monoid import IndexedFreeAbelianMonoid
        return IndexedFreeAbelianMonoid(index_set, names=names, **kwds)

    if names is None:
        raise ValueError("names must be specified")
    return FreeAbelianMonoid_factory(index_set, names)
Ejemplo n.º 15
0
def _multi_variate(base_ring, names, n, sparse, order, implementation):
    #    if not sparse:
    #        raise ValueError, "A dense representation of multivariate polynomials is not supported"
    sparse = False
    # "True" would be correct, since there is no dense implementation of
    # multivariate polynomials. However, traditionally, "False" is used in the key,
    # even though it is meaningless.

    if implementation is not None:
        raise ValueError(
            "The %s implementation is not known for multivariate polynomial rings"
            % implementation)

    names = normalize_names(n, names)

    import sage.rings.polynomial.multi_polynomial_ring as m
    from sage.rings.polynomial.term_order import TermOrder

    order = TermOrder(order, n)

    key = (base_ring, names, n, sparse, order)
    R = _get_from_cache(key)
    if not R is None:
        return R

    from sage.rings.polynomial.multi_polynomial_libsingular import MPolynomialRing_libsingular
    if m.integral_domain.is_IntegralDomain(base_ring):
        if n < 1:
            R = m.MPolynomialRing_polydict_domain(base_ring, n, names, order)
        else:
            try:
                R = MPolynomialRing_libsingular(base_ring, n, names, order)
            except (TypeError, NotImplementedError):
                R = m.MPolynomialRing_polydict_domain(base_ring, n, names,
                                                      order)
    else:
        if not base_ring.is_zero():
            try:
                R = MPolynomialRing_libsingular(base_ring, n, names, order)
            except (TypeError, NotImplementedError):
                R = m.MPolynomialRing_polydict(base_ring, n, names, order)
        else:
            R = m.MPolynomialRing_polydict(base_ring, n, names, order)
    _save_in_cache(key, R)
    return R
Ejemplo n.º 16
0
def _multi_variate(base_ring, names, n, sparse, order, implementation):
    #    if not sparse:
    #        raise ValueError, "A dense representation of multivariate polynomials is not supported"
    sparse = False
    # "True" would be correct, since there is no dense implementation of
    # multivariate polynomials. However, traditionally, "False" is used in the key,
    # even though it is meaningless.

    if implementation is not None:
        raise ValueError("The %s implementation is not known for multivariate polynomial rings" % implementation)

    names = normalize_names(n, names)

    import sage.rings.polynomial.multi_polynomial_ring as m
    from sage.rings.polynomial.term_order import TermOrder

    order = TermOrder(order, n)

    key = (base_ring, names, n, sparse, order)
    R = _get_from_cache(key)
    if not R is None:
        return R

    from sage.rings.polynomial.multi_polynomial_libsingular import MPolynomialRing_libsingular

    if m.integral_domain.is_IntegralDomain(base_ring):
        if n < 1:
            R = m.MPolynomialRing_polydict_domain(base_ring, n, names, order)
        else:
            try:
                R = MPolynomialRing_libsingular(base_ring, n, names, order)
            except (TypeError, NotImplementedError):
                R = m.MPolynomialRing_polydict_domain(base_ring, n, names, order)
    else:
        if not base_ring.is_zero():
            try:
                R = MPolynomialRing_libsingular(base_ring, n, names, order)
            except (TypeError, NotImplementedError):
                R = m.MPolynomialRing_polydict(base_ring, n, names, order)
        else:
            R = m.MPolynomialRing_polydict(base_ring, n, names, order)
    _save_in_cache(key, R)
    return R
Ejemplo n.º 17
0
    def create_key_and_extra_args(self, order, name=None, modulus=None, names=None,
                                  impl=None, proof=None, **kwds):
        """
        EXAMPLES::

            sage: GF.create_key_and_extra_args(9, 'a')
            ((9, ('a',), x^2 + 2*x + 2, None, '{}', 3, 2, True), {})
            sage: GF.create_key_and_extra_args(9, 'a', foo='value')
            ((9, ('a',), x^2 + 2*x + 2, None, "{'foo': 'value'}", 3, 2, True), {'foo': 'value'})
        """
        from sage.structure.proof.all import WithProof, arithmetic
        if proof is None: proof = arithmetic()
        with WithProof('arithmetic', proof):
            order = int(order)
            if order <= 1:
                raise ValueError("the order of a finite field must be > 1.")

            if arith.is_prime(order):
                name = None
                modulus = None
                p = integer.Integer(order)
                n = integer.Integer(1)
            elif arith.is_prime_power(order):
                if not names is None: name = names
                name = normalize_names(1,name)

                p, n = arith.factor(order)[0]

                if modulus is None or isinstance(modulus, str):
                    # A string specifies an algorithm to find a suitable modulus.
                    if modulus == "default":    # for backward compatibility
                        modulus = None
                    modulus = GF(p)['x'].irreducible_element(n, algorithm=modulus)
                elif isinstance(modulus, (list, tuple)):
                    modulus = GF(p)['x'](modulus)
                elif sage.rings.polynomial.polynomial_element.is_Polynomial(modulus):
                    modulus = modulus.change_variable_name('x')
                else:
                    raise TypeError("wrong type for modulus parameter")
            else:
                raise ValueError("the order of a finite field must be a prime power.")

            return (order, name, modulus, impl, str(kwds), p, n, proof), kwds
Ejemplo n.º 18
0
def _multi_variate(base_ring, names, n, sparse, order):
    """
    EXAMPLES::

        sage: from sage.rings.polynomial.laurent_polynomial_ring import _multi_variate
        sage: _multi_variate(QQ, ('x','y'), 2, False, 'degrevlex')
        Multivariate Laurent Polynomial Ring in x, y over Rational Field
    """
    # We need to come up with a name for the inverse that is easy to search
    # for in a string *and* doesn't overlap with the name that we already have.
    # For now, I'm going to use a name mangling with checking method.
    names = normalize_names(n, names)

    from term_order import TermOrder
    order = TermOrder(order, n)

    if isinstance(names, list):
        names = tuple(names)
    elif isinstance(names, str):
        if ',' in names:
            names = tuple(names.split(','))

    key = (base_ring, names, n, sparse, order)
    P = _get_from_cache(key)
    if P is not None:
        return P
    prepend_string = "qk"
    while True:
        for a in names:
            if prepend_string in a:
                prepend_string += 'k'
                break
        else:
            break
    R = _multi_variate_poly(base_ring, names, n, sparse, order, None)
    P = LaurentPolynomialRing_mpair(R, prepend_string, names)
    _save_in_cache(key, P)
    return P
Ejemplo n.º 19
0
def _multi_variate(base_ring, names, n, sparse, order):
    """
    EXAMPLES::

        sage: from sage.rings.polynomial.laurent_polynomial_ring import _multi_variate
        sage: _multi_variate(QQ, ('x','y'), 2, False, 'degrevlex')
        Multivariate Laurent Polynomial Ring in x, y over Rational Field
    """
    # We need to come up with a name for the inverse that is easy to search
    # for in a string *and* doesn't overlap with the name that we already have.
    # For now, I'm going to use a name mangling with checking method.
    names = normalize_names(n, names)

    from term_order import TermOrder
    order = TermOrder(order, n)

    if isinstance(names, list):
        names = tuple(names)
    elif isinstance(names, str):
        if ',' in names:
            names = tuple(names.split(','))

    key = (base_ring, names, n, sparse, order)
    P = _get_from_cache(key)
    if P is not None:
        return P
    prepend_string = "qk"
    while True:
        for a in names:
            if prepend_string in a:
                prepend_string += 'k'
                break
        else:
            break
    R = _multi_variate_poly(base_ring, names, n, sparse, order, None)
    P = LaurentPolynomialRing_mpair(R, prepend_string, names)
    _save_in_cache(key, P)
    return P
Ejemplo n.º 20
0
def _single_variate(base_ring, names, sparse):
    """
    EXAMPLES::

        sage: from sage.rings.polynomial.laurent_polynomial_ring import _single_variate
        sage: _single_variate(QQ, ('x',), False)
        Univariate Laurent Polynomial Ring in x over Rational Field
    """
    names = normalize_names(1, names)
    key = (base_ring, names, sparse)
    P = _get_from_cache(key)
    if P is not None:
        return P
    prepend_string = "qk"
    while True:
        if prepend_string in names:
            prepend_string += 'k'
        else:
            break
    R = _single_variate_poly(base_ring, names, sparse, None)
    P = LaurentPolynomialRing_univariate(R, names)
    _save_in_cache(key, P)
    return P
Ejemplo n.º 21
0
def _single_variate(base_ring, names, sparse):
    """
    EXAMPLES::

        sage: from sage.rings.polynomial.laurent_polynomial_ring import _single_variate
        sage: _single_variate(QQ, ('x',), False)
        Univariate Laurent Polynomial Ring in x over Rational Field
    """
    names = normalize_names(1, names)
    key = (base_ring, names, sparse)
    P = _get_from_cache(key)
    if P is not None:
        return P
    prepend_string = "qk"
    while True:
        if prepend_string in names:
            prepend_string += 'k'
        else:
            break
    R = _single_variate_poly(base_ring, names, sparse, None)
    P = LaurentPolynomialRing_univariate(R, names)
    _save_in_cache(key, P)
    return P
Ejemplo n.º 22
0
    def create_key_and_extra_args(self, order, name=None, modulus=None, names=None,
                                  impl=None, proof=None, check_irreducible=True, **kwds):
        """
        EXAMPLES::

            sage: GF.create_key_and_extra_args(9, 'a')
            ((9, ('a',), x^2 + 2*x + 2, 'givaro', '{}', 3, 2, True), {})
            sage: GF.create_key_and_extra_args(9, 'a', foo='value')
            ((9, ('a',), x^2 + 2*x + 2, 'givaro', "{'foo': 'value'}", 3, 2, True), {'foo': 'value'})
        """
        import sage.rings.arith
        from sage.structure.proof.all import WithProof, arithmetic
        if proof is None:
            proof = arithmetic()
        with WithProof('arithmetic', proof):
            order = Integer(order)
            if order <= 1:
                raise ValueError("the order of a finite field must be at least 2")

            if order.is_prime():
                p = order
                n = Integer(1)
                if impl is None:
                    impl = 'modn'
                name = ('x',)  # Ignore name
                # Every polynomial of degree 1 is irreducible
                check_irreducible = False
            # This check should be replaced by order.is_prime_power()
            # if Trac #16878 is fixed.
            elif sage.rings.arith.is_prime_power(order):
                if not names is None: name = names
                name = normalize_names(1,name)

                p, n = order.factor()[0]

                # The following is a temporary solution that allows us
                # to construct compatible systems of finite fields
                # until algebraic closures of finite fields are
                # implemented in Sage.  It requires the user to
                # specify two parameters:
                #
                # - `conway` -- boolean; if True, this field is
                #   constructed to fit in a compatible system using
                #   a Conway polynomial.
                # - `prefix` -- a string used to generate names for
                #   automatically constructed finite fields
                #
                # See the docstring of FiniteFieldFactory for examples.
                #
                # Once algebraic closures of finite fields are
                # implemented, this syntax should be superseded by
                # something like the following:
                #
                #     sage: Fpbar = GF(5).algebraic_closure('z')
                #     sage: F, e = Fpbar.subfield(3)  # e is the embedding into Fpbar
                #     sage: F
                #     Finite field in z3 of size 5^3
                #
                # This temporary solution only uses actual Conway
                # polynomials (no pseudo-Conway polynomials), since
                # pseudo-Conway polynomials are not unique, and until
                # we have algebraic closures of finite fields, there
                # is no good place to store a specific choice of
                # pseudo-Conway polynomials.
                if name is None:
                    if not ('conway' in kwds and kwds['conway']):
                        raise ValueError("parameter 'conway' is required if no name given")
                    if 'prefix' not in kwds:
                        raise ValueError("parameter 'prefix' is required if no name given")
                    name = kwds['prefix'] + str(n)

                if 'conway' in kwds and kwds['conway']:
                    from conway_polynomials import conway_polynomial
                    if 'prefix' not in kwds:
                        raise ValueError("a prefix must be specified if conway=True")
                    if modulus is not None:
                        raise ValueError("no modulus may be specified if conway=True")
                    # The following raises a RuntimeError if no polynomial is found.
                    modulus = conway_polynomial(p, n)

                if impl is None:
                    if order < zech_log_bound:
                        impl = 'givaro'
                    elif p == 2:
                        impl = 'ntl'
                    else:
                        impl = 'pari_ffelt'
            else:
                raise ValueError("the order of a finite field must be a prime power")

            # Determine modulus.
            # For the 'modn' implementation, we use the following
            # optimization which we also need to avoid an infinite loop:
            # a modulus of None is a shorthand for x-1.
            if modulus is not None or impl != 'modn':
                R = PolynomialRing(FiniteField(p), 'x')
                if modulus is None:
                    modulus = R.irreducible_element(n)
                if isinstance(modulus, str):
                    # A string specifies an algorithm to find a suitable modulus.
                    if modulus == "default":
                        from sage.misc.superseded import deprecation
                        deprecation(16983, "the modulus 'default' is deprecated, use modulus=None instead (which is the default)")
                        modulus = None
                    modulus = R.irreducible_element(n, algorithm=modulus)
                else:
                    if sage.rings.polynomial.polynomial_element.is_Polynomial(modulus):
                        modulus = modulus.change_variable_name('x')
                    modulus = R(modulus).monic()

                    if modulus.degree() != n:
                        raise ValueError("the degree of the modulus does not equal the degree of the field")
                    if check_irreducible and not modulus.is_irreducible():
                        raise ValueError("finite field modulus must be irreducible but it is not")
                # If modulus is x - 1 for impl="modn", set it to None
                if impl == 'modn' and modulus[0] == -1:
                    modulus = None

            return (order, name, modulus, impl, str(kwds), p, n, proof), kwds
Ejemplo n.º 23
0
def ProductProjectiveSpaces(n, R=None, names='x'):
    r"""
    Returns the cartesian product of projective spaces. Can input either a list of projective spaces
    over the same base ring or the list of dimensions, the base ring, and the variable names.

    INPUT:

    - ``n`` -- a list of integers or a list of projective spaces

    - ``R`` -- a ring

    - ``names`` -- a string or list of strings

    EXAMPLES::

        sage: P1 = ProjectiveSpace(QQ,2,'x')
        sage: P2 = ProjectiveSpace(QQ,3,'y')
        sage: ProductProjectiveSpaces([P1,P2])
        Product of projective spaces P^2 x P^3 over Rational Field

    ::

        sage: ProductProjectiveSpaces([2,2],GF(7),'y')
        Product of projective spaces P^2 x P^2 over Finite Field of size 7

    ::

        sage: P1 = ProjectiveSpace(ZZ,2,'x')
        sage: P2 = ProjectiveSpace(QQ,3,'y')
        sage: ProductProjectiveSpaces([P1,P2])
        Traceback (most recent call last):
        ...
        AttributeError: Components must be over the same base ring
    """
    if isinstance(R, (list, tuple)):
        n, R = R, n
    if not isinstance(n, (tuple, list)):
        raise TypeError("Must be a list of dimensions")
    if R is None:
        R = QQ  # default is the rationals
    if isinstance(n[0], ProjectiveSpace_ring):
        #this should be a list of projective spaces
        names = []
        N = []
        R = None
        for PS in n:
            if not isinstance(PS,ProjectiveSpace_ring):
                raise TypeError("Must be a list of Projective Spaces or (dimensions,base ring,names)")
            if R is None:
                R = PS.base_ring()
            elif R != PS.base_ring():
                raise AttributeError("Components must be over the same base ring")
            N.append(PS.dimension_relative())
            names += PS.variable_names()
        X = ProductProjectiveSpaces_ring(N, R, names)
        X._components = n
    else:
        if isinstance(R, (list,tuple)):
           n, R = R, n
        if not isinstance(n,(list,tuple)):
            raise ValueError("Need list or tuple of dimensions")
        if not is_CommutativeRing(R):
            raise ValueError("Must be a commutative ring")
        from sage.structure.parent_gens import normalize_names
        n_vars=sum(d+1 for d in n)
        if isinstance(names, six.string_types):
            names = normalize_names(n_vars, names)
        else:
            name_list = list(names)
            if len(name_list) == len(n):
                names = []
                for name, dim in zip(name_list, n):
                    names += normalize_names(dim+1, name)
            else:
                n_vars = sum(1+d for d in n)
                names = normalize_names(n_vars, name_list)
        X = ProductProjectiveSpaces_ring(n, R, names)
    return(X)
Ejemplo n.º 24
0
 def create_key(self, n, names):
     n = int(n)
     names = normalize_names(n, names)
     return (n, names)
Ejemplo n.º 25
0
def BooleanPolynomialRing_constructor(n=None, names=None, order="lex"):
    """
    Construct a boolean polynomial ring with the following
    parameters:

    INPUT:

    - ``n`` -- number of variables (an integer > 1)
    - ``names`` -- names of ring variables, may be a string or list/tuple of strings
    - ``order`` -- term order (default: lex)

    EXAMPLES::

        sage: R.<x, y, z> = BooleanPolynomialRing() # indirect doctest
        sage: R
        Boolean PolynomialRing in x, y, z

        sage: p = x*y + x*z + y*z
        sage: x*p
        x*y*z + x*y + x*z

        sage: R.term_order()
        Lexicographic term order

        sage: R = BooleanPolynomialRing(5,'x',order='deglex(3),deglex(2)')
        sage: R.term_order()
        Block term order with blocks:
        (Degree lexicographic term order of length 3,
         Degree lexicographic term order of length 2)

        sage: R = BooleanPolynomialRing(3,'x',order='degrevlex')
        sage: R.term_order()
        Degree reverse lexicographic term order

        sage: BooleanPolynomialRing(names=('x','y'))
        Boolean PolynomialRing in x, y

        sage: BooleanPolynomialRing(names='x,y')
        Boolean PolynomialRing in x, y

    TESTS::

        sage: P.<x,y> = BooleanPolynomialRing(2,order='degrevlex')
        sage: x > y
        True

        sage: P.<x0, x1, x2, x3> = BooleanPolynomialRing(4,order='degrevlex(2),degrevlex(2)')
        sage: x0 > x1
        True
        sage: x2 > x3
        True
    """

    if isinstance(n, str):
        names = n
        n = 0
    if n is None and names is not None:
        n = 0

    names = normalize_names(n, names)
    if n is 0:
        n = len(names)

    from sage.rings.polynomial.term_order import TermOrder

    order = TermOrder(order, n)

    key = ("pbori", names, n, order)
    R = _get_from_cache(key)
    if not R is None:
        return R

    from sage.rings.polynomial.pbori import BooleanPolynomialRing

    R = BooleanPolynomialRing(n, names, order)

    _save_in_cache(key, R)
    return R
Ejemplo n.º 26
0
    def create_key_and_extra_args(self,
                                  order,
                                  name=None,
                                  modulus=None,
                                  names=None,
                                  impl=None,
                                  proof=None,
                                  check_irreducible=True,
                                  **kwds):
        """
        EXAMPLES::

            sage: GF.create_key_and_extra_args(9, 'a')
            ((9, ('a',), x^2 + 2*x + 2, 'givaro', '{}', 3, 2, True), {})
            sage: GF.create_key_and_extra_args(9, 'a', foo='value')
            ((9, ('a',), x^2 + 2*x + 2, 'givaro', "{'foo': 'value'}", 3, 2, True), {'foo': 'value'})
        """
        import sage.rings.arith
        from sage.structure.proof.all import WithProof, arithmetic
        if proof is None:
            proof = arithmetic()
        with WithProof('arithmetic', proof):
            order = Integer(order)
            if order <= 1:
                raise ValueError(
                    "the order of a finite field must be at least 2")

            if order.is_prime():
                p = order
                n = Integer(1)
                if impl is None:
                    impl = 'modn'
                name = ('x', )  # Ignore name
                # Every polynomial of degree 1 is irreducible
                check_irreducible = False
            # This check should be replaced by order.is_prime_power()
            # if Trac #16878 is fixed.
            elif sage.rings.arith.is_prime_power(order):
                if not names is None: name = names
                name = normalize_names(1, name)

                p, n = order.factor()[0]

                # The following is a temporary solution that allows us
                # to construct compatible systems of finite fields
                # until algebraic closures of finite fields are
                # implemented in Sage.  It requires the user to
                # specify two parameters:
                #
                # - `conway` -- boolean; if True, this field is
                #   constructed to fit in a compatible system using
                #   a Conway polynomial.
                # - `prefix` -- a string used to generate names for
                #   automatically constructed finite fields
                #
                # See the docstring of FiniteFieldFactory for examples.
                #
                # Once algebraic closures of finite fields are
                # implemented, this syntax should be superseded by
                # something like the following:
                #
                #     sage: Fpbar = GF(5).algebraic_closure('z')
                #     sage: F, e = Fpbar.subfield(3)  # e is the embedding into Fpbar
                #     sage: F
                #     Finite field in z3 of size 5^3
                #
                # This temporary solution only uses actual Conway
                # polynomials (no pseudo-Conway polynomials), since
                # pseudo-Conway polynomials are not unique, and until
                # we have algebraic closures of finite fields, there
                # is no good place to store a specific choice of
                # pseudo-Conway polynomials.
                if name is None:
                    if not ('conway' in kwds and kwds['conway']):
                        raise ValueError(
                            "parameter 'conway' is required if no name given")
                    if 'prefix' not in kwds:
                        raise ValueError(
                            "parameter 'prefix' is required if no name given")
                    name = kwds['prefix'] + str(n)

                if 'conway' in kwds and kwds['conway']:
                    from conway_polynomials import conway_polynomial
                    if 'prefix' not in kwds:
                        raise ValueError(
                            "a prefix must be specified if conway=True")
                    if modulus is not None:
                        raise ValueError(
                            "no modulus may be specified if conway=True")
                    # The following raises a RuntimeError if no polynomial is found.
                    modulus = conway_polynomial(p, n)

                if impl is None:
                    if order < zech_log_bound:
                        impl = 'givaro'
                    elif p == 2:
                        impl = 'ntl'
                    else:
                        impl = 'pari_ffelt'
            else:
                raise ValueError(
                    "the order of a finite field must be a prime power")

            # Determine modulus.
            # For the 'modn' implementation, we use the following
            # optimization which we also need to avoid an infinite loop:
            # a modulus of None is a shorthand for x-1.
            if modulus is not None or impl != 'modn':
                R = PolynomialRing(FiniteField(p), 'x')
                if modulus is None:
                    modulus = R.irreducible_element(n)
                if isinstance(modulus, str):
                    # A string specifies an algorithm to find a suitable modulus.
                    if modulus == "default":
                        from sage.misc.superseded import deprecation
                        deprecation(
                            16983,
                            "the modulus 'default' is deprecated, use modulus=None instead (which is the default)"
                        )
                        modulus = None
                    modulus = R.irreducible_element(n, algorithm=modulus)
                else:
                    if sage.rings.polynomial.polynomial_element.is_Polynomial(
                            modulus):
                        modulus = modulus.change_variable_name('x')
                    modulus = R(modulus).monic()

                    if modulus.degree() != n:
                        raise ValueError(
                            "the degree of the modulus does not equal the degree of the field"
                        )
                    if check_irreducible and not modulus.is_irreducible():
                        raise ValueError(
                            "finite field modulus must be irreducible but it is not"
                        )
                # If modulus is x - 1 for impl="modn", set it to None
                if impl == 'modn' and modulus[0] == -1:
                    modulus = None

            return (order, name, modulus, impl, str(kwds), p, n, proof), kwds
Ejemplo n.º 27
0
def PowerSeriesRing(base_ring, name=None, arg2=None, names=None,
                    sparse=False, default_prec=None, order='negdeglex', num_gens=None):
    r"""
    Create a univariate or multivariate power series ring over a given
    (commutative) base ring.
    
    INPUT:
    
    
    -  ``base_ring`` - a commutative ring
    
    -  ``name``, ``names`` - name(s) of the indeterminate
    
    - ``default_prec`` - the default precision used if an exact object must
       be changed to an approximate object in order to do an arithmetic
       operation.  If left as ``None``, it will be set to 20 in the
       univariate case, and 12 in the multivariate case.
    
    -  ``sparse`` - (default: ``False``) whether power series
       are represented as sparse objects.

    - ``order`` - (default: ``negdeglex``) term ordering, for multivariate case

    - ``num_gens`` - number of generators, for multivariate case
    
    
    There is a unique power series ring over each base ring with given
    variable name. Two power series over the same base ring with
    different variable names are not equal or isomorphic.
    
    EXAMPLES (Univariate)::
    
        sage: R = PowerSeriesRing(QQ, 'x'); R
        Power Series Ring in x over Rational Field
    
    ::
    
        sage: S = PowerSeriesRing(QQ, 'y'); S
        Power Series Ring in y over Rational Field
    
    ::
    
        sage: R = PowerSeriesRing(QQ, 10)
        Traceback (most recent call last):
        ...
        ValueError: first letter of variable name must be a letter
    
    ::
    
        sage: S = PowerSeriesRing(QQ, 'x', default_prec = 15); S
        Power Series Ring in x over Rational Field
        sage: S.default_prec()
        15

    EXAMPLES (Multivariate) See also :doc:`multi_power_series_ring`::

        sage: R = PowerSeriesRing(QQ, 't,u,v'); R
        Multivariate Power Series Ring in t, u, v over Rational Field

    ::

        sage: N = PowerSeriesRing(QQ,'w',num_gens=5); N
        Multivariate Power Series Ring in w0, w1, w2, w3, w4 over Rational Field

    Number of generators can be specified before variable name without using keyword::
        
        sage: M = PowerSeriesRing(QQ,4,'k'); M
        Multivariate Power Series Ring in k0, k1, k2, k3 over Rational Field

    Multivariate power series can be constructed using angle bracket or double square bracket notation::

        sage: R.<t,u,v> = PowerSeriesRing(QQ, 't,u,v'); R
        Multivariate Power Series Ring in t, u, v over Rational Field

        sage: ZZ[['s,t,u']]
        Multivariate Power Series Ring in s, t, u over Integer Ring

    Sparse multivariate power series ring::
    
        sage: M = PowerSeriesRing(QQ,4,'k',sparse=True); M
        Sparse Multivariate Power Series Ring in k0, k1, k2, k3 over
        Rational Field

    Power series ring over polynomial ring::
    
        sage: H = PowerSeriesRing(PolynomialRing(ZZ,3,'z'),4,'f'); H
        Multivariate Power Series Ring in f0, f1, f2, f3 over Multivariate
        Polynomial Ring in z0, z1, z2 over Integer Ring

    Power series ring over finite field::
    
        sage: S = PowerSeriesRing(GF(65537),'x,y'); S
        Multivariate Power Series Ring in x, y over Finite Field of size
        65537

    Power series ring with many variables::

        sage: R = PowerSeriesRing(ZZ, ['x%s'%p for p in primes(100)]); R
        Multivariate Power Series Ring in 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 over Integer Ring

    - Use :meth:`inject_variables` to make the variables available for
      interactive use.

      ::

        sage: R.inject_variables()
        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
        
        sage: f = x47 + 3*x11*x29 - x19 + R.O(3) 
        sage: f in R
        True


    Variable ordering determines how series are displayed::

        sage: T.<a,b> = PowerSeriesRing(ZZ,order='deglex'); T
        Multivariate Power Series Ring in a, b over Integer Ring
        sage: T.term_order()
        Degree lexicographic term order
        sage: p = - 2*b^6 + a^5*b^2 + a^7 - b^2 - a*b^3 + T.O(9); p
        a^7 + a^5*b^2 - 2*b^6 - a*b^3 - b^2 + O(a, b)^9

        sage: U = PowerSeriesRing(ZZ,'a,b',order='negdeglex'); U
        Multivariate Power Series Ring in a, b over Integer Ring
        sage: U.term_order()
        Negative degree lexicographic term order
        sage: U(p)
        -b^2 - a*b^3 - 2*b^6 + a^7 + a^5*b^2 + O(a, b)^9


    TESTS::

        sage: N = PowerSeriesRing(QQ,'k',num_gens=5); N
        Multivariate Power Series Ring in k0, k1, k2, k3, k4 over Rational Field

    The following behavior of univariate power series ring will eventually
    be deprecated and then changed to return a multivariate power series
    ring::

        sage: N = PowerSeriesRing(QQ,'k',5); N
        Power Series Ring in k over Rational Field
        sage: N.default_prec()
        5
        sage: L.<m> = PowerSeriesRing(QQ,5); L
        Power Series Ring in m over Rational Field
        sage: L.default_prec()
        5

    """
    #multivariate case:
    # examples for first case:
    # PowerSeriesRing(QQ,'x,y,z')
    # PowerSeriesRing(QQ,['x','y','z'])
    # PowerSeriesRing(QQ,['x','y','z'], 3)
    if names is None and name is not None:
        names = name
    if isinstance(names, (tuple, list)) and len(names) > 1 or (isinstance(names, str) and ',' in names):
        return _multi_variate(base_ring, num_gens=arg2, names=names,
                     order=order, default_prec=default_prec, sparse=sparse)
    # examples for second case:
    # PowerSeriesRing(QQ,3,'t')
    if arg2 is None and num_gens is not None:
        arg2 = names
        names = num_gens
    if isinstance(arg2, str) and isinstance(names, (int,long,integer.Integer)):
        return _multi_variate(base_ring, num_gens=names, names=arg2,
                     order=order, default_prec=default_prec, sparse=sparse)

    
    # univariate case: the arguments to PowerSeriesRing used to be
    # (base_ring, name=None, default_prec=20, names=None, sparse=False),
    # and thus that is what the code below expects; this behavior is being
    # deprecated, and will eventually be removed.
    if default_prec is None and arg2 is None:
        default_prec = 20
    elif arg2 is not None:
        default_prec = arg2

    ## too many things (padics, elliptic curves) depend on this behavior,
    ## so no warning for now.
    ##
    # from sage.misc.misc import deprecation
    # if isinstance(name, (int,long,integer.Integer)) or isinstance(arg2,(int,long,integer.Integer)):
    #     deprecation("This behavior of PowerSeriesRing is being deprecated in favor of constructing multivariate power series rings. (See Trac ticket #1956.)")


    # the following is the original, univariate-only code

    if isinstance(name, (int,long,integer.Integer)):
        default_prec = name
    if not names is None:
        name = names
    try:
        name = gens.normalize_names(1, name)
    except TypeError:
        raise TypeError, "illegal variable name"
    
    if name is None:
        raise TypeError, "You must specify the name of the indeterminate of the Power series ring."
    
    key = (base_ring, name, default_prec, sparse)
    if _cache.has_key(key):
        R = _cache[key]()
        if not R is None:
            return R

    if isinstance(name, (tuple, list)):
        assert len(name) == 1
        name = name[0]

    if not (name is None or isinstance(name, str)):
        raise TypeError, "variable name must be a string or None"
        
                  
    if isinstance(base_ring, field.Field):
        R = PowerSeriesRing_over_field(base_ring, name, default_prec, sparse=sparse)
    elif isinstance(base_ring, integral_domain.IntegralDomain):
        R = PowerSeriesRing_domain(base_ring, name, default_prec, sparse=sparse)
    elif isinstance(base_ring, commutative_ring.CommutativeRing):
        R = PowerSeriesRing_generic(base_ring, name, default_prec, sparse=sparse)
    else:
        raise TypeError, "base_ring must be a commutative ring"
    _cache[key] = weakref.ref(R)
    return R
Ejemplo n.º 28
0
def BooleanPolynomialRing_constructor(n=None, names=None, order="lex"):
    """
    Construct a boolean polynomial ring with the following
    parameters:

    INPUT:

    - ``n`` -- number of variables (an integer > 1)
    - ``names`` -- names of ring variables, may be a string or list/tuple of strings
    - ``order`` -- term order (default: lex)

    EXAMPLES::

        sage: R.<x, y, z> = BooleanPolynomialRing() # indirect doctest
        sage: R
        Boolean PolynomialRing in x, y, z

        sage: p = x*y + x*z + y*z
        sage: x*p
        x*y*z + x*y + x*z

        sage: R.term_order()
        Lexicographic term order

        sage: R = BooleanPolynomialRing(5,'x',order='deglex(3),deglex(2)')
        sage: R.term_order()
        Block term order with blocks:
        (Degree lexicographic term order of length 3,
         Degree lexicographic term order of length 2)

        sage: R = BooleanPolynomialRing(3,'x',order='degneglex')
        sage: R.term_order()
        Degree negative lexicographic term order

        sage: BooleanPolynomialRing(names=('x','y'))
        Boolean PolynomialRing in x, y

        sage: BooleanPolynomialRing(names='x,y')
        Boolean PolynomialRing in x, y

    TESTS::

        sage: P.<x,y> = BooleanPolynomialRing(2,order='deglex')
        sage: x > y
        True

        sage: P.<x0, x1, x2, x3> = BooleanPolynomialRing(4,order='deglex(2),deglex(2)')
        sage: x0 > x1
        True
        sage: x2 > x3
        True
    """

    if isinstance(n, str):
        names = n
        n = 0
    if n is None and names is not None:
        n = 0

    names = normalize_names(n, names)
    if n is 0:
        n = len(names)

    from sage.rings.polynomial.term_order import TermOrder

    order = TermOrder(order, n)

    key = ("pbori", names, n, order)
    R = _get_from_cache(key)
    if not R is None:
        return R

    from sage.rings.polynomial.pbori import BooleanPolynomialRing
    R = BooleanPolynomialRing(n, names, order)

    _save_in_cache(key, R)
    return R
Ejemplo n.º 29
0
def FreeMonoid(index_set=None, names=None, commutative=False, **kwds):
    r"""
    Return a free monoid on `n` generators or with the generators indexed by
    a set `I`.

    We construct free monoids by specifing either:

    - the number of generators and/or the names of the generators
    - the indexing set for the generators

    INPUT:

    - ``index_set`` -- an indexing set for the generators; if an integer,
      than this becomes `\{0, 1, \ldots, n-1\}`

    -  ``names`` -- names of generators

    - ``commutative`` -- (default: ``False``) whether the free monoid is
      commutative or not

    OUTPUT:

    A free monoid.

    EXAMPLES::

        sage: F.<a,b,c,d,e> = FreeMonoid(); F
        Free monoid on 5 generators (a, b, c, d, e)
        sage: FreeMonoid(index_set=ZZ)
        Free monoid indexed by Integer Ring

        sage: F.<x,y,z> = FreeMonoid(abelian=True); F
        Free abelian monoid on 3 generators (x, y, z)
        sage: FreeMonoid(index_set=ZZ, commutative=True)
        Free abelian monoid indexed by Integer Ring
    """
    if 'abelian' in kwds:
        commutative = kwds['abelian']
        del kwds['abelian']

    if commutative:
        from sage.monoids.free_abelian_monoid import FreeAbelianMonoid
        return FreeAbelianMonoid(index_set, names, **kwds)

    if isinstance(index_set, str): # Swap args (this works if names is None as well)
        names, index_set = index_set, names

    if index_set is None and names is not None:
        if isinstance(names, str):
            index_set = names.count(',')
        else:
            index_set = len(names)

    if index_set not in ZZ:
        if names is not None:
            names = normalize_names(len(names), names)
        from sage.monoids.indexed_free_monoid import IndexedFreeMonoid
        return IndexedFreeMonoid(index_set, names=names, **kwds)

    if names is None:
        raise ValueError("names must be specified")
    return FreeMonoid_factory(index_set, names)
Ejemplo n.º 30
0
def ProductProjectiveSpaces(n, R=None, names='x'):
    r"""
    Returns the cartesian product of projective spaces. Can input either a list of projective spaces
    over the same base ring or the list of dimensions, the base ring, and the variable names.

    INPUT:

    - ``n`` -- a list of integers or a list of projective spaces

    - ``R`` -- a ring

    - ``names`` -- a string or list of strings

    EXAMPLES::

        sage: P1 = ProjectiveSpace(QQ,2,'x')
        sage: P2 = ProjectiveSpace(QQ,3,'y')
        sage: ProductProjectiveSpaces([P1,P2])
        Product of projective spaces P^2 x P^3 over Rational Field

    ::

        sage: ProductProjectiveSpaces([2,2],GF(7),'y')
        Product of projective spaces P^2 x P^2 over Finite Field of size 7

    ::

        sage: P1 = ProjectiveSpace(ZZ,2,'x')
        sage: P2 = ProjectiveSpace(QQ,3,'y')
        sage: ProductProjectiveSpaces([P1,P2])
        Traceback (most recent call last):
        ...
        AttributeError: Components must be over the same base ring
    """
    if isinstance(R, (list, tuple)):
        n, R = R, n
    if not isinstance(n, (tuple, list)):
        raise TypeError("Must be a list of dimensions")
    if R is None:
        R = QQ  # default is the rationals
    if isinstance(n[0], ProjectiveSpace_ring):
        #this should be a list of projective spaces
        names = []
        N = []
        R = None
        for PS in n:
            if not isinstance(PS,ProjectiveSpace_ring):
                raise TypeError("Must be a list of Projective Spaces or (dimensions,base ring,names)")
            if R is None:
                R = PS.base_ring()
            elif R != PS.base_ring():
                raise AttributeError("Components must be over the same base ring")
            N.append(PS.dimension_relative())
            names += PS.variable_names()
        X = ProductProjectiveSpaces_ring(N, R, names)
        X._components = n
    else:
        if isinstance(R, (list,tuple)):
           n, R = R, n
        if not isinstance(n,(list,tuple)):
            raise ValueError("Need list or tuple of dimensions")
        if not is_CommutativeRing(R):
            raise ValueError("Must be a commutative ring")
        from sage.structure.parent_gens import normalize_names
        n_vars=sum(d+1 for d in n)
        if isinstance(names, basestring):
            names = normalize_names(n_vars, names)
        else:
            name_list = list(names)
            if len(name_list) == len(n):
                names = []
                for name, dim in zip(name_list, n):
                    names += normalize_names(dim+1, name)
            else:
                n_vars = sum(1+d for d in n)
                names = normalize_names(n_vars, name_list)
        X = ProductProjectiveSpaces_ring(n, R, names)
    return(X)
Ejemplo n.º 31
0
    def create_key_and_extra_args(self,
                                  order,
                                  name=None,
                                  modulus=None,
                                  names=None,
                                  impl=None,
                                  proof=None,
                                  **kwds):
        """
        EXAMPLES::

            sage: GF.create_key_and_extra_args(9, 'a')
            ((9, ('a',), x^2 + 2*x + 2, None, '{}', 3, 2, True), {})
            sage: GF.create_key_and_extra_args(9, 'a', foo='value')
            ((9, ('a',), x^2 + 2*x + 2, None, "{'foo': 'value'}", 3, 2, True), {'foo': 'value'})
        """
        from sage.structure.proof.all import WithProof, arithmetic
        if proof is None: proof = arithmetic()
        with WithProof('arithmetic', proof):
            order = int(order)
            if order <= 1:
                raise ValueError("the order of a finite field must be > 1.")

            if arith.is_prime(order):
                name = None
                modulus = None
                p = integer.Integer(order)
                n = integer.Integer(1)
            elif arith.is_prime_power(order):
                if not names is None: name = names
                name = normalize_names(1, name)

                p, n = arith.factor(order)[0]

                # The following is a temporary solution that allows us
                # to construct compatible systems of finite fields
                # until algebraic closures of finite fields are
                # implemented in Sage.  It requires the user to
                # specify two parameters:
                #
                # - `conway` -- boolean; if True, this field is
                #   constructed to fit in a compatible system using
                #   a Conway polynomial.
                # - `prefix` -- a string used to generate names for
                #   automatically constructed finite fields
                #
                # See the docstring of FiniteFieldFactory for examples.
                #
                # Once algebraic closures of finite fields are
                # implemented, this syntax should be superseded by
                # something like the following:
                #
                #     sage: Fpbar = GF(5).algebraic_closure('z')
                #     sage: F, e = Fpbar.subfield(3)  # e is the embedding into Fpbar
                #     sage: F
                #     Finite field in z3 of size 5^3
                #
                # This temporary solution only uses actual Conway
                # polynomials (no pseudo-Conway polynomials), since
                # pseudo-Conway polynomials are not unique, and until
                # we have algebraic closures of finite fields, there
                # is no good place to store a specific choice of
                # pseudo-Conway polynomials.
                if name is None:
                    if not (kwds.has_key('conway') and kwds['conway']):
                        raise ValueError(
                            "parameter 'conway' is required if no name given")
                    if not kwds.has_key('prefix'):
                        raise ValueError(
                            "parameter 'prefix' is required if no name given")
                    name = kwds['prefix'] + str(n)

                if kwds.has_key('conway') and kwds['conway']:
                    from conway_polynomials import conway_polynomial
                    if not kwds.has_key('prefix'):
                        raise ValueError(
                            "a prefix must be specified if conway=True")
                    if modulus is not None:
                        raise ValueError(
                            "no modulus may be specified if conway=True")
                    # The following raises a RuntimeError if no polynomial is found.
                    modulus = conway_polynomial(p, n)

                if modulus is None or isinstance(modulus, str):
                    # A string specifies an algorithm to find a suitable modulus.
                    if modulus == "default":  # for backward compatibility
                        modulus = None
                    modulus = GF(p)['x'].irreducible_element(n,
                                                             algorithm=modulus)
                elif isinstance(modulus, (list, tuple)):
                    modulus = GF(p)['x'](modulus)
                elif sage.rings.polynomial.polynomial_element.is_Polynomial(
                        modulus):
                    modulus = modulus.change_variable_name('x')
                else:
                    raise TypeError("wrong type for modulus parameter")
            else:
                raise ValueError(
                    "the order of a finite field must be a prime power.")

            return (order, name, modulus, impl, str(kwds), p, n, proof), kwds
Ejemplo n.º 32
0
def FreeMonoid(index_set=None, names=None, commutative=False, **kwds):
    r"""
    Return a free monoid on `n` generators or with the generators indexed by
    a set `I`.

    We construct free monoids by specifing either:

    - the number of generators and/or the names of the generators
    - the indexing set for the generators

    INPUT:

    - ``index_set`` -- an indexing set for the generators; if an integer,
      than this becomes `\{0, 1, \ldots, n-1\}`

    -  ``names`` -- names of generators

    - ``commutative`` -- (default: ``False``) whether the free monoid is
      commutative or not

    OUTPUT:

    A free monoid.

    EXAMPLES::

        sage: F.<a,b,c,d,e> = FreeMonoid(); F
        Free monoid on 5 generators (a, b, c, d, e)
        sage: FreeMonoid(index_set=ZZ)
        Free monoid indexed by Integer Ring

        sage: F.<x,y,z> = FreeMonoid(abelian=True); F
        Free abelian monoid on 3 generators (x, y, z)
        sage: FreeMonoid(index_set=ZZ, commutative=True)
        Free abelian monoid indexed by Integer Ring
    """
    if 'abelian' in kwds:
        commutative = kwds['abelian']
        del kwds['abelian']

    if commutative:
        from sage.monoids.free_abelian_monoid import FreeAbelianMonoid
        return FreeAbelianMonoid(index_set, names, **kwds)

    if isinstance(index_set,
                  str):  # Swap args (this works if names is None as well)
        names, index_set = index_set, names

    if index_set is None and names is not None:
        if isinstance(names, str):
            index_set = names.count(',')
        else:
            index_set = len(names)

    if index_set not in ZZ:
        if names is not None:
            names = normalize_names(len(names), names)
        from sage.monoids.indexed_free_monoid import IndexedFreeMonoid
        return IndexedFreeMonoid(index_set, names=names, **kwds)

    if names is None:
        raise ValueError("names must be specified")
    return FreeMonoid_factory(index_set, names)
Ejemplo n.º 33
0
 def create_key(self, n, names):
     n = int(n)
     names = normalize_names(n, names)
     return (n, names)
Ejemplo n.º 34
0
    def create_key_and_extra_args(self, order, name=None, modulus=None, names=None,
                                  impl=None, proof=None, **kwds):
        """
        EXAMPLES::

            sage: GF.create_key_and_extra_args(9, 'a')
            ((9, ('a',), x^2 + 2*x + 2, None, '{}', 3, 2, True), {})
            sage: GF.create_key_and_extra_args(9, 'a', foo='value')
            ((9, ('a',), x^2 + 2*x + 2, None, "{'foo': 'value'}", 3, 2, True), {'foo': 'value'})
        """
        from sage.structure.proof.all import WithProof, arithmetic
        if proof is None: proof = arithmetic()
        with WithProof('arithmetic', proof):
            order = int(order)
            if order <= 1:
                raise ValueError("the order of a finite field must be > 1.")

            if arith.is_prime(order):
                name = None
                modulus = None
                p = integer.Integer(order)
                n = integer.Integer(1)
            elif arith.is_prime_power(order):
                if not names is None: name = names
                name = normalize_names(1,name)

                p, n = arith.factor(order)[0]

                # The following is a temporary solution that allows us
                # to construct compatible systems of finite fields
                # until algebraic closures of finite fields are
                # implemented in Sage.  It requires the user to
                # specify two parameters:
                #
                # - `conway` -- boolean; if True, this field is
                #   constructed to fit in a compatible system using
                #   a Conway polynomial.
                # - `prefix` -- a string used to generate names for
                #   automatically constructed finite fields
                #
                # See the docstring of FiniteFieldFactory for examples.
                #
                # Once algebraic closures of finite fields are
                # implemented, this syntax should be superseded by
                # something like the following:
                #
                #     sage: Fpbar = GF(5).algebraic_closure('z')
                #     sage: F, e = Fpbar.subfield(3)  # e is the embedding into Fpbar
                #     sage: F
                #     Finite field in z3 of size 5^3
                #
                # This temporary solution only uses actual Conway
                # polynomials (no pseudo-Conway polynomials), since
                # pseudo-Conway polynomials are not unique, and until
                # we have algebraic closures of finite fields, there
                # is no good place to store a specific choice of
                # pseudo-Conway polynomials.
                if name is None:
                    if not (kwds.has_key('conway') and kwds['conway']):
                        raise ValueError("parameter 'conway' is required if no name given")
                    if not kwds.has_key('prefix'):
                        raise ValueError("parameter 'prefix' is required if no name given")
                    name = kwds['prefix'] + str(n)

                if kwds.has_key('conway') and kwds['conway']:
                    from conway_polynomials import conway_polynomial
                    if not kwds.has_key('prefix'):
                        raise ValueError("a prefix must be specified if conway=True")
                    if modulus is not None:
                        raise ValueError("no modulus may be specified if conway=True")
                    # The following raises a RuntimeError if no polynomial is found.
                    modulus = conway_polynomial(p, n)

                if modulus is None or isinstance(modulus, str):
                    # A string specifies an algorithm to find a suitable modulus.
                    if modulus == "default":    # for backward compatibility
                        modulus = None
                    modulus = GF(p)['x'].irreducible_element(n, algorithm=modulus)
                elif isinstance(modulus, (list, tuple)):
                    modulus = GF(p)['x'](modulus)
                elif sage.rings.polynomial.polynomial_element.is_Polynomial(modulus):
                    modulus = modulus.change_variable_name('x')
                else:
                    raise TypeError("wrong type for modulus parameter")
            else:
                raise ValueError("the order of a finite field must be a prime power.")

            return (order, name, modulus, impl, str(kwds), p, n, proof), kwds