Example #1
0
def save(x, filename, bzip2=False, gzip=False):
    """
    save(x, filename):

    Saves x to a file.  Pretty much the only constraint on x is that
    it have no circular references (it must be Python pickle-able).
    This uses the pickle module, so data you save is *guaranteed*
    to be readable by future versions of Python.

    INPUT:
       x -- almost arbitrary object
       filename -- a string

    OUTPUT:
       Creates a file named filename, from which the object x
       can be reconstructed.
    """
    from sage.misc.superseded import deprecation
    deprecation(17653, 'The sage.misc.db module is deprecated, use the load/save functions from sage.structure.sage_object instead')

    o=open(filename,"w")
    # Note: don't use protocol 2 here (use 1), since loading doesn't work
    # on my extension types.
    cPickle.dump(x,o,1)
    o.close()
    if bzip2:
        os.system("bzip2 -f %s"%filename)
    if gzip:
        os.system("gzip -f %s"%filename)
Example #2
0
def IncidenceStructureFromMatrix(M, name=None):
    """
    Deprecated function that builds an incidence structure from a matrix.

    You should now use ``designs.IncidenceStructure(incidence_matrix=M)``.

    INPUT:

    - ``M`` -- a binary matrix. Creates a set of "points" from the rows and a
      set of "blocks" from the columns.

    EXAMPLES::

        sage: BD1 = designs.IncidenceStructure(7,[[0,1,2],[0,3,4],[0,5,6],[1,3,5],[1,4,6],[2,3,6],[2,4,5]])
        sage: M = BD1.incidence_matrix()
        sage: BD2 = IncidenceStructureFromMatrix(M)
        doctest:...: DeprecationWarning: IncidenceStructureFromMatrix is deprecated.
        Please use designs.IncidenceStructure(incidence_matrix=M) instead.
        See http://trac.sagemath.org/16553 for details.
        sage: BD1 == BD2
        True
    """
    from sage.misc.superseded import deprecation
    deprecation(16553, 'IncidenceStructureFromMatrix is deprecated. Please use designs.IncidenceStructure(incidence_matrix=M) instead.')
    return IncidenceStructure(incidence_matrix=M, name=name)
Example #3
0
    def points_from_gap(self):
        """
        Literally pushes this block design over to GAP and returns the
        points of that. Other than debugging, usefulness is unclear.

        REQUIRES: GAP's Design package.

        EXAMPLES::

            sage: from sage.combinat.designs.block_design import BlockDesign
            sage: BD = BlockDesign(7,[[0,1,2],[0,3,4],[0,5,6],[1,3,5],[1,4,6],[2,3,6],[2,4,5]])
            sage: BD.points_from_gap()      # optional - gap_packages (design package)
            doctest:1: DeprecationWarning: Unless somebody protests this method will be removed, as nobody seems to know why it is there.
            See http://trac.sagemath.org/14499 for details.
            [1, 2, 3, 4, 5, 6, 7]
        """
        from sage.misc.superseded import deprecation
        deprecation(14499, ('Unless somebody protests this method will be '
                            'removed, as nobody seems to know why it is there.'))
        from sage.interfaces.gap import gap, GapElement
        from sage.sets.set import Set
        gap.load_package("design")
        gD = self._gap_()
        gP = gap.eval("BlockDesignPoints("+gD+")").replace("..",",")
        return range(eval(gP)[0],eval(gP)[1]+1)
Example #4
0
def load(filename, bzip2=False, gzip=False):
    """
    load(filename):

    Loads an object from filename and returns it.

    INPUT:
       filename -- a string that defines a valid file.  If the
          file doesn't exist then an IOError exception is raised.

    OUTPUT:
       An almost arbitrary object.
    """
    from sage.misc.superseded import deprecation
    deprecation(17653, 'The sage.misc.db module is deprecated, use the load/save functions from sage.structure.sage_object instead')

    if bzip2:
        os.system("bunzip2 -f -k %s"%(filename + ".bz2"))
    if gzip:
        os.system("cat %s.gz | gunzip -f > %s"%(filename,filename))
    assert os.path.exists(filename)
    o = open(filename,"r")
    X = cPickle.load(o)
    if bzip2 or gzip:
        os.remove(filename)
    return X
Example #5
0
def CyclicCodeFromCheckPolynomial(n,h,ignore=True):
    r"""
    If h is a polynomial over GF(q) which divides `x^n-1` then
    this constructs the code "generated by `g = (x^n-1)/h`"
    (ie, the code associated with the principle ideal `gR` in
    the ring `R = GF(q)[x]/(x^n-1)` in the usual way). The
    option "ignore" says to ignore the condition that the
    characteristic of the base field does not divide the length (the
    usual assumption in the theory of cyclic codes).

    EXAMPLES::

        sage: P.<x> = PolynomialRing(GF(3),"x")
        sage: C = codes.CyclicCodeFromCheckPolynomial(4,x + 1); C
        doctest:...
        DeprecationWarning: codes.CyclicCodeFromCheckPolynomial is now deprecated. Please use codes.CyclicCode instead.
        See http://trac.sagemath.org/20100 for details.
        [4, 1] Cyclic Code over GF(3)
        sage: C = codes.CyclicCodeFromCheckPolynomial(4,x^3 + x^2 + x + 1); C
        [4, 3] Cyclic Code over GF(3)
        sage: C.generator_matrix()
        [2 1 0 0]
        [0 2 1 0]
        [0 0 2 1]
    """
    from sage.misc.superseded import deprecation
    from sage.coding.cyclic_code import CyclicCode
    deprecation(20100, "codes.CyclicCodeFromCheckPolynomial is now deprecated. Please use codes.CyclicCode instead.")
    P = h.parent()
    x = P.gen()
    g = P((x**n-1)/h)
    return CyclicCode(length = n, generator_pol = g)
Example #6
0
    def __call__(self, x, coerce=True, hold=False, prec=None,
            dont_call_method_on_arg=False):
        """
        Note that the ``prec`` argument is deprecated. The precision for
        the result is deduced from the precision of the input. Convert
        the input to a higher precision explicitly if a result with higher
        precision is desired.::

            sage: t = exp(RealField(100)(2)); t
            7.3890560989306502272304274606
            sage: t.prec()
            100

        TESTS::

            sage: exp(2,prec=100)
            doctest:...: DeprecationWarning: The prec keyword argument is deprecated. Explicitly set the precision of the input, for example exp(RealField(300)(1)), or use the prec argument to .n() for exact inputs, e.g., exp(1).n(300), instead.
            See http://trac.sagemath.org/7490 for details.
            7.3890560989306502272304274606
        """
        if prec is not None:
            from sage.misc.superseded import deprecation
            deprecation(7490, "The prec keyword argument is deprecated. Explicitly set the precision of the input, for example exp(RealField(300)(1)), or use the prec argument to .n() for exact inputs, e.g., exp(1).n(300), instead.")
            x = GinacFunction.__call__(self, x, coerce=coerce, hold=hold,
                    dont_call_method_on_arg=dont_call_method_on_arg)
            return x.n(prec)
        return GinacFunction.__call__(self, x, coerce=coerce, hold=hold,
                dont_call_method_on_arg=dont_call_method_on_arg)
Example #7
0
def from_rank(r, n, k):
    r"""
    Returns the combination of rank ``r`` in the subsets of ``range(n)`` of
    size ``k`` when listed in lexicographic order.

    The algorithm used is based on combinadics and James McCaffrey's
    MSDN article. See :wikipedia:`Combinadic`.

    EXAMPLES::

        sage: import sage.combinat.choose_nk as choose_nk
        sage: choose_nk.from_rank(0,3,0)
        doctest:...: DeprecationWarning: choose_nk.from_rank is deprecated and will be removed. Use combination.from_rank instead
        See http://trac.sagemath.org/18674 for details.
        ()
        sage: choose_nk.from_rank(0,3,1)
        (0,)
        sage: choose_nk.from_rank(1,3,1)
        (1,)
        sage: choose_nk.from_rank(2,3,1)
        (2,)
        sage: choose_nk.from_rank(0,3,2)
        (0, 1)
        sage: choose_nk.from_rank(1,3,2)
        (0, 2)
        sage: choose_nk.from_rank(2,3,2)
        (1, 2)
        sage: choose_nk.from_rank(0,3,3)
        (0, 1, 2)
    """
    from sage.misc.superseded import deprecation
    deprecation(18674, "choose_nk.from_rank is deprecated and will be removed. Use combination.from_rank instead")
    return combination.from_rank(r, n, k)
Example #8
0
def subtract_from_line_numbers(s, n):
    r"""
    Given a string ``s`` and an integer ``n``, for any line of ``s`` which has
    the form ``'text:NUM:text'`` subtract ``n`` from NUM and return
    ``'text:(NUM-n):text'``. Return other lines of ``s`` without change.

    EXAMPLES::

        sage: from sage.misc.cython import subtract_from_line_numbers
        sage: subtract_from_line_numbers('hello:1234:hello', 3)
        doctest:...: DeprecationWarning: subtract_from_line_numbers is deprecated
        See http://trac.sagemath.org/22805 for details.
        'hello:1231:hello\n'
        sage: subtract_from_line_numbers('text:123\nhello:1234:', 3)
        'text:123\nhello:1231:\n'
    """
    from sage.misc.superseded import deprecation
    deprecation(22805, 'subtract_from_line_numbers is deprecated')

    ans = []
    for X in s.split('\n'):
        i = X.find(':')
        j = i+1 + X[i+1:].find(':')
        try:
            ans.append('%s:%s:%s\n'%(X[:i], int(X[i+1:j]) - n, X[j+1:]))
        except ValueError:
            ans.append(X)
    return '\n'.join(ans)
Example #9
0
def to_libgap(x):
    """
    Helper to convert ``x`` to a LibGAP matrix or matrix group
    element.

    Deprecated; use the ``x.gap()`` method or ``libgap(x)`` instead.

    EXAMPLES::

        sage: from sage.groups.matrix_gps.morphism import to_libgap
        sage: to_libgap(GL(2,3).gen(0))
        doctest:...: DeprecationWarning: this function is deprecated.
         Use x.gap() or libgap(x) instead.
        See https://trac.sagemath.org/25444 for details.
        [ [ Z(3), 0*Z(3) ], [ 0*Z(3), Z(3)^0 ] ]
        sage: to_libgap(matrix(QQ, [[1,2],[3,4]]))
        [ [ 1, 2 ], [ 3, 4 ] ]
    """
    from sage.misc.superseded import deprecation
    deprecation(25444, "this function is deprecated."
                " Use x.gap() or libgap(x) instead.")
    try:
        return x.gap()
    except AttributeError:
        from sage.libs.gap.libgap import libgap
        return libgap(x)
Example #10
0
    def __call__(self, x, prec=None, coerce=True, hold=False ):
        """
        Note that the ``prec`` argument is deprecated. The precision for
        the result is deduced from the precision of the input. Convert
        the input to a higher precision explicitly if a result with higher
        precision is desired.

        EXAMPLES::

            sage: t = Ei(RealField(100)(2.5)); t
            7.0737658945786007119235519625
            sage: t.prec()
            100

            sage: Ei(1.1, prec=300)
            doctest:...: DeprecationWarning: The prec keyword argument is deprecated. Explicitly set the precision of the input, for example Ei(RealField(300)(1)), or use the prec argument to .n() for exact inputs, e.g., Ei(1).n(300), instead.
            See http://trac.sagemath.org/7748 for details.
            2.16737827956340306615064476647912607220394065907142504328679588538509331805598360907980986
        """
        if prec is not None:
            from sage.misc.superseded import deprecation
            deprecation(7748, "The prec keyword argument is deprecated. Explicitly set the precision of the input, for example Ei(RealField(300)(1)), or use the prec argument to .n() for exact inputs, e.g., Ei(1).n(300), instead.")
            import mpmath
            return mpmath_utils_call(mpmath.ei, x, prec=prec)

        return BuiltinFunction.__call__(self, x, coerce=coerce, hold=hold)
Example #11
0
    def indices_cmp(self, x, y):
        r"""
        A comparison function on sets which gives a linear extension
        of the inclusion order.

        INPUT:

        - ``x``, ``y`` -- sets

        EXAMPLES::

            sage: from functools import cmp_to_key
            sage: A = Sets().WithRealizations().example(); A
            The subset algebra of {1, 2, 3} over Rational Field
            sage: sorted(A.indices(), key=cmp_to_key(A.indices_cmp))
            doctest:...: DeprecationWarning: indices_cmp is deprecated, use indices_key instead.
            See http://trac.sagemath.org/17229 for details.
            [{}, {1}, {2}, {3}, {1, 2}, {1, 3}, {2, 3}, {1, 2, 3}]
        """
        from sage.misc.superseded import deprecation
        deprecation(17229, "indices_cmp is deprecated, use indices_key instead.")

        s = (len(x) > len(y)) - (len(x) < len(y))
        if s != 0:
            return s
        return (list(x) > list(y)) - (list(x) < list(y))
Example #12
0
    def quit(self, verbose=False, timeout=None):
        """
        Quit the running subprocess.

        INPUT:

        - ``verbose`` -- (boolean, default ``False``) print a message
          when quitting this process?

        EXAMPLES::

            sage: a = maxima('y')
            sage: maxima.quit(verbose=True)
            Exiting Maxima with PID ... running .../local/bin/maxima ...
            sage: a._check_valid()
            Traceback (most recent call last):
            ...
            ValueError: The maxima session in which this object was defined is no longer running.

        Calling ``quit()`` a second time does nothing::

            sage: maxima.quit(verbose=True)
        """
        if timeout is not None:
            from sage.misc.superseded import deprecation
            deprecation(17686, 'the timeout argument to quit() is deprecated and ignored')
        if self._expect is not None:
            if verbose:
                if self.is_remote():
                    print "Exiting %r (running on %s)"%(self._expect, self._server)
                else:
                    print "Exiting %r"%(self._expect,)
            self._expect.close()
        self._reset_expect()
Example #13
0
File: kfpoly.py Project: kini/sage
def q_bin(a, b, t=None):
    r"""
    Returns the `t`-binomial coefficient `[a+b,b]_t`.

    INPUT:

    - ``a``, ``b`` -- two nonnegative integers

    By definition `[a+b,b]_t = (1-t)(1-t^2) \cdots (1-t^{a+b}) / ((1-t) \cdots (1-t^b) (1-t) \cdots (1-t^a))`.

    EXAMPLES::

        sage: from sage.combinat.sf.kfpoly import q_bin
        sage: t = PolynomialRing(ZZ, 't').gen()
        sage: q_bin(4,2, t)
        doctest:...: DeprecationWarning: please use sage.combinat.q_analogues.q_binomial instead
        See http://trac.sagemath.org/14496 for details.
        t^8 + t^7 + 2*t^6 + 2*t^5 + 3*t^4 + 2*t^3 + 2*t^2 + t + 1
        sage: q_bin(4,3, t)
        t^12 + t^11 + 2*t^10 + 3*t^9 + 4*t^8 + 4*t^7 + 5*t^6 + 4*t^5 + 4*t^4 + 3*t^3 + 2*t^2 + t + 1
    """
    from sage.misc.superseded import deprecation

    deprecation(14496, "please use sage.combinat.q_analogues.q_binomial instead")
    return sage.combinat.q_analogues.q_binomial(a + b, b, t)
def number_of_automorphisms(self, recompute=None):
    """
    Return a list of the number of automorphisms (of det 1 and -1) of
    the quadratic form.

    OUTPUT:

        an integer >= 2.

    EXAMPLES::

        sage: Q = QuadraticForm(ZZ, 3, [1, 0, 0, 1, 0, 1], unsafe_initialization=True)
        sage: Q.number_of_automorphisms()
        48

    ::

        sage: Q = DiagonalQuadraticForm(ZZ, [1,1,1,1])
        sage: Q.number_of_automorphisms()
        384
        sage: 2^4 * factorial(4)
        384
    """
    if recompute is not None:
        from sage.misc.superseded import deprecation
        deprecation(6326, "the 'recompute' argument is no longer used")

    try:
        return self.__number_of_automorphisms
    except AttributeError:
        self._compute_automorphisms()
        return self.__number_of_automorphisms
Example #15
0
def magic_transformer(line):
    r"""
    Handle input lines that start out like ``load ...`` or ``attach
    ...``.

    Since there are objects in the Sage namespace named ``load`` and
    ``attach``, IPython's automagic will not transform these lines
    into ``%load ...`` and ``%attach ...``, respectively.  Thus, we
    have to do it manually.

        EXAMPLES::

            sage: from sage.misc.interpreter import get_test_shell, magic_transformer
            sage: mt = magic_transformer()
            sage: mt.push('load /path/to/file')
            doctest:...: DeprecationWarning: Use %runfile instead of load.
            See http://trac.sagemath.org/12719 for details.
            '%runfile /path/to/file'
            sage: mt.push('attach /path/to/file')
            doctest:...: DeprecationWarning: Use %attach instead of attach.
            See http://trac.sagemath.org/12719 for details.
            '%attach /path/to/file'
            sage: mt.push('time 1+2')
            doctest:...: DeprecationWarning: Use %time instead of time.
            See http://trac.sagemath.org/12719 for details.
            '%time 1+2'
    """
    global _magic_deprecations
    for old,new in _magic_deprecations.items():
        if line.startswith(old+' '):
            from sage.misc.superseded import deprecation
            deprecation(12719, 'Use %s instead of %s.'%(new,old))
            return new+line[len(old):]
    return line
Example #16
0
    def has_key(self, key):
        r"""
        Deprecated; present just for the sake of compatibility.

        Use ``key in self`` instead.

        INPUT:

        - ``key`` -- A value identifying the element, will be converted.

        EXAMPLES::

            sage: from sage.misc.converting_dict import KeyConvertingDict
            sage: d = KeyConvertingDict(int)
            sage: d[3] = 42
            sage: d.has_key("3")
            doctest:warning...:
            DeprecationWarning: use 'key in dictionary' syntax instead
            See https://trac.sagemath.org/25281 for details.
            True
            sage: d.has_key(4)
            False
        """
        from sage.misc.superseded import deprecation
        deprecation(25281, "use 'key in dictionary' syntax instead")
        return key in self
Example #17
0
def ChooseNK(n, k):
    """
    All possible choices of k elements out of range(n) without repetitions.

    The elements of the output are tuples of Python int (and not Sage Integer).

    This was deprecated in :trac:`10534` for :func:`Combinations`
    (or ``itertools.combinations`` for doing iteration).

    EXAMPLES::

        sage: from sage.combinat.choose_nk import ChooseNK
        sage: c = ChooseNK(4,2)
        doctest:...: DeprecationWarning: ChooseNk is deprecated and will be
        removed. Use Combinations instead (or combinations from the itertools
        module for iteration)
        See http://trac.sagemath.org/10534 for details.
        sage: c.first()
        [0, 1]
        sage: c.list()
        [[0, 1], [0, 2], [0, 3], [1, 2], [1, 3], [2, 3]]
    """
    from sage.misc.superseded import deprecation
    deprecation(10534, "ChooseNk is deprecated and will be removed. Use Combinations instead (or combinations from the itertools module for iteration)")
    from sage.combinat.combination import Combinations
    return Combinations(n,k)
Example #18
0
def is_MatrixGroupHomset(x):
    r"""
    Test whether ``x`` is a matrix group homset.

    EXAMPLES::

        sage: from sage.groups.matrix_gps.homset import is_MatrixGroupHomset
        sage: is_MatrixGroupHomset(4)
        doctest:...: DeprecationWarning:
        Importing MatrixGroupHomset from here is deprecated.
        If you need to use it, please import it directly from
         sage.groups.libgap_morphism
        See https://trac.sagemath.org/25444 for details.
        False

        sage: F = GF(5)
        sage: gens = [matrix(F,2,[1,2, -1, 1]), matrix(F,2, [1,1, 0,1])]
        sage: G = MatrixGroup(gens)
        sage: from sage.groups.matrix_gps.homset import MatrixGroupHomset
        sage: M = MatrixGroupHomset(G, G)
        sage: is_MatrixGroupHomset(M)
        True
    """
    deprecation(25444, "MatrixGroupHomset is deprecated. "
                "Use GroupHomset_libgap instead.")
    return isinstance(x, MatrixGroupHomset)
Example #19
0
File: misc.py Project: ProgVal/sage
def composite_field(K, L):
    """
    Return a canonical field that contains both $K$ and $L$, if possible.
    Otherwise, raise a ValueError.

    INPUT:
        K -- field
        L -- field
    OUTPUT:
        field

    EXAMPLES:
        sage: composite_field(QQ,QQbar)
        doctest:...: DeprecationWarning: The function composite_field() is deprecated. Use get_coercion_model().common_parent() instead
        See http://trac.sagemath.org/19415 for details.
        Algebraic Field
        sage: composite_field(QQ,QQ[sqrt(2)])
        Number Field in sqrt2 with defining polynomial x^2 - 2
        sage: composite_field(QQ,QQ)
        Rational Field
        sage: composite_field(QQ,GF(7))
        Traceback (most recent call last):
        ...
        ValueError: unable to find a common field
    """
    from sage.misc.superseded import deprecation
    deprecation(19415, "The function composite_field() is deprecated. Use get_coercion_model().common_parent() instead")
    C = Sequence([K(0), L(0)]).universe()
    if C not in _Fields:
        raise ValueError("unable to find a common field")
    return C
Example #20
0
    def positive_roots(self, as_reflections=None):
        """
        Return the positive roots.

        These are roots in the Coxeter sense, that all have the
        same norm. They are given by their coefficients in the
        base of simple roots, also taken to have all the same
        norm.

        .. SEEALSO::

            :meth:`reflections`

        EXAMPLES::

            sage: W = CoxeterGroup(['A',3], implementation='reflection')
            sage: W.positive_roots()
            ((1, 0, 0), (1, 1, 0), (0, 1, 0), (1, 1, 1), (0, 1, 1), (0, 0, 1))
            sage: W = CoxeterGroup(['I',5], implementation='reflection')
            sage: W.positive_roots()
            ((1, 0),
             (-E(5)^2 - E(5)^3, 1),
             (-E(5)^2 - E(5)^3, -E(5)^2 - E(5)^3),
             (1, -E(5)^2 - E(5)^3),
             (0, 1))
        """
        if as_reflections is not None:
            from sage.misc.superseded import deprecation
            deprecation(20027, "as_reflections is deprecated; instead, use reflections()")
        return tuple(self._positive_roots_reflections().keys())
Example #21
0
    def __classcall_private__(cls, ct, c=None, use_Y=None):
        r"""
        Normalize input to ensure a unique representation.

        INPUT:

        - ``ct`` -- a Cartan type

        EXAMPLES::

            sage: M = crystals.infinity.NakajimaMonomials("E8")
            sage: M1 = crystals.infinity.NakajimaMonomials(['E',8])
            sage: M2 = crystals.infinity.NakajimaMonomials(CartanType(['E',8]))
            sage: M is M1 is M2
            True
        """
        if use_Y is not None:
            from sage.misc.superseded import deprecation
            deprecation(18895, 'use_Y is deprecated; use the set_variables() method instead.')
        else:
            use_Y = True

        cartan_type = CartanType(ct)
        n = len(cartan_type.index_set())
        c = InfinityCrystalOfNakajimaMonomials._normalize_c(c, n)
        M = super(InfinityCrystalOfNakajimaMonomials, cls).__classcall__(cls, cartan_type, c)
        if not use_Y:
            M.set_variables('A')
        else:
            M.set_variables('Y')
        return M
Example #22
0
def install_package(package=None, force=None):
    """
    This function is obsolete. Run ``sage -i PKGNAME`` from a shell
    to install a package. Use the function :func:`installed_packages`
    to list all installed packages.

    TESTS::

        sage: install_package()
        doctest:...: DeprecationWarning: use installed_packages() to list all installed packages
        See http://trac.sagemath.org/16759 for details.
        [...'atlas...'python...]
        sage: install_package("autotools")
        Traceback (most recent call last):
        ...
        NotImplementedError: installing Sage packages using 'install_package()' is obsolete.
        Run 'sage -i autotools' from a shell prompt instead
    """
    if package is not None:
        # deprecation(16759, ...)
        raise NotImplementedError("installing Sage packages using 'install_package()' is obsolete.\nRun 'sage -i {}' from a shell prompt instead".format(package))

    from sage.misc.superseded import deprecation
    deprecation(16759, "use installed_packages() to list all installed packages")
    return installed_packages()
Example #23
0
    def nth_iterate(self, f, n, normalize=False):
        r"""
        For a map of this point and a point `P` in ``self.domain()``
        this function returns the nth iterate of `P` by  this point.

        If ``normalize == True``,
        then the coordinates are automatically normalized.

        INPUT:

        - ``f`` -- a ProductProjectiveSpaces_morphism_ring with ``self`` in ``f.domain()``.

        - ``n`` -- a positive integer.

        - ``normalize`` -- Boolean (optional Default: ``False``).

        OUTPUT:

        - A point in ``self.codomain()``

        EXAMPLES::

            sage: Z.<a,b,x,y> = ProductProjectiveSpaces([1, 1], ZZ)
            sage: f = DynamicalSystem_projective([a*b, b^2, x^3 - y^3, y^2*x], domain=Z)
            sage: P = Z([2, 6, 2, 4])
            sage: P.nth_iterate(f, 2, normalize = True)
            doctest:warning
            ...
            (1 : 3 , 407 : 112)

        .. TODO:: Is there a more efficient way to do this?
        """
        from sage.misc.superseded import deprecation
        deprecation(23479, "use f.nth_iterate(P, n, normalize) instead")
        return f.nth_iterate(self, n, normalize)
Example #24
0
    def __init__(self, base_field, order):
        r"""
        TESTS:

        If ``base_field`` is not a finite field, an exception is raised::

            sage: codes.HammingCode(RR, 3)
            Traceback (most recent call last):
            ...
            ValueError: base_field has to be a finite field

        If ``order`` is not a Sage Integer or a Python int, an exception is raised::
            sage: codes.HammingCode(GF(3), 3.14)
            Traceback (most recent call last):
            ...
            ValueError: order has to be a Sage Integer or a Python int
        """
        if isinstance(base_field, (Integer, int)) and isinstance(order, Field):
            from sage.misc.superseded import deprecation
            deprecation(19930, "codes.HammingCode(r, F) is now deprecated. Please use codes.HammingCode(F, r) instead.")
            tmp = copy(order)
            order = copy(base_field)
            base_field = copy(tmp)

        if not base_field.is_finite():
            raise ValueError("base_field has to be a finite field")
        if not isinstance(order, (Integer, int)):
            raise ValueError("order has to be a Sage Integer or a Python int")

        q = base_field.order()
        length = Integer((q ** order - 1) / (q - 1))
        super(HammingCode, self).__init__(base_field, length, "Systematic", "Syndrome")
        self._dimension = length - order
Example #25
0
    def __call__(self, line, line_number):
        """
        Transform ``line``.

        INPUT:

        - ``line`` -- string. The line to be transformed.

        OUTPUT:

        A string, the transformed line.

        EXAMPLES::

            sage: from sage.misc.interpreter import get_test_shell, MagicTransformer
            sage: mt = MagicTransformer()
            sage: mt('load /path/to/file', 0)
            doctest:1: DeprecationWarning: Use %runfile instead of load.
            See http://trac.sagemath.org/12719 for details.
            '%runfile /path/to/file'
            sage: mt('attach /path/to/file', 0)
            doctest:1: DeprecationWarning: Use %attach instead of attach.
            See http://trac.sagemath.org/12719 for details.
            '%attach /path/to/file'
            sage: mt('time 1+2', 0)
            doctest:1: DeprecationWarning: Use %time instead of time.
            See http://trac.sagemath.org/12719 for details.
            '%time 1+2'
        """
        for old,new in self.deprecations.items():
            if line.startswith(old+' '):
                from sage.misc.superseded import deprecation
                deprecation(12719, 'Use %s instead of %s.'%(new,old))
                return new+line[len(old):]
        return line
Example #26
0
def CombinatorialLogarithmSeries(R=QQ):
    r"""
    Return the cycle index series of the virtual species `\Omega`, the compositional inverse
    of the species `E^{+}` of nonempty sets.

    The notion of virtual species is treated thoroughly in [BLL]_. The specific algorithm used
    here to compute the cycle index of `\Omega` is found in [Labelle]_.

    EXAMPLES:

    The virtual species `\Omega` is 'properly virtual', in the sense that its cycle index
    has negative coefficients::

        sage: from sage.combinat.species.combinatorial_logarithm import CombinatorialLogarithmSeries
        sage: CombinatorialLogarithmSeries().coefficients(4)
        doctest:...: DeprecationWarning: CombinatorialLogarithmSeries is deprecated, use CycleIndexSeriesRing(R).logarithm_series() or CycleIndexSeries().logarithm() instead
        See http://trac.sagemath.org/14846 for details.
        [0, p[1], -1/2*p[1, 1] - 1/2*p[2], 1/3*p[1, 1, 1] - 1/3*p[3]]

    Its defining property is that `\Omega \circ E^{+} = E^{+} \circ \Omega = X` (that is, that
    composition with `E^{+}` in both directions yields the multiplicative identity `X`)::

        sage: Eplus = sage.combinat.species.set_species.SetSpecies(min=1).cycle_index_series()
        sage: CombinatorialLogarithmSeries().compose(Eplus).coefficients(4)
        [0, p[1], 0, 0]
    """
    deprecation(14846, "CombinatorialLogarithmSeries is deprecated, use CycleIndexSeriesRing(R).logarithm_series() or CycleIndexSeries().logarithm() instead")
    return LogarithmCycleIndexSeries(R)
Example #27
0
File: set.py Project: chos9/sage
def EnumeratedSet(X):
    """
    Return the enumerated set associated to $X$.

    The input object $X$ must be finite.

    EXAMPLES::

        sage: EnumeratedSet([1,1,2,3])
        doctest:1: DeprecationWarning: EnumeratedSet is deprecated; use Set instead.
        See http://trac.sagemath.org/8930 for details.
        {1, 2, 3}
        sage: EnumeratedSet(ZZ)
        Traceback (most recent call last):
        ...
        ValueError: X (=Integer Ring) must be finite
    """
    from sage.misc.superseded import deprecation
    deprecation(8930, 'EnumeratedSet is deprecated; use Set instead.')
    try:
        if not X.is_finite():
            raise ValueError, "X (=%s) must be finite"%X
    except AttributeError:
        pass
    return Set_object_enumerated(X)
Example #28
0
    def parameters(self, t=None):
        """
        Returns `(t,v,k,lambda)`. Does not check if the input is a block
        design.

        INPUT:

        - ``t`` -- `t` such that the design is a `t`-design.

        EXAMPLES::

            sage: from sage.combinat.designs.block_design import BlockDesign
            sage: BD = BlockDesign(7,[[0,1,2],[0,3,4],[0,5,6],[1,3,5],[1,4,6],[2,3,6],[2,4,5]], name="FanoPlane")
            sage: BD.parameters(t=2)
            (2, 7, 3, 1)
            sage: BD.parameters(t=3)
            (3, 7, 3, 0)
        """
        if t is None:
            from sage.misc.superseded import deprecation
            deprecation(15664, "the 't' argument will become mandatory soon. 2"+
                        " is used when none is provided.")
            t = 2

        v = len(self.points())
        blks = self.blocks()
        k = len(blks[int(0)])
        b = len(blks)
        #A = self.incidence_matrix()
        #r = sum(A.rows()[0])
        lmbda = int(b/(binomial(v, t)/binomial(k, t)))
        return (t, v, k, lmbda)
Example #29
0
    def sort(self, cmp=None, key=None, reverse=False):
        """
        Sort this list *IN PLACE*.

        INPUT:

        - ``key`` - see Python ``list sort``
        
        - ``reverse`` - see Python ``list sort``

        - ``cmp`` - see Python ``list sort`` (deprecated)

        Because ``cmp`` is not allowed in Python3, it must be avoided.

        EXAMPLES::

            sage: B = Sequence([3,2,1/5])
            sage: B.sort()
            sage: B
            [1/5, 2, 3]
            sage: B.sort(reverse=True); B
            [3, 2, 1/5]

        TESTS::

            sage: B.sort(cmp = lambda x,y: cmp(y,x)); B
            doctest:...: DeprecationWarning: sorting using cmp is deprecated
            See http://trac.sagemath.org/21376 for details.
            [3, 2, 1/5]
        """
        if cmp is not None:
            from sage.misc.superseded import deprecation
            deprecation(21376, 'sorting using cmp is deprecated')
        self._require_mutable()
        list.sort(self, cmp=cmp, key=key, reverse=reverse)
Example #30
0
    def __init__(self, coordinates, metric = None):
        """
        An open subset of Euclidian space with a specific set of
        coordinates. See ``CoordinatePatch`` for details.

        INPUT:

        - ``coordinates`` -- a set of symbolic variables that serve
          as coordinates on this space.

        - ``metric`` (default: ``None``) -- a metric tensor on this
          coordinate patch.  Providing anything other than ``None``
          is currently not defined.

        EXAMPLES::

            sage: x, y, z = var('x, y, z')
            sage: S = CoordinatePatch((x, y, z)); S
            doctest:...: DeprecationWarning: Use Manifold instead.
            See http://trac.sagemath.org/24444 for details.
            Open subset of R^3 with coordinates x, y, z
        """
        from sage.symbolic.ring import is_SymbolicVariable
        from sage.misc.superseded import deprecation
        deprecation(24444, 'Use Manifold instead.')

        if not all(is_SymbolicVariable(c) for c in coordinates):
            raise TypeError("%s is not a valid vector of coordinates." % \
                coordinates)

        self._coordinates = tuple(coordinates)
        dim = len(self._coordinates)

        if metric is not None:
            raise NotImplementedError("Metric geometry not supported yet.")
    def __getitem__(self, n):
        """
        Return the `n`-th coefficient of ``self``.

        EXAMPLES::

            sage: K = Qp(13,7)
            sage: R.<t> = K[]
            sage: a = 13^7*t^3 + K(169,4)*t - 13^4
            sage: a[1]
            13^2 + O(13^4)

        Slices can be used to truncate polynomials::

            sage: a[:2]
            (13^2 + O(13^4))*t + (12*13^4 + 12*13^5 + 12*13^6 + 12*13^7 + 12*13^8 + 12*13^9 + 12*13^10 + O(13^11))

        Any other kind of slicing is deprecated or an error, see
        :trac:`18940`::

            sage: a[1:3]
            doctest:...: DeprecationWarning: polynomial slicing with a start index is deprecated, use list() and slice the resulting list instead
            See http://trac.sagemath.org/18940 for details.
            (13^2 + O(13^4))*t
            sage: a[1:3:2]
            Traceback (most recent call last):
            ...
            NotImplementedError: polynomial slicing with a step is not defined
        """
        d = len(self._relprecs)  # = degree + 1
        if isinstance(n, slice):
            start, stop, step = n.start, n.stop, n.step
            if step is not None:
                raise NotImplementedError("polynomial slicing with a step is not defined")
            if start is None:
                start = 0
            else:
                if start < 0:
                    start = 0
                from sage.misc.superseded import deprecation
                deprecation(18940, "polynomial slicing with a start index is deprecated, use list() and slice the resulting list instead")
            if stop is None or stop > d:
                stop = d
            values = ([self.base_ring().zero()] * start
                      + [self[i] for i in xrange(start, stop)])
            return self.parent()(values)

        try:
            n = n.__index__()
        except AttributeError:
            raise TypeError("list indices must be integers, not {0}".format(type(n).__name__))

        if n < 0 or n >= d:
            return self.base_ring().zero()
        if self._list is not None:
            return self._list[n]
        return self.base_ring()(self.base_ring().prime_pow(self._valbase)
            * self._poly[n], absprec = self._valbase + self._relprecs[n])
Example #32
0
def LinearExtensions(dag):
    r"""
    ``LinearExtensions`` is deprecated; use
    :meth:`sage.combinat.posets.FinitePoset.linear_extensions` or :meth:`sage.graphs.digraph.DiGraph.topological_sort_generator` instead.

    EXAMPLES::

        sage: D = DiGraph({ 0:[1,2], 1:[3], 2:[3,4] })
        sage: Poset(D).linear_extensions().list()
        [[0, 1, 2, 3, 4],
         [0, 2, 1, 3, 4],
         [0, 2, 1, 4, 3],
         [0, 2, 4, 1, 3],
         [0, 1, 2, 4, 3]]

        sage: D.topological_sort_generator().list()
        [[0, 1, 2, 3, 4],
         [0, 2, 1, 3, 4],
         [0, 2, 1, 4, 3],
         [0, 2, 4, 1, 3],
         [0, 1, 2, 4, 3]]

        sage: D = DiGraph({ "a":["b","c"], "b":["d"], "c":["d","e"] })
        sage: Poset(D).linear_extensions().list()
        [['a', 'b', 'c', 'd', 'e'],
         ['a', 'c', 'b', 'd', 'e'],
         ['a', 'c', 'b', 'e', 'd'],
         ['a', 'c', 'e', 'b', 'd'],
         ['a', 'b', 'c', 'e', 'd']]

        sage: D.topological_sort_generator().list()
        [['a', 'b', 'c', 'd', 'e'],
         ['a', 'c', 'b', 'd', 'e'],
         ['a', 'c', 'b', 'e', 'd'],
         ['a', 'c', 'e', 'b', 'd'],
         ['a', 'b', 'c', 'e', 'd']]

    TESTS::

        sage: from sage.graphs.linearextensions import LinearExtensions
        sage: D = DiGraph({ 0:[1,2], 1:[3], 2:[3,4] })
        sage: LinearExtensions(D).list()
        doctest:...: DeprecationWarning: LinearExtensions is deprecated; use FinitePoset.linear_extensions or DiGraph.topological_sort_generator instead
        See https://trac.sagemath.org/25864 for details.
        [[0, 1, 2, 3, 4],
         [0, 1, 2, 4, 3],
         [0, 2, 1, 3, 4],
         [0, 2, 1, 4, 3],
         [0, 2, 4, 1, 3]]

    """
    from sage.misc.superseded import deprecation
    deprecation(
        25864,
        "LinearExtensions is deprecated; use FinitePoset.linear_extensions or DiGraph.topological_sort_generator instead"
    )

    return LinearExtensionsOld(dag)
Example #33
0
def median(v):
    """
    Return the median (middle value) of the elements of `v`

    If `v` is empty, we define the median to be NaN, which is
    consistent with NumPy (note that R returns NULL).
    If `v` is comprised of strings, TypeError occurs.
    For elements other than numbers, the median is a result of ``sorted()``.

    This function is deprecated.  Use ``numpy.median`` or ``numpy.nanmedian``
    instead.

    INPUT:

    - `v` -- a list

    OUTPUT:

    - median element of `v`

    EXAMPLES::

        sage: median([1,2,3,4,5])
        doctest:warning...
        DeprecationWarning: sage.stats.basic_stats.median is deprecated; use numpy.median or numpy.nanmedian instead
        See https://trac.sagemath.org/29662 for details.
        3
        sage: median([e, pi])
        1/2*pi + 1/2*e
        sage: median(['sage', 'linux', 'python'])
        'python'
        sage: median([])
        NaN
        sage: class MyClass:
        ....:    def median(self):
        ....:       return 1
        sage: stats.median(MyClass())
        1
    """
    deprecation(
        29662,
        'sage.stats.basic_stats.median is deprecated; use numpy.median or numpy.nanmedian instead'
    )

    if hasattr(v, 'median'):
        return v.median()

    if not v:
        # Median of empty set defined as NaN
        return NaN
    values = sorted(v)
    if len(values) % 2:
        return values[((len(values)) + 1) // 2 - 1]
    else:
        lower = values[(len(values) + 1) // 2 - 1]
        upper = values[len(values) // 2]
        return (lower + upper) / ZZ(2)
Example #34
0
def TernaryGolayCode():
    """
    This method is now deprecated.
    Please use :class:`sage.coding.golay_code.GolayCode` instead.
    """
    from sage.misc.superseded import deprecation
    from .golay_code import GolayCode
    deprecation(20787, "codes.TernaryGolayCode is now deprecated. Please use codes.GolayCode instead.")
    return GolayCode(GF(3), False)
Example #35
0
    def __init__(self, q, names="a", modulus=None, repr="poly"):
        """
        Initialize ``self``.

        TESTS::

            sage: k.<a> = GF(2^100, modulus='strangeinput')
            Traceback (most recent call last):
            ...
            ValueError: no such algorithm for finding an irreducible polynomial: strangeinput
            sage: k.<a> = GF(2^20) ; type(k)
            <class 'sage.rings.finite_rings.finite_field_ntl_gf2e.FiniteField_ntl_gf2e_with_category'>
            sage: loads(dumps(k)) is k
            True
            sage: k1.<a> = GF(2^16)
            sage: k2.<a> = GF(2^17)
            sage: k1 == k2
            False
            sage: k3.<a> = GF(2^16, impl="pari_ffelt")
            sage: k1 == k3
            False

            sage: TestSuite(k).run()

            sage: k.<a> = GF(2^64)
            sage: k._repr_option('element_is_atomic')
            False
            sage: P.<x> = PolynomialRing(k)
            sage: (a+1)*x # indirect doctest
            (a + 1)*x
        """
        late_import()
        q = Integer(q)
        if q < 2:
            raise ValueError("q must be a 2-power")
        k = q.exact_log(2)
        if q != 1 << k:
            raise ValueError("q must be a 2-power")
        FiniteField.__init__(self, GF2, names, normalize=True)

        self._kwargs = {'repr': repr}

        from sage.rings.polynomial.polynomial_element import is_Polynomial
        if not is_Polynomial(modulus):
            from sage.misc.superseded import deprecation
            deprecation(
                16983,
                "constructing a FiniteField_ntl_gf2e without giving a polynomial as modulus is deprecated, use the more general FiniteField constructor instead"
            )
            R = GF2['x']
            if modulus is None or isinstance(modulus, str):
                modulus = R.irreducible_element(k, algorithm=modulus)
            else:
                modulus = R(modulus)

        self._cache = Cache_ntl_gf2e(self, k, modulus)
        self._modulus = modulus
Example #36
0
    def orbit_structure(self, f):
        r"""
        This function returns the pair `[m, n]` where `m` is the
        preperiod and `n` is the period of the point by ``f``.

        Every point is preperiodic over a finite field.


        INPUT:

        - ``f`` -- a :class:`ScemeMorphism_polynomial` with the point in ``f.domain()``.

        OUTPUT:

        - a list `[m, n]` of integers.

        EXAMPLES::

            sage: P.<x,y,z> = AffineSpace(GF(5), 3)
            sage: f = DynamicalSystem_affine([x^2 + y^2, y^2, z^2 + y*z], domain=P)
            sage: f.orbit_structure(P(1, 1, 1))
            [0, 6]

        ::

            sage: P.<x,y,z> = AffineSpace(GF(7), 3)
            sage: X = P.subscheme(x^2 - y^2)
            sage: f = DynamicalSystem_affine([x^2, y^2, z^2], domain=X)
            sage: f.orbit_structure(X(1, 1, 2))
            [0, 2]

        ::

            sage: P.<x,y> = AffineSpace(GF(13), 2)
            sage: f = DynamicalSystem_affine([x^2 - y^2, y^2], domain=P)
            sage: P(3, 4).orbit_structure(f)
            doctest:warning
            ...
            [2, 6]

        ::

            sage: P.<x,y> = AffineSpace(GF(13), 2)
            sage: H = End(P)
            sage: f = H([x^2 - y^2, y^2])
            sage: f.orbit_structure(P(3, 4))
            doctest:warning
            ...
            [2, 6]
        """
        from sage.misc.superseded import deprecation
        deprecation(23479, "use f.orbit_structure(P, n) instead")
        try:
            return f.orbit_structure(self)
        except AttributeError:
            raise TypeError("map must be a dynamical system")
Example #37
0
def top():
    """
    Return the 'top' or 'prstat' line that contains this running Sage
    process.

    For FreeBSD, return the line containing this running Sage process from
    'ps -axwww -o pid,user,vsz,rss,state,pri,nice,time,cpu,comm'.

    OUTPUT:

    - a string

    EXAMPLES::

        sage: top()              # random output
        '72373 python       0.0%  0:01.36   1    14+  1197   39M+   34M+   55M+  130M+'

    .. NOTE::

        The external command 'top' (http://www.unixtop.org/) is called on
        Linux, and most other operating systems. The output format of
        'top' is not consistent across all platforms and all versions of
        'top'. If the :func:`top` function does not work in Sage, you may
        need to install 'top'.

        The external command 'prstat' is called on the Solaris and
        OpenSolaris systems. That is part of Solaris, and will not need to
        be installed. The columns used in the 'prstat' output are::

            PID USERNAME  SIZE   RSS STATE  PRI NICE      TIME  CPU PROCESS/NLWP
    """
    from sage.misc.superseded import deprecation
    deprecation(21805, "the function top() is deprecated.")

    U = os.uname()[0].lower()
    pid = os.getpid()

    if U == 'linux':
        cmd = 'top -b -n 1 -p %s' % pid
    elif U == 'darwin':
        cmd = 'top -l 1 |grep "^ *%s "' % pid
    elif U == 'sunos':
        cmd = '/usr/bin/prstat -n 100000 1 1  | grep "^ *%s "' % pid
    elif U[:6] == 'cygwin':
        cmd = 'top -b -n 1 -p %s' % pid
    elif U == 'freebsd':
        cmd = 'ps -axwww -o pid,user,vsz,rss,state,pri,nice,time,cpu,comm | grep "^ *%s "' % pid
    else:
        raise NotImplementedError("top not implemented on platform %s" % U)

    r = os.popen(cmd).read()
    r = r.strip()
    i = r.rfind('\n')
    if i == -1:
        return r
    return r[i + 1:]
Example #38
0
def pari(x):
    """
    Return the PARI object constructed from a Sage/Python object.

    This is deprecated, import ``pari`` from ``sage.libs.pari.all``.
    """
    from sage.misc.superseded import deprecation
    deprecation(17451, 'gen_py.pari is deprecated, use sage.libs.pari.all.pari instead')
    from sage.libs.pari.all import pari
    return pari(x)
Example #39
0
 def __del__(self):
     if not self._printed:
         message = """ 
             html(...) will change soon to return HTML instead of
             printing it. Instead use pretty_print(html(...)) for
             strings or just pretty_print(...) for math.
         """
         message = ' '.join([l.strip() for l in message.splitlines()])
         from sage.misc.superseded import deprecation
         deprecation(18292, message)
Example #40
0
 def wrapper(*args, **kwds):
     for old_name, new_name in self.renames.items():
         if old_name in kwds and new_name not in kwds:
             if self.deprecation is not None:
                 from sage.misc.superseded import deprecation
                 deprecation(self.deprecation, "use the option "
                             "%r instead of %r" % (new_name, old_name))
             kwds[new_name] = kwds[old_name]
             del kwds[old_name]
     return func(*args, **kwds)
def MPolynomialRing(*args, **kwds):
    r"""
    This function is deprecated and will be removed in a future version of
    Sage. Please use PolynomialRing instead.

    If you have questions regarding this function and its replacement,
    please send your comments to [email protected].
    """
    from sage.misc.superseded import deprecation
    deprecation(6500, "MPolynomialRing is deprecated, use PolynomialRing instead!")
    return PolynomialRing(*args, **kwds)
Example #42
0
    def is_graded(self):
        r"""
        Deprecated, has conflicting definition of "graded" vs. "ranked"
        with posets.

        Return ``True`` if the Hasse diagram is ranked. For definition
        of ranked see :meth:`~rank_function`.
        """
        from sage.misc.superseded import deprecation
        deprecation(16998, "Use is_ranked(). Definition conflict with posets.")
        return self.is_ranked()
Example #43
0
 def make_adjacent_and_visible(self, p, e, reverse=False):
     r"""
     Move the polygon across the prescribed edge so that is adjacent,
     and make the moved polygon visible.
     """
     from sage.misc.superseded import deprecation
     deprecation(
         42,
         "Do not use .make_adjacent_and_visible(). Use .make_adjacent() instead."
     )
     self.make_adjacent(p, e, reverse=reverse)
Example #44
0
def cython_create_local_so(filename):
    r"""
    Compile filename and make it available as a loadable shared object file.

    INPUT:

    - ``filename`` - string: a Cython (.spyx) file

    OUTPUT: None

    EFFECT: A compiled, python "importable" loadable shared object file is created.

    .. note::

        Shared object files are *not* reloadable. The intent is for
        imports in other scripts. A possible development cycle might
        go thus:

        - Attach a .spyx file
        - Interactively test and edit it to your satisfaction
        - Use ``cython_create_local_so`` to create the shared object file
        - Import the .so file in other scripts

    EXAMPLES::

        sage: curdir = os.path.abspath(os.curdir)
        sage: dir = tmp_dir(); os.chdir(dir)
        sage: f = open('hello.spyx', 'w')
        sage: s = "def hello():\n    print('hello')\n"
        sage: _ = f.write(s)
        sage: f.close()
        sage: cython_create_local_so('hello.spyx')
        doctest:...: DeprecationWarning: cython_create_local_so is deprecated, call cython() with the create_local_so_file=True keyword
        See http://trac.sagemath.org/24722 for details.
        Compiling hello.spyx...
        sage: sys.path.append('.')
        sage: import hello
        sage: hello.hello()
        hello
        sage: os.chdir(curdir)

    AUTHORS:

    - David Fu (2008-04-09): initial version
    """
    from sage.misc.superseded import deprecation
    deprecation(
        24722,
        "cython_create_local_so is deprecated, call cython() with the create_local_so_file=True keyword"
    )
    cython(filename,
           compile_message=True,
           use_cache=False,
           create_local_so_file=True)
Example #45
0
def RibbonTableaux_shapeweightlength(shape, weight, length):
    """
    EXAMPLES::

        sage: sage.combinat.ribbon_tableau.RibbonTableaux_shapeweightlength([[2,1],[]], [1,1,1], 1)
        doctest:...: DeprecationWarning: this class is deprecated. Use RibbonTableaux instead
        See http://trac.sagemath.org/14101 for details.
        Ribbon tableaux of shape [2, 1] / [] and weight [1, 1, 1] with 1-ribbons
    """
    from sage.misc.superseded import deprecation
    deprecation(14101, 'this class is deprecated. Use RibbonTableaux instead')
    return RibbonTableaux(shape, weight, length)
Example #46
0
def parse_sequence(text=''):
    r"""
    This internal function was only used by the sloane_find function,
    which is now deprecated.

    TESTS::
        sage: from sage.databases.sloane import parse_sequence
        sage: parse_sequence()
        doctest:...: DeprecationWarning: The function parse_sequence is not used anymore (2012-01-01).
        See http://trac.sagemath.org/10358 for details.
    """
    deprecation(10358, "The function parse_sequence is not used anymore (2012-01-01).")
Example #47
0
    def __init__(self,
                 number_field,
                 algorithm='pari',
                 names=None,
                 gc_numbering=None,
                 _type=None):
        r"""
        Create a Galois group.

        EXAMPLES::

            sage: QuadraticField(-23,'a').galois_group()
            Galois group 2T1 (S2) with order 2 of x^2 + 23

        You can specify the variable name for the Galois closure::

            sage: G = NumberField(x^3 - 2, 'b').galois_group(names="c"); G
            Galois group 3T2 (S3) with order 6 of x^3 - 2
            sage: G._galois_closure
            Number Field in c with defining polynomial x^6 + 108

        Or have one chosen automatically (``c`` is appended to the variable name)::

            sage: G = NumberField(x^3 - 2, 'b').galois_group()
            sage: G._galois_closure
            Number Field in bc with defining polynomial x^6 + 108

        TESTS::

            sage: F.<z> = CyclotomicField(7)
            sage: G = F.galois_group()

        We test that a method inherited from PermutationGroup_generic returns
        the right type of element (see :trac:`133`)::

            sage: phi = G.random_element()
            sage: type(phi) is G.element_class
            True
            sage: phi(z) # random
            z^3
        """
        if not number_field.is_absolute():
            # We eventually want to support relative Galois groups, which currently just create the Galois group of the absolute field
            deprecation(
                28782,
                "Use .absolute_field().galois_group() if you want the Galois group of the absolute field"
            )
        if gc_numbering is None:
            gc_numbering = False if algorithm == 'magma' else True
        # For the deprecated group() method of GaloisGroup_v1
        self._type = _type
        super(GaloisGroup_v2, self).__init__(number_field, algorithm, names,
                                             gc_numbering)
Example #48
0
def hurwitz_zeta(s, x, prec=None, **kwargs):
    r"""
    The Hurwitz zeta function `\zeta(s, x)`, where `s` and `x` are complex.

    The Hurwitz zeta function is one of the many zeta functions. It
    defined as

    .. MATH::

             \zeta(s, x) = \sum_{k=0}^{\infty} (k + x)^{-s}.


    When `x = 1`, this coincides with Riemann's zeta function.
    The Dirichlet L-functions may be expressed as a linear combination
    of Hurwitz zeta functions.

    EXAMPLES:

    Symbolic evaluations::

        sage: hurwitz_zeta(x, 1)
        zeta(x)
        sage: hurwitz_zeta(4, 3)
        1/90*pi^4 - 17/16
        sage: hurwitz_zeta(-4, x)
        -1/5*x^5 + 1/2*x^4 - 1/3*x^3 + 1/30*x
        sage: hurwitz_zeta(7, -1/2)
        127*zeta(7) - 128
        sage: hurwitz_zeta(-3, 1)
        1/120

    Numerical evaluations::

        sage: hurwitz_zeta(3, 1/2).n()
        8.41439832211716
        sage: hurwitz_zeta(11/10, 1/2).n()
        12.1038134956837
        sage: hurwitz_zeta(3, x).series(x, 60).subs(x=0.5).n()
        8.41439832211716
        sage: hurwitz_zeta(3, 0.5)
        8.41439832211716

    REFERENCES:

    - :wikipedia:`Hurwitz_zeta_function`
    """
    if prec:
        deprecation(
            15095, 'the syntax hurwitz_zeta(s, x, prec) has been '
            'deprecated. Use hurwitz_zeta(s, x).n(digits=prec) '
            'instead.')
        return hurwitz_zeta_func(s, x).n(digits=prec)
    return hurwitz_zeta_func(s, x, **kwargs)
Example #49
0
    def __init__(self, q, name="a", modulus=None, repr="poly", cache=False):
        """
        Initialize ``self``.

        EXAMPLES::

            sage: k.<a> = GF(2^3)
            sage: j.<b> = GF(3^4)
            sage: k == j
            False

            sage: GF(2^3,'a') == copy(GF(2^3,'a'))
            True
            sage: TestSuite(GF(2^3, 'a')).run()
        """
        self._kwargs = {}

        if repr not in ['int', 'log', 'poly']:
            raise ValueError("Unknown representation %s" % repr)

        q = Integer(q)
        if q < 2:
            raise ValueError("q must be a prime power")
        F = q.factor()
        if len(F) > 1:
            raise ValueError("q must be a prime power")
        p = F[0][0]
        k = F[0][1]

        if q >= 1 << 16:
            raise ValueError("q must be < 2^16")

        from .finite_field_constructor import GF
        FiniteField.__init__(self, GF(p), name, normalize=False)

        self._kwargs['repr'] = repr
        self._kwargs['cache'] = cache

        from sage.rings.polynomial.polynomial_element import is_Polynomial
        if not is_Polynomial(modulus):
            from sage.misc.superseded import deprecation
            deprecation(
                16930,
                "constructing a FiniteField_givaro without giving a polynomial as modulus is deprecated, use the more general FiniteField constructor instead"
            )
            R = GF(p)['x']
            if modulus is None or isinstance(modulus, str):
                modulus = R.irreducible_element(k, algorithm=modulus)
            else:
                modulus = R(modulus)

        self._cache = Cache_givaro(self, p, k, modulus, repr, cache)
        self._modulus = modulus
Example #50
0
File: log.py Project: Etn40ff/sage
    def __call__(self,
                 x,
                 coerce=True,
                 hold=False,
                 prec=None,
                 dont_call_method_on_arg=False):
        """
        Note that the ``prec`` argument is deprecated. The precision for
        the result is deduced from the precision of the input. Convert
        the input to a higher precision explicitly if a result with higher
        precision is desired.::

            sage: t = exp(RealField(100)(2)); t
            7.3890560989306502272304274606
            sage: t.prec()
            100

        TESTS::

            sage: exp(2,prec=100)
            doctest:...: DeprecationWarning: The prec keyword argument is deprecated. Explicitly set the precision of the input, for example exp(RealField(300)(1)), or use the prec argument to .n() for exact inputs, e.g., exp(1).n(300), instead.
            See http://trac.sagemath.org/7490 for details.
            7.3890560989306502272304274606

        Ensure that :trac:`13608` is fixed::

            sage: import mpmath
            sage: a = mpmath.mpf('0.5')
            sage: exp(a)
            mpf('1.6487212707001282')
            sage: a.exp
            -1
        """
        if prec is not None:
            from sage.misc.superseded import deprecation
            deprecation(
                7490,
                "The prec keyword argument is deprecated. Explicitly set the precision of the input, for example exp(RealField(300)(1)), or use the prec argument to .n() for exact inputs, e.g., exp(1).n(300), instead."
            )
            x = GinacFunction.__call__(
                self,
                x,
                coerce=coerce,
                hold=hold,
                dont_call_method_on_arg=dont_call_method_on_arg)
            return x.n(prec)
        return GinacFunction.__call__(
            self,
            x,
            coerce=coerce,
            hold=hold,
            dont_call_method_on_arg=dont_call_method_on_arg)
Example #51
0
    def __init__(self, l):
        """
        TESTS::

            sage: F = FiniteCombinatorialClass([1,2,3])
            doctest:warning...:
            DeprecationWarning: Please use FiniteEnumeratedSets instead.
            See http://trac.sagemath.org/13552 for details.
            sage: F == loads(dumps(F))
            True
        """
        deprecation(13552, "Please use FiniteEnumeratedSets instead.")
        self.l = list(l)  # Probably would be better to use a tuple
Example #52
0
def SemistandardSkewTableaux_p(*args, **kargs):
    """
    EXAMPLES::

        sage: sage.combinat.skew_tableau.SemistandardSkewTableaux_p([[2,1],[]])
        doctest:1: DeprecationWarning: this class is deprecated. Use SemistandardSkewTableaux_shape instead
        See http://trac.sagemath.org/9265 for details.
        Semistandard skew tableaux of shape [[2, 1], []]
    """
    deprecation(
        9265,
        'this class is deprecated. Use SemistandardSkewTableaux_shape instead')
    return SemistandardSkewTableaux_shape(*args, **kargs)
Example #53
0
def StandardSkewTableaux_n(*args, **kargs):
    """
    EXAMPLES::

        sage: sage.combinat.skew_tableau.StandardSkewTableaux_n(2)
        doctest:1: DeprecationWarning: this class is deprecated. Use StandardSkewTableaux_size instead
        See http://trac.sagemath.org/9265 for details.
        Standard skew tableaux of size 2
    """
    deprecation(
        9265,
        'this class is deprecated. Use StandardSkewTableaux_size instead')
    return StandardSkewTableaux(*args, **kargs)
Example #54
0
def graphics_filename(ext='.png'):
    """
    Deprecated SageNB graphics filename

    You should just use :meth:`tmp_filename`.

    When run from the Sage notebook, return the next available canonical
    filename for a plot/graphics file in the current working directory.
    Otherwise, return a temporary file inside ``SAGE_TMP``.

    INPUT:

    - ``ext`` -- (default: ``".png"``) A file extension (including the dot)
      for the filename.

    OUTPUT:

    The path of the temporary file created. In the notebook, this is
    a filename without path in the current directory. Otherwise, this
    an absolute path.

    EXAMPLES::

        sage: from sage.misc.temporary_file import graphics_filename
        sage: print(graphics_filename())  # random, typical filename for sagenb
        sage0.png

    TESTS:

    When doctesting, this returns instead a random temporary file.
    We check that it's a file inside ``SAGE_TMP`` and that the extension
    is correct::

        sage: fn = graphics_filename(ext=".jpeg")
        sage: fn.startswith(str(SAGE_TMP))
        True
        sage: fn.endswith('.jpeg')
        True
    """
    import sage.plot.plot
    if sage.plot.plot.EMBEDDED_MODE:
        # Don't use this unsafe function except in the notebook, #15515
        i = 0
        while os.path.exists('sage%d%s' % (i, ext)):
            i += 1
        filename = 'sage%d%s' % (i, ext)
        return filename
    else:
        from sage.misc.superseded import deprecation
        deprecation(17234, 'use tmp_filename instead')
        return tmp_filename(ext=ext)
Example #55
0
    def r_quotient(self, length):
        """
      This method is deprecated.

      EXAMPLES::

          sage: SkewPartition([[3, 3, 2, 1], [2, 1]]).r_quotient(2)
          doctest:1: DeprecationWarning: r_quotient is deprecated. Use quotient instead.
          See http://trac.sagemath.org/5790 for details.
          [[[3], []], [[], []]]
      """
        from sage.misc.superseded import deprecation
        deprecation(5790, 'r_quotient is deprecated. Use quotient instead.')
        return self.quotient(length)
Example #56
0
    def __init__(self,
                 base_field,
                 length,
                 designed_distance,
                 primitive_root=None,
                 offset=1,
                 jump_size=1,
                 b=0):
        """
        TESTS:

        ``designed_distance`` must be between 1 and ``length`` (inclusive),
        otherwise an exception is raised::

            sage: C = codes.BCHCode(GF(2), 15, 16)
            Traceback (most recent call last):
            ...
            ValueError: designed_distance must belong to [1, n]
        """
        if not (designed_distance <= length and designed_distance > 0):
            raise ValueError("designed_distance must belong to [1, n]")
        if base_field in ZZ and designed_distance in Fields:
            from sage.misc.superseded import deprecation
            deprecation(
                20335,
                "codes.BCHCode(n, designed_distance, F, b=0) is now deprecated. Please use the new signature instead."
            )
            (length, designed_distance, base_field) = (base_field, length,
                                                       designed_distance)
            offset = b
        if base_field not in Fields or not base_field.is_finite():
            raise ValueError("base_field has to be a finite field")

        q = base_field.cardinality()
        s = Zmod(length)(q).multiplicative_order()
        if gcd(jump_size, q**s - 1) != 1:
            raise ValueError("jump_size must be coprime with the order of "
                             "the multiplicative group of the splitting field")

        D = [(offset + jump_size * i) % length
             for i in range(designed_distance - 1)]

        super(BCHCode, self).__init__(field=base_field,
                                      length=length,
                                      D=D,
                                      primitive_root=primitive_root)
        self._default_decoder_name = "UnderlyingGRS"
        self._jump_size = jump_size
        self._offset = offset
        self._designed_distance = designed_distance
Example #57
0
def save_db(x):
    """
    Save x to the database.  x must define a filename method.
    """
    from sage.misc.superseded import deprecation
    deprecation(
        17653,
        'The sage.misc.db module is deprecated, use the load/save functions from sage.structure.sage_object instead'
    )

    path()
    fn = PATH + x.filename()
    save(x, fn)
    os.system("bzip2 -f %s" % fn)
Example #58
0
def register_sage_classes():
    """
    Register all relevant Sage classes in the :class:`numbers`
    hierarchy.

    EXAMPLES::

        sage: import numbers
        sage: isinstance(5, numbers.Integral)
        True
        sage: isinstance(5, numbers.Number)
        True
        sage: isinstance(5/1, numbers.Integral)
        False
        sage: isinstance(22/7, numbers.Rational)
        True
        sage: isinstance(1.3, numbers.Real)
        True
        sage: isinstance(CC(1.3), numbers.Real)
        False
        sage: isinstance(CC(1.3 + I), numbers.Complex)
        True
        sage: isinstance(RDF(1.3), numbers.Real)
        True
        sage: isinstance(CDF(1.3, 4), numbers.Complex)
        True
        sage: isinstance(AA(sqrt(2)), numbers.Real)
        True
        sage: isinstance(QQbar(I), numbers.Complex)
        True

    This doesn't work with symbolic expressions at all::

        sage: isinstance(pi, numbers.Real)
        False
        sage: isinstance(I, numbers.Complex)
        False
        sage: isinstance(sqrt(2), numbers.Real)
        False

    Because we do this, NumPy's ``isscalar()`` recognizes Sage types::

        sage: from numpy import isscalar
        sage: isscalar(3.141)
        True
        sage: isscalar(4/17)
        True
    """
    from sage.misc.superseded import deprecation
    deprecation(32641, "register_sage_classes is a deprecated no-op")
Example #59
0
def WeightedIntegerVectors_nweight(n, weight):
    """
    Deprecated in :trac:`12453`. Use :class:`WeightedIntegerVectors` instead.

    EXAMPLES::

        sage: sage.combinat.integer_vector_weighted.WeightedIntegerVectors_nweight(7, [2,2])
        doctest:...: DeprecationWarning: this class is deprecated. Use WeightedIntegerVectors instead
        See http://trac.sagemath.org/12453 for details.
        Integer vectors of 7 weighted by [2, 2]
    """
    from sage.misc.superseded import deprecation
    deprecation(12453, 'this class is deprecated. Use WeightedIntegerVectors instead')
    return WeightedIntegerVectors(n, weight)
Example #60
0
def incomplete_gamma(*args, **kwds):
    """
        Deprecated name for :class:`Function_gamma_inc`.

    TESTS::

        sage: incomplete_gamma(1,1)
        doctest:...: DeprecationWarning: Please use gamma_inc().
        See http://trac.sagemath.org/16697 for details.
        e^(-1)
    """
    from sage.misc.superseded import deprecation
    deprecation(16697, 'Please use gamma_inc().')
    return gamma_inc(*args, **kwds)