Example #1
0
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.
        {1, 2, 3}
        sage: EnumeratedSet(ZZ)
        Traceback (most recent call last):
        ...
        ValueError: X (=Integer Ring) must be finite
    """
    from sage.misc.misc import deprecation

    deprecation("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 #2
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.
            2.16737827956340306615064476647912607220394065907142504328679588538509331805598360907980986
        """
        if prec is not None:
            from sage.misc.misc import deprecation
            deprecation("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 #3
0
    def coef(self, P):
        r"""
        Synonym for :meth:`coefficient`

        .. WARNING::
         
            This method is deprecated. It will be removed in a future
            release of Sage. Please use the ``coefficient(P)`` method
            instead.

        EXAMPLES::

            sage: x,y = AffineSpace(2, GF(5), names='xy').gens()
            sage: C = Curve(y^2 - x^9 - x)
            sage: pts = C.rational_points(); pts
            [(0, 0), (2, 2), (2, 3), (3, 1), (3, 4)]
            sage: D = C.divisor(pts[0])
            sage: D.coefficient(pts[0])
            1
        """
        from sage.misc.misc import deprecation
        deprecation(
            "This method is deprecated. It will be removed in a future release of Sage. Please use the coefficient() method instead."
        )
        return self.coefficient(P)
Example #4
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.
            2.16737827956340306615064476647912607220394065907142504328679588538509331805598360907980986
        """
        if prec is not None:
            from sage.misc.misc import deprecation
            deprecation(
                "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 #5
0
File: log.py Project: dagss/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.
            7.3890560989306502272304274606
        """
        if prec is not None:
            from sage.misc.misc import deprecation
            deprecation("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 #6
0
def sqrt(x):
    """
    Returns a square root of x.

    This function (``numerical_sqrt``) is deprecated.  Use ``sqrt(x,
    prec=n)`` instead.
    
    EXAMPLES::
    
        sage: numerical_sqrt(10.1)
        doctest:1: DeprecationWarning: numerical_sqrt is deprecated, use sqrt(x, prec=n) instead
        3.17804971641414
        sage: numerical_sqrt(9)
        3
    """
    from sage.misc.misc import deprecation

    deprecation("numerical_sqrt is deprecated, use sqrt(x, prec=n) instead")
    try:
        return x.sqrt()
    except (AttributeError, ValueError):
        try:
            return RDF(x).sqrt()
        except TypeError:
            return CDF(x).sqrt()
Example #7
0
def _normalize_integral_input(f, v=None, a=None, b=None):
    r"""
    Validate and return variable and endpoints for an integral.
    
    INPUT:
    
    - ``f`` -- an expression to integrate;
    
    - ``v`` -- a variable of integration or a triple;
    
    - ``a`` -- (optional) the left endpoint of integration;
    
    - ``b`` -- (optional) the right endpoint of integration.
    
    It is also possible to pass last three parameters in ``v`` as a triple.
    
    OUPUT:
    
    - a tuple of ``f``, ``v``, ``a``, and ``b``.
    
    EXAMPLES::
    
        sage: from sage.symbolic.integration.integral import \
        ...       _normalize_integral_input
        sage: _normalize_integral_input(x^2, x, 0, 3)
        (x^2, x, 0, 3)
        sage: _normalize_integral_input(x^2, [x, 0, 3], None, None)
        (x^2, x, 0, 3)
        sage: _normalize_integral_input(x^2, [0, 3], None, None)
        doctest:...: DeprecationWarning:
        Variable of integration should be specified explicitly.
        (x^2, x, 0, 3)
        sage: _normalize_integral_input(x^2, [x], None, None)
        (x^2, x, None, None)
    """
    if isinstance(v, (list, tuple)) and a is None and b is None:
        if len(v) == 1:  # bare variable in a tuple
            v = v[0]
        elif len(v) == 2:  # endpoints only
            a, b = v
            v = None
        elif len(v) == 3:  # variable and endpoints
            v, a, b = v
        else:
            raise ValueError("invalid input %s - please use variable, "
                             "with or without two endpoints" % repr(v))
    elif b is None and a is not None:
        # two arguments, must be endpoints
        v, a, b = None, v, a
    if v is None:
        from sage.misc.misc import deprecation
        deprecation("Variable of integration should be specified explicitly.")
        v = f.default_variable()
        if isinstance(f, Function):  # a bare function like sin
            f = f(v)
    if (a is None) ^ (b is None):
        raise TypeError('only one endpoint was given!')
    return f, v, a, b
Example #8
0
def _normalize_integral_input(f, v=None, a=None, b=None):
    r"""
    Validate and return variable and endpoints for an integral.
    
    INPUT:
    
    - ``f`` -- an expression to integrate;
    
    - ``v`` -- a variable of integration or a triple;
    
    - ``a`` -- (optional) the left endpoint of integration;
    
    - ``b`` -- (optional) the right endpoint of integration.
    
    It is also possible to pass last three parameters in ``v`` as a triple.
    
    OUPUT:
    
    - a tuple of ``f``, ``v``, ``a``, and ``b``.
    
    EXAMPLES::
    
        sage: from sage.symbolic.integration.integral import \
        ...       _normalize_integral_input
        sage: _normalize_integral_input(x^2, x, 0, 3)
        (x^2, x, 0, 3)
        sage: _normalize_integral_input(x^2, [x, 0, 3], None, None)
        (x^2, x, 0, 3)
        sage: _normalize_integral_input(x^2, [0, 3], None, None)
        doctest:...: DeprecationWarning:
        Variable of integration should be specified explicitly.
        (x^2, x, 0, 3)
        sage: _normalize_integral_input(x^2, [x], None, None)
        (x^2, x, None, None)
    """
    if isinstance(v, (list, tuple)) and a is None and b is None:
        if len(v) == 1: # bare variable in a tuple
            v = v[0]
        elif len(v) == 2: # endpoints only
            a, b = v
            v = None
        elif len(v) == 3: # variable and endpoints
            v, a, b = v
        else:
            raise ValueError("invalid input %s - please use variable, "
                             "with or without two endpoints" % repr(v))
    elif b is None and a is not None:
        # two arguments, must be endpoints
        v, a, b = None, v, a
    if v is None:
        from sage.misc.misc import deprecation
        deprecation("Variable of integration should be specified explicitly.")
        v = f.default_variable()
        if isinstance(f, Function):  # a bare function like sin
            f = f(v)
    if (a is None) ^ (b is None):
        raise TypeError('only one endpoint was given!')
    return f, v, a, b
Example #9
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.deprecated is not None:
                 deprecation("use the option %r instead of %r"%(new_name,old_name),
                     version=self.deprecated)
             kwds[new_name] = kwds[old_name]
             del kwds[old_name]
     return func(*args, **kwds)
Example #10
0
def jsmath(x, mode='display'):
    r'''
    Attempt to nicely render an arbitrary SAGE object wih jsmath typesetting.
    Tries to call ._latex_() on x. If that fails, it will render a string
    representation of x.

    .. warning::

        2009-04: This function is deprecated; use ``html`` instead:
        replace ``jsmath('MATH', mode='display')`` with ``html('$$MATH$$')``,
        and replace ``jsmath('MATH', mode='inline')`` with ``html('$MATH$')``.

    INPUT:
        x -- the object to render
        mode -- 'display' for displaymath or 'inline' for inline math

    OUTPUT:
        A string of html that contains the LaTeX represntation of x. In the
        notebook this gets embedded into the cell.

    EXAMPLES::
    
        sage: from sage.misc.latex import jsmath
        sage: f = maxima('1/(x^2+1)')
        sage: g = f.integrate()
        sage: jsmath(f)
        ... DeprecationWarning: The jsmath function is deprecated.  Use html('$math$') for inline mode or html('$$math$$') for display mode.
        # -*- coding: utf-8 -*-
        <html><font color='black'><div class="math">{{1}\over{x^2+1}}</div></font></html>
        sage: jsmath(g, 'inline')
        <html><font color='black'><span class="math">\tan^{-1} x</span></font></html>
        sage: jsmath('\int' + latex(f) + '\ dx=' + latex(g))
        <html><font color='black'><div class="math">\int{{1}\over{x^2+1}}\ dx=\tan^{-1} x</div></font></html>

    AUTHORS: 

    - William Stein (2006-10): general layout (2006-10)

    - Bobby Moretti (2006-10): improvements, comments, documentation
    '''
    from sage.misc.misc import deprecation
    from sage.misc.html import html
    deprecation("The jsmath function is deprecated.  Use html('$math$') for inline mode or html('$$math$$') for display mode.")    
    if mode == 'display':
        delimiter = '$$'
    elif mode == 'inline':
        delimiter = '$'
    else:
        raise ValueError, "mode must be either 'display' or 'inline'"
    try:
        # try to get a latex representation of the object
        x = x._latex_()
    except AttributeError:
        # otherwise just get the string representation
        x = str(x)
    return html(delimiter + x + delimiter)
Example #11
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.::

            sage: t = gamma(RealField(100)(2.5)); t
            1.3293403881791370204736256125
            sage: t.prec()
            100

            sage: gamma(6, prec=53)
            doctest:...: DeprecationWarning: The prec keyword argument is deprecated. Explicitly set the precision of the input, for example gamma(RealField(300)(1)), or use the prec argument to .n() for exact inputs, e.g., gamma(1).n(300), instead.
            120.000000000000

        TESTS::

            sage: gamma(pi,prec=100)
            2.2880377953400324179595889091

            sage: gamma(3/4,prec=100)
            1.2254167024651776451290983034
        """
        if prec is not None:
            from sage.misc.misc import deprecation
            deprecation(
                "The prec keyword argument is deprecated. Explicitly set the precision of the input, for example gamma(RealField(300)(1)), or use the prec argument to .n() for exact inputs, e.g., gamma(1).n(300), instead."
            )
            import mpmath
            return mpmath_utils.call(mpmath.gamma, x, prec=prec)

        # this is a kludge to keep
        #     sage: Q.<i> = NumberField(x^2+1)
        #     sage: gamma(i)
        # working, since number field elements cannot be coerced into SR
        # without specifying an explicit embedding into CC any more
        try:
            res = GinacFunction.__call__(self, x, coerce=coerce, hold=hold)
        except TypeError, err:
            # the __call__() method returns a TypeError for fast float arguments
            # as well, we only proceed if the error message says that
            # the arguments cannot be coerced to SR
            if not str(err).startswith("cannot coerce"):
                raise

            from sage.misc.misc import deprecation
            deprecation(
                "Calling symbolic functions with arguments that cannot be coerced into symbolic expressions is deprecated."
            )
            parent = RR if prec is None else RealField(prec)
            try:
                x = parent(x)
            except (ValueError, TypeError):
                x = parent.complex_field()(x)
            res = GinacFunction.__call__(self, x, coerce=coerce, hold=hold)
Example #12
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.deprecated is not None:
                 deprecation("use the option %r instead of %r" %
                             (new_name, old_name),
                             version=self.deprecated)
             kwds[new_name] = kwds[old_name]
             del kwds[old_name]
     return func(*args, **kwds)
Example #13
0
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.misc import deprecation
    deprecation("MPolynomialRing is deprecated, use PolynomialRing instead!")
    return PolynomialRing(*args, **kwds)
Example #14
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.::

            sage: t = gamma(RealField(100)(2.5)); t
            1.3293403881791370204736256125
            sage: t.prec()
            100

            sage: gamma(6, prec=53)
            doctest:...: DeprecationWarning: The prec keyword argument is deprecated. Explicitly set the precision of the input, for example gamma(RealField(300)(1)), or use the prec argument to .n() for exact inputs, e.g., gamma(1).n(300), instead.
            120.000000000000

        TESTS::

            sage: gamma(pi,prec=100)
            2.2880377953400324179595889091

            sage: gamma(3/4,prec=100)
            1.2254167024651776451290983034
        """
        if prec is not None:
            from sage.misc.misc import deprecation
            deprecation("The prec keyword argument is deprecated. Explicitly set the precision of the input, for example gamma(RealField(300)(1)), or use the prec argument to .n() for exact inputs, e.g., gamma(1).n(300), instead.")
            import mpmath
            return mpmath_utils.call(mpmath.gamma, x, prec=prec)

        # this is a kludge to keep
        #     sage: Q.<i> = NumberField(x^2+1)
        #     sage: gamma(i)
        # working, since number field elements cannot be coerced into SR
        # without specifying an explicit embedding into CC any more
        try:
            res = GinacFunction.__call__(self, x, coerce=coerce, hold=hold)
        except TypeError, err:
            # the __call__() method returns a TypeError for fast float arguments
            # as well, we only proceed if the error message says that
            # the arguments cannot be coerced to SR
            if not str(err).startswith("cannot coerce"):
                raise

            from sage.misc.misc import deprecation
            deprecation("Calling symbolic functions with arguments that cannot be coerced into symbolic expressions is deprecated.")
            parent = RR if prec is None else RealField(prec)
            try:
                x = parent(x)
            except (ValueError, TypeError):
                x = parent.complex_field()(x)
            res = GinacFunction.__call__(self, x, coerce=coerce, hold=hold)
Example #15
0
def DiamondPoset(*args, **kwds):
    r"""
    This function is deprecated and will be removed in a future
    version of Sage. Please use ``Posets.DiamondPoset`` instead.

    TESTS::

        sage: DiamondPoset(3)
        doctest:1: DeprecationWarning: DiamondPoset is deprecated, use Posets.DiamondPoset instead!
        Finite lattice containing 3 elements
    """
    deprecation("%s is deprecated, use Posets.%s instead!" % \
           ("DiamondPoset","DiamondPoset"))
    return Posets.DiamondPoset(*args, **kwds)
Example #16
0
def BooleanLattice(*args, **kwds):
    r"""
    This function is deprecated and will be removed in a future
    version of Sage. Please use ``Posets.BooleanLattice`` instead.

    TESTS::

        sage: BooleanLattice(3)
        doctest:1: DeprecationWarning: BooleanLattice is deprecated, use Posets.BooleanLattice instead!
        Finite lattice containing 8 elements
    """
    deprecation("%s is deprecated, use Posets.%s instead!" % \
           ("BooleanLattice", "BooleanLattice"))
    return Posets.BooleanLattice(*args, **kwds)
Example #17
0
def PosetOfIntegerCompositions(*args, **kwds):
    r"""
    This function is deprecated and will be removed in a future
    version of Sage. Please use ``Posets.IntegerCompositions`` instead.

    TESTS::

        sage: PosetOfIntegerCompositions(3)
        doctest:1: DeprecationWarning: PosetOfIntegerCompositions is deprecated, use Posets.IntegerCompositions instead!
        Finite poset containing 4 elements
    """
    deprecation("%s is deprecated, use Posets.%s instead!" % \
           ("PosetOfIntegerCompositions","IntegerCompositions"))
    return Posets.IntegerCompositions(*args, **kwds)
Example #18
0
 def string_rep(self):
     r"""
     Returns the string representation of the alphabet.
     
     TESTS::
     
         sage: from sage.combinat.words.alphabet import OrderedAlphabet_Finite
         sage: OrderedAlphabet_Finite([1, 3, 2]).string_rep()
         doctest:1: DeprecationWarning: string_rep is deprecated, use __repr__ instead!
         'Ordered Alphabet [1, 3, 2]'
     """
     from sage.misc.misc import deprecation
     deprecation("string_rep is deprecated, use __repr__ instead!")
     return self.__repr__()
Example #19
0
def RandomPoset(*args, **kwds):
    r"""
    This function is deprecated and will be removed in a future
    version of Sage. Please use ``Posets.RandomPoset`` instead.

    TESTS::

        sage: RandomPoset(17,.15)
        doctest:1: DeprecationWarning: RandomPoset is deprecated, use Posets.RandomPoset instead!
        Finite poset containing 17 elements
    """
    deprecation("%s is deprecated, use Posets.%s instead!" % \
           ("RandomPoset","RandomPoset"))
    return Posets.RandomPoset(*args, **kwds)
Example #20
0
def SymmetricGroupWeakOrderPoset(*args, **kwds):
    r"""
    This function is deprecated and will be removed in a future
    version of Sage. Please use ``Posets.SymmetricGroupWeakOrderPoset`` instead.

    TESTS::

        sage: SymmetricGroupWeakOrderPoset(3)
        doctest:1: DeprecationWarning: SymmetricGroupWeakOrderPoset is deprecated, use Posets.SymmetricGroupWeakOrderPoset instead!
        Finite poset containing 6 elements
    """
    deprecation("%s is deprecated, use Posets.%s instead!" % \
           ("SymmetricGroupWeakOrderPoset","SymmetricGroupWeakOrderPoset"))
    return Posets.SymmetricGroupWeakOrderPoset(*args, **kwds)
Example #21
0
    def string_rep(self):
        r"""
        Returns the string representation of the alphabet.
        
        TESTS::
        
            sage: from sage.combinat.words.alphabet import OrderedAlphabet_Finite
            sage: OrderedAlphabet_Finite([1, 3, 2]).string_rep()
            doctest:1: DeprecationWarning: string_rep is deprecated, use __repr__ instead!
            'Ordered Alphabet [1, 3, 2]'
        """
        from sage.misc.misc import deprecation

        deprecation("string_rep is deprecated, use __repr__ instead!")
        return self.__repr__()
Example #22
0
    def range(self):
        """
        Returns the codomain of this morphism.  This method is
        deprecated.  Please use :meth:`codomain` instead.

        EXAMPLES::

            sage: G = PSL(2,7)
            sage: D, iota1, iota2, pr1, pr2 = G.direct_product(G)
            sage: pr1.range()
            doctest... DeprecationWarning: (Since Sage Version 5.0) range is deprecated. Please use codomain instead.
            Permutation Group with generators [(3,7,5)(4,8,6), (1,2,6)(3,4,8)]
        """
        deprecation('range is deprecated. Please use codomain instead.', 'Sage Version 5.0')
        return self.codomain()
Example #23
0
    def __init__(self):
        """
        Issue deprecation warnings for the old networkx XDiGraph formats

        EXAMPLE::

            sage: from sage.graphs.base.graph_backends import NetworkXDiGraphDeprecated
            sage: NetworkXDiGraphDeprecated()
            doctest:...
            <class 'sage.graphs.base.graph_backends.NetworkXDiGraphDeprecated'>
        """
        from sage.misc.misc import deprecation
        deprecation("Your digraph object is saved in an old format since networkx "+
                    "was updated to 1.0.1. You can re-save your digraph by typing "+
                    "digraph.save(filename) to make this warning go away.")
Example #24
0
    def range(self):
        """
        Returns the codomain of this morphism.  This method is
        deprecated.  Please use :meth:`codomain` instead.

        EXAMPLES::

            sage: G = PSL(2,7)
            sage: D, iota1, iota2, pr1, pr2 = G.direct_product(G)
            sage: pr1.range()
            doctest... DeprecationWarning: (Since Sage Version 5.0) range is deprecated. Please use codomain instead.
            Permutation Group with generators [(3,7,5)(4,8,6), (1,2,6)(3,4,8)]
        """
        deprecation('range is deprecated. Please use codomain instead.',
                    'Sage Version 5.0')
        return self.codomain()
Example #25
0
def adapt_to_callable(f, nargs=None):
    """
    Tries to make every function in f into a (fast) callable
    function, returning a new list of functions and the expected
    arguments.
    
    INPUT:
    
    - ``f`` -- a list of functions; these can be symbolic expressions,
            polynomials, etc
            
    -  ``nargs`` -- number of input args to have in the output functions
    
    OUTPUT: functions, expected arguments
    """
    from sage.misc.misc import deprecation
    deprecation(
        "adapt_to_callable is a deprecated function.  Please use functions from sage.misc.plot instead."
    )

    try:
        from sage.symbolic.callable import is_CallableSymbolicExpression
        if sum([is_CallableSymbolicExpression(z) for z in f]):
            # Sum to get common universe; this works since f is
            # callable, and summing gets the arguments in the right
            # order.
            vars = sum(f).args()
        else:
            # Otherwise any free variable names in any order
            try:
                vars = tuple(sorted(set(sum([z.variables() for z in f], ()))))
                if len(vars) > 1:
                    from sage.misc.misc import deprecation
                    deprecation(
                        "Substitution using function-call syntax and unnamed arguments is deprecated and will be removed from a future release of Sage; you can use named arguments instead, like EXPR(x=..., y=...)"
                    )
            except AttributeError:
                vars = ()
                f = [fast_float_constant(x) for x in f]
    except TypeError:
        vars = ()
        f = [fast_float_constant(x) for x in f]

    if nargs is not None and len(vars) != nargs:
        vars = (vars + ('_', ) * nargs)[:nargs]

    return fast_float(f, *vars), vars
Example #26
0
    def is_distributive_lattice_fastest(self):
        r"""
        This function is deprecated and will be removed in a future
        version of Sage. Please use ``self.is_distributive_lattice()``
        instead.

        TESTS::

            sage: from sage.combinat.posets.hasse_diagram import HasseDiagram
            sage: H = HasseDiagram({0:[1,3,2],1:[4],2:[4,5,6],3:[6],4:[7],5:[7],6:[7],7:[]})
            sage: H.is_distributive_lattice_fastest()
            doctest:1: DeprecationWarning: is_distributive_lattice_fastest is deprecated, use is_distributive_lattice instead!
            False
        """
        from sage.misc.misc import deprecation
        deprecation("is_distributive_lattice_fastest is deprecated, use is_distributive_lattice instead!")
        return self.is_distributive_lattice()
Example #27
0
    def is_distributive_lattice_fastest(self):
        r"""
        This function is deprecated and will be removed in a future
        version of Sage. Please use ``self.is_distributive_lattice()``
        instead.

        TESTS::

            sage: from sage.combinat.posets.hasse_diagram import HasseDiagram
            sage: H = HasseDiagram({0:[1,3,2],1:[4],2:[4,5,6],3:[6],4:[7],5:[7],6:[7],7:[]})
            sage: H.is_distributive_lattice_fastest()
            doctest:1: DeprecationWarning: is_distributive_lattice_fastest is deprecated, use is_distributive_lattice instead!
            False
        """
        from sage.misc.misc import deprecation
        deprecation("is_distributive_lattice_fastest is deprecated, use is_distributive_lattice instead!")
        return self.is_distributive_lattice()
Example #28
0
def lngamma(t):
    r"""
    This method is deprecated, please use
    :meth:`~sage.functions.other.log_gamma` instead.

    See the :meth:`~sage.functions.other.log_gamma` function for '
    documentation and examples.

    EXAMPLES::
        
        sage: lngamma(RR(6))
        doctest:...: DeprecationWarning: The method lngamma() is deprecated. Use log_gamma() instead.
        4.78749174278205
    """
    from sage.misc.misc import deprecation
    deprecation("The method lngamma() is deprecated. Use log_gamma() instead.")
    return log_gamma(t)
    def __call__(self, n, z, 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::

        """
        if prec is not None:
            from sage.misc.misc import deprecation
            deprecation("The prec keyword argument is deprecated. Explicitly set the precision of the input, for example En(RealField(300)(1), RealField(300)(1)), or use the prec argument to .n() for exact inputs, e.g., En(1,1).n(300), instead.")
            
            import mpmath
            return mpmath_utils.call(mpmath.expint, n, z, prec=prec)

        return BuiltinFunction.__call__(self, n, z, coerce=coerce, hold=hold)
Example #30
0
def adapt_to_callable(f, nargs=None):
    """
    Tries to make every function in f into a (fast) callable
    function, returning a new list of functions and the expected
    arguments.
    
    INPUT:
    
    - ``f`` -- a list of functions; these can be symbolic expressions,
            polynomials, etc
            
    -  ``nargs`` -- number of input args to have in the output functions
    
    OUTPUT: functions, expected arguments
    """
    from sage.misc.misc import deprecation
    deprecation("adapt_to_callable is a deprecated function.  Please use functions from sage.misc.plot instead.")
    
    try:
        from sage.symbolic.callable import is_CallableSymbolicExpression
        if sum([is_CallableSymbolicExpression(z) for z in f]):
            # Sum to get common universe; this works since f is
            # callable, and summing gets the arguments in the right
            # order.
            vars = sum(f).args()
        else:
            # Otherwise any free variable names in any order
            try:
                vars = tuple(sorted(set(sum( [z.variables() for z in f], ()) )))
                if len(vars) > 1:
                    from sage.misc.misc import deprecation
                    deprecation("Substitution using function-call syntax and unnamed arguments is deprecated and will be removed from a future release of Sage; you can use named arguments instead, like EXPR(x=..., y=...)")
            except AttributeError:
                vars = ()
                f = [fast_float_constant(x) for x in f]
    except TypeError:
        vars = ()
        f = [fast_float_constant(x) for x in f]
    
    if nargs is not None and len(vars) != nargs:
        vars = (vars + ('_',)*nargs)[:nargs]
        
    return fast_float(f, *vars), vars
Example #31
0
def dynkin_diagram(t):
    """
    Returns the Dynkin diagram of type t.
    
    Note that this function is deprecated, and that you should use
    DynkinDiagram instead as this will be disappearing in the near
    future.
    
    EXAMPLES::
    
        sage: dynkin_diagram(["A", 3])
        doctest:1: DeprecationWarning: dynkin_diagram is deprecated, use DynkinDiagram instead!
        O---O---O
        1   2   3
        A3
    """
    from sage.misc.misc import deprecation
    deprecation("dynkin_diagram is deprecated, use DynkinDiagram instead!")
    return DynkinDiagram(t)
Example #32
0
def dynkin_diagram(t):
    """
    Returns the Dynkin diagram of type t.
    
    Note that this function is deprecated, and that you should use
    DynkinDiagram instead as this will be disappearing in the near
    future.
    
    EXAMPLES::
    
        sage: dynkin_diagram(["A", 3])
        doctest:1: DeprecationWarning: dynkin_diagram is deprecated, use DynkinDiagram instead!
        O---O---O
        1   2   3
        A3
    """
    from sage.misc.misc import deprecation
    deprecation("dynkin_diagram is deprecated, use DynkinDiagram instead!")
    return DynkinDiagram(t)
Example #33
0
File: log.py Project: dagss/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.
            7.3890560989306502272304274606
        """
        if prec is not None:
            from sage.misc.misc import deprecation
            deprecation(
                "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 #34
0
def exp_int(t):
    r"""
    The exponential integral `\int_t^\infty e^{-x}/x dx` (t
    belongs to RR).  This function is deprecated - please use
    ``Ei`` or ``exponential_integral_1`` as needed instead.

    EXAMPLES::
        
        sage: exp_int(6)
        doctest:...: DeprecationWarning: The method exp_int() is deprecated. Use -Ei(-x) or exponential_integral_1(x) as needed instead.
        0.000360082452162659
    """
    from sage.misc.misc import deprecation
    deprecation("The method exp_int() is deprecated. Use -Ei(-x) or exponential_integral_1(x) as needed instead.")
    try:
        return t.eint1()
    except AttributeError:
        from sage.libs.pari.all import pari
        try:
            return pari(t).eint1()
        except:
            raise NotImplementedError
Example #35
0
    def __init__(self, G, H, gens=None, images=None):
        """
        Some python code for wrapping GAP's GroupHomomorphismByImages
        function but only for permutation groups. Can be expensive if G is
        large. Returns "fail" if gens does not generate self or if the map
        does not extend to a group homomorphism, self - other.

        EXAMPLES::

            sage: G = CyclicPermutationGroup(4)
            sage: H = DihedralGroup(4)
            sage: phi = PermutationGroupMorphism_im_gens(G, H, map(H, G.gens())); phi
            Permutation group morphism:
              From: Cyclic group of order 4 as a permutation group
              To:   Dihedral group of order 8 as a permutation group
              Defn: [(1,2,3,4)] -> [(1,2,3,4)]
            sage: g = G([(1,3),(2,4)]); g
            (1,3)(2,4)          
            sage: phi(g) 
            (1,3)(2,4)
            sage: images = ((4,3,2,1),)
            sage: phi = PermutationGroupMorphism_im_gens(G, G, images)
            sage: g = G([(1,2,3,4)]); g
            (1,2,3,4)
            sage: phi(g)
            (1,4,3,2)

        AUTHORS:

        - David Joyner (2006-02)
        """
        if not all([isinstance(X, PermutationGroup_generic) for X in [G, H]]):
            raise TypeError, "Sorry, the groups must be permutation groups."
        if images is not None:
            deprecation('only the images need to be specified')
        else:
            images = gens
        PermutationGroupMorphism.__init__(self, G, H)
        self._images = [H(img) for img in images]
Example #36
0
    def __init__(self, G, H, gens=None, images=None):
        """
        Some python code for wrapping GAP's GroupHomomorphismByImages
        function but only for permutation groups. Can be expensive if G is
        large. Returns "fail" if gens does not generate self or if the map
        does not extend to a group homomorphism, self - other.

        EXAMPLES::

            sage: G = CyclicPermutationGroup(4)
            sage: H = DihedralGroup(4)
            sage: phi = PermutationGroupMorphism_im_gens(G, H, map(H, G.gens())); phi
            Permutation group morphism:
              From: Cyclic group of order 4 as a permutation group
              To:   Dihedral group of order 8 as a permutation group
              Defn: [(1,2,3,4)] -> [(1,2,3,4)]
            sage: g = G([(1,3),(2,4)]); g
            (1,3)(2,4)          
            sage: phi(g) 
            (1,3)(2,4)
            sage: images = ((4,3,2,1),)
            sage: phi = PermutationGroupMorphism_im_gens(G, G, images)
            sage: g = G([(1,2,3,4)]); g
            (1,2,3,4)
            sage: phi(g)
            (1,4,3,2)

        AUTHORS:

        - David Joyner (2006-02)
        """
        if not all([isinstance(X, PermutationGroup_generic) for X in [G, H]]):
            raise TypeError, "Sorry, the groups must be permutation groups."
        if images is not None:
            deprecation('only the images need to be specified')
        else:
            images = gens
        PermutationGroupMorphism.__init__(self, G, H)
        self._images = [H(img) for img in images]
Example #37
0
    def coef(self,P):
        r"""
        Synonym for :meth:`coefficient`

        .. WARNING::
         
            This method is deprecated. It will be removed in a future
            release of Sage. Please use the ``coefficient(P)`` method
            instead.

        EXAMPLES::

            sage: x,y = AffineSpace(2, GF(5), names='xy').gens()
            sage: C = Curve(y^2 - x^9 - x)
            sage: pts = C.rational_points(); pts
            [(0, 0), (2, 2), (2, 3), (3, 1), (3, 4)]
            sage: D = C.divisor(pts[0])
            sage: D.coefficient(pts[0])
            1
        """
        from sage.misc.misc import deprecation
        deprecation("This method is deprecated. It will be removed in a future release of Sage. Please use the coefficient() method instead.")
        return self.coefficient(P)
Example #38
0
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.
        {1, 2, 3}
        sage: EnumeratedSet(ZZ)
        Traceback (most recent call last):
        ...
        ValueError: X (=Integer Ring) must be finite
    """
    from sage.misc.misc import deprecation
    deprecation('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 #39
0
def sqrt(x):
    """
    Returns a square root of x.

    This function (``numerical_sqrt``) is deprecated.  Use ``sqrt(x,
    prec=n)`` instead.
    
    EXAMPLES::
    
        sage: numerical_sqrt(10.1)
        doctest:1: DeprecationWarning: numerical_sqrt is deprecated, use sqrt(x, prec=n) instead
        3.17804971641414
        sage: numerical_sqrt(9)
        3
    """
    from sage.misc.misc import deprecation
    deprecation("numerical_sqrt is deprecated, use sqrt(x, prec=n) instead")
    try:
        return x.sqrt()
    except (AttributeError, ValueError):
        try:
            return RDF(x).sqrt()
        except TypeError:
            return CDF(x).sqrt()
Example #40
0
 def r_quotient(self, length):
     """ *** deprecate *** """
     from sage.misc.misc import deprecation
     deprecation('r_quotient is deprecated. Use quotient instead.')
     return self.quotient(self, length)
Example #41
0
from sage.misc.misc import deprecation
deprecation('The module sage.geometry.polyhedra has been removed, use sage.geometry.polyhedron instead.',
            'Sage Version 4.8')
from polyhedron.all import *
Example #42
0
 def r_quotient(self, length):
   """ *** deprecate *** """
   from sage.misc.misc import deprecation
   deprecation('r_quotient is deprecated. Use quotient instead.')
   return self.quotient(self,length)
Example #43
0
def EllipticCurve(x=None, y=None, j=None):
    r"""
    There are several ways to construct an elliptic curve:
    
    .. math::
    
       y^2 + a_1 xy + a_3 y = x^3 + a_2 x^2 + a_4 x + a_6.       
    
    
    - EllipticCurve([a1,a2,a3,a4,a6]): Elliptic curve with given
      a-invariants. The invariants are coerced into the parent of the
      first element. If all are integers, they are coerced into the
      rational numbers.
    
    - EllipticCurve([a4,a6]): Same as above, but a1=a2=a3=0.
    
    - EllipticCurve(label): Returns the elliptic curve over Q from the
      Cremona database with the given label. The label is a string, such
      as "11a" or "37b2". The letters in the label *must* be lower case
      (Cremona's new labeling).
    
    - EllipticCurve(R, [a1,a2,a3,a4,a6]): Create the elliptic curve
      over R with given a-invariants. Here R can be an arbitrary ring.
      Note that addition need not be defined.
    
            
    - EllipticCurve(j): Return an elliptic curve with j-invariant
      `j`.  Warning: this is deprecated.  Use ``EllipticCurve_from_j(j)`` 
      or ``EllipticCurve(j=j)`` instead.         

    In each case above where the input is a list of length 2 or 5, one
    can instead give a 2 or 5-tuple instead.
    
    EXAMPLES: We illustrate creating elliptic curves.
    
    ::
    
        sage: EllipticCurve([0,0,1,-1,0])
        Elliptic Curve defined by y^2 + y = x^3 - x over Rational Field
    
    We create a curve from a Cremona label::
    
        sage: EllipticCurve('37b2')
        Elliptic Curve defined by y^2 + y = x^3 + x^2 - 1873*x - 31833 over Rational Field
        sage: EllipticCurve('5077a')
        Elliptic Curve defined by y^2 + y = x^3 - 7*x + 6 over Rational Field
        sage: EllipticCurve('389a')
        Elliptic Curve defined by y^2 + y = x^3 + x^2 - 2*x over Rational Field

    Unicode labels are allowed::

        sage: EllipticCurve(u'389a')
        Elliptic Curve defined by y^2 + y = x^3 + x^2 - 2*x over Rational Field
    
    We create curves over a finite field as follows::
    
        sage: EllipticCurve([GF(5)(0),0,1,-1,0])
        Elliptic Curve defined by y^2 + y = x^3 + 4*x over Finite Field of size 5
        sage: EllipticCurve(GF(5), [0, 0,1,-1,0])
        Elliptic Curve defined by y^2 + y = x^3 + 4*x over Finite Field of size 5

    Elliptic curves over `\ZZ/N\ZZ` with `N` prime are of type
    "elliptic curve over a finite field"::

        sage: F = Zmod(101)
        sage: EllipticCurve(F, [2, 3])
        Elliptic Curve defined by y^2 = x^3 + 2*x + 3 over Ring of integers modulo 101
        sage: E = EllipticCurve([F(2), F(3)])
        sage: type(E)
        <class 'sage.schemes.elliptic_curves.ell_finite_field.EllipticCurve_finite_field_with_category'>
        sage: E.category()
        Category of schemes over Ring of integers modulo 101

    In contrast, elliptic curves over `\ZZ/N\ZZ` with `N` composite
    are of type "generic elliptic curve"::

        sage: F = Zmod(95)
        sage: EllipticCurve(F, [2, 3])
        Elliptic Curve defined by y^2 = x^3 + 2*x + 3 over Ring of integers modulo 95
        sage: E = EllipticCurve([F(2), F(3)])
        sage: type(E)
        <class 'sage.schemes.elliptic_curves.ell_generic.EllipticCurve_generic_with_category'>
        sage: E.category()
        Category of schemes over Ring of integers modulo 95

    The following is a curve over the complex numbers::
    
        sage: E = EllipticCurve(CC, [0,0,1,-1,0])
        sage: E
        Elliptic Curve defined by y^2 + 1.00000000000000*y = x^3 + (-1.00000000000000)*x over Complex Field with 53 bits of precision
        sage: E.j_invariant()
        2988.97297297297
    
    We can also create elliptic curves by giving the Weierstrass equation::
    
        sage: x, y = var('x,y')
        sage: EllipticCurve(y^2 + y ==  x^3 + x - 9)
        Elliptic Curve defined by y^2 + y = x^3 + x - 9 over Rational Field
        
        sage: R.<x,y> = GF(5)[]
        sage: EllipticCurve(x^3 + x^2 + 2 - y^2 - y*x)
        Elliptic Curve defined by y^2 + x*y  = x^3 + x^2 + 2 over Finite Field of size 5

    We can explicitly specify the `j`-invariant::

        sage: E = EllipticCurve(j=1728); E; E.j_invariant(); E.label()
        Elliptic Curve defined by y^2 = x^3 - x over Rational Field
        1728
        '32a2'

        sage: E = EllipticCurve(j=GF(5)(2)); E; E.j_invariant()
        Elliptic Curve defined by y^2 = x^3 + x + 1 over Finite Field of size 5
        2

    See trac #6657::    

        sage: EllipticCurve(GF(144169),j=1728)
        Elliptic Curve defined by y^2 = x^3 + x over Finite Field of size 144169


    TESTS::
    
        sage: R = ZZ['u', 'v']
        sage: EllipticCurve(R, [1,1])
        Elliptic Curve defined by y^2 = x^3 + x + 1 over Multivariate Polynomial Ring in u, v
        over Integer Ring
    
    We create a curve and a point over QQbar (see #6879)::
    
        sage: E = EllipticCurve(QQbar,[0,1])
        sage: E(0)
        (0 : 1 : 0)
        sage: E.base_field()
        Algebraic Field

        sage: E = EllipticCurve(RR,[1,2]); E; E.base_field()
        Elliptic Curve defined by y^2 = x^3 + 1.00000000000000*x + 2.00000000000000 over Real Field with 53 bits of precision
        Real Field with 53 bits of precision
        sage: EllipticCurve(CC,[3,4]); E; E.base_field()
        Elliptic Curve defined by y^2 = x^3 + 3.00000000000000*x + 4.00000000000000 over Complex Field with 53 bits of precision
        Elliptic Curve defined by y^2 = x^3 + 1.00000000000000*x + 2.00000000000000 over Real Field with 53 bits of precision
        Real Field with 53 bits of precision
        sage: E = EllipticCurve(QQbar,[5,6]); E; E.base_field()
        Elliptic Curve defined by y^2 = x^3 + 5*x + 6 over Algebraic Field
        Algebraic Field

    See trac #6657::

        sage: EllipticCurve(3,j=1728)
        Traceback (most recent call last):
        ...
        ValueError: First parameter (if present) must be a ring when j is specified

        sage: EllipticCurve(GF(5),j=3/5)
        Traceback (most recent call last):
        ...
        ValueError: First parameter must be a ring containing 3/5

    If the universe of the coefficients is a general field, the object
    constructed has type EllipticCurve_field.  Otherwise it is
    EllipticCurve_generic.  See trac #9816::

        sage: E = EllipticCurve([QQbar(1),3]); E
        Elliptic Curve defined by y^2 = x^3 + x + 3 over Algebraic Field
        sage: type(E)
        <class 'sage.schemes.elliptic_curves.ell_field.EllipticCurve_field_with_category'>

        sage: E = EllipticCurve([RR(1),3]); E
        Elliptic Curve defined by y^2 = x^3 + 1.00000000000000*x + 3.00000000000000 over Real Field with 53 bits of precision
        sage: type(E)
        <class 'sage.schemes.elliptic_curves.ell_field.EllipticCurve_field_with_category'>

        sage: E = EllipticCurve([i,i]); E
        Elliptic Curve defined by y^2 = x^3 + I*x + I over Symbolic Ring
        sage: type(E)
        <class 'sage.schemes.elliptic_curves.ell_field.EllipticCurve_field_with_category'>
        sage: E.category()
        Category of schemes over Symbolic Ring
        sage: is_field(SR)
        True

        sage: F = FractionField(PolynomialRing(QQ,'t'))
        sage: t = F.gen()
        sage: E = EllipticCurve([t,0]); E
        Elliptic Curve defined by y^2 = x^3 + t*x over Fraction Field of Univariate Polynomial Ring in t over Rational Field
        sage: type(E)
        <class 'sage.schemes.elliptic_curves.ell_field.EllipticCurve_field_with_category'>
        sage: E.category()
        Category of schemes over Fraction Field of Univariate Polynomial Ring in t over Rational Field

    See :trac:`12517`::

        sage: E = EllipticCurve([1..5])
        sage: EllipticCurve(E.a_invariants())
        Elliptic Curve defined by y^2 + x*y + 3*y = x^3 + 2*x^2 + 4*x + 5 over Rational Field
    """
    import ell_generic, ell_field, ell_finite_field, ell_number_field, ell_rational_field, ell_padic_field  # here to avoid circular includes
    
    if j is not None:
        if not x is None:
            if rings.is_Ring(x):
                try:
                    j = x(j)
                except (ZeroDivisionError, ValueError, TypeError):                    
                    raise ValueError, "First parameter must be a ring containing %s"%j
            else:
                raise ValueError, "First parameter (if present) must be a ring when j is specified"
        return EllipticCurve_from_j(j)

    assert x is not None
    
    if is_SymbolicEquation(x):
        x = x.lhs() - x.rhs()
    
    if parent(x) is SR:
        x = x._polynomial_(rings.QQ['x', 'y'])
    
    if rings.is_MPolynomial(x) and y is None:
        f = x
        if f.degree() != 3:
            raise ValueError, "Elliptic curves must be defined by a cubic polynomial."
        if f.degrees() == (3,2):
            x, y = f.parent().gens()
        elif f.degree() == (2,3):
            y, x = f.parent().gens()
        elif len(f.parent().gens()) == 2 or len(f.parent().gens()) == 3 and f.is_homogeneous():
            # We'd need a point too...
            raise NotImplementedError, "Construction of an elliptic curve from a generic cubic not yet implemented."
        else:
            raise ValueError, "Defining polynomial must be a cubic polynomial in two variables."

        try:
            if f.coefficient(x**3) < 0:
                f = -f
            # is there a nicer way to extract the coefficients?
            a1 = a2 = a3 = a4 = a6 = 0
            for coeff, mon in f:
                if mon == x**3:
                    assert coeff == 1
                elif mon == x**2:
                    a2 = coeff
                elif mon == x:
                    a4 = coeff
                elif mon == 1:
                    a6 = coeff
                elif mon == y**2:
                    assert coeff == -1
                elif mon == x*y:
                    a1 = -coeff
                elif mon == y:
                    a3 = -coeff
                else:
                    assert False
            return EllipticCurve([a1, a2, a3, a4, a6])
        except AssertionError:
            raise NotImplementedError, "Construction of an elliptic curve from a generic cubic not yet implemented."
    
    if rings.is_Ring(x):
        if rings.is_RationalField(x):
            return ell_rational_field.EllipticCurve_rational_field(x, y)
        elif rings.is_FiniteField(x) or (rings.is_IntegerModRing(x) and x.characteristic().is_prime()):
            return ell_finite_field.EllipticCurve_finite_field(x, y)
        elif rings.is_pAdicField(x):
            return ell_padic_field.EllipticCurve_padic_field(x, y)
        elif rings.is_NumberField(x):
            return ell_number_field.EllipticCurve_number_field(x, y)
        elif rings.is_Field(x):
            return ell_field.EllipticCurve_field(x, y)
        return ell_generic.EllipticCurve_generic(x, y)

    if isinstance(x, unicode):
        x = str(x)
        
    if isinstance(x, str):
        return ell_rational_field.EllipticCurve_rational_field(x)
        
    if rings.is_RingElement(x) and y is None:
        from sage.misc.misc import deprecation
        deprecation("'EllipticCurve(j)' is deprecated; use 'EllipticCurve_from_j(j)' or 'EllipticCurve(j=j)' instead.")
        # Fixed for all characteristics and cases by John Cremona
        j=x
        F=j.parent().fraction_field()
        char=F.characteristic()
        if char==2:
            if j==0:
                return EllipticCurve(F, [ 0, 0, 1, 0, 0 ])
            else:
                return EllipticCurve(F, [ 1, 0, 0, 0, 1/j ])
        if char==3:
            if j==0:
                return EllipticCurve(F, [ 0, 0, 0, 1, 0 ])
            else:
                return EllipticCurve(F, [ 0, j, 0, 0, -j**2 ])
        if j == 0:
            return EllipticCurve(F, [ 0, 0, 0, 0, 1 ])
        if j == 1728:
            return EllipticCurve(F, [ 0, 0, 0, 1, 0 ])
        k=j-1728
        return EllipticCurve(F, [0,0,0,-3*j*k, -2*j*k**2])

    if not isinstance(x, (list, tuple)):
        raise TypeError, "invalid input to EllipticCurve constructor"

    x = Sequence(x)
    if not (len(x) in [2,5]):
        raise ValueError, "sequence of coefficients must have length 2 or 5"
    R = x.universe()

    if isinstance(x[0], (rings.Rational, rings.Integer, int, long)):
        return ell_rational_field.EllipticCurve_rational_field(x, y)

    elif rings.is_NumberField(R):
        return ell_number_field.EllipticCurve_number_field(x, y)

    elif rings.is_pAdicField(R):
        return ell_padic_field.EllipticCurve_padic_field(x, y)
    
    elif rings.is_FiniteField(R) or (rings.is_IntegerModRing(R) and R.characteristic().is_prime()):
        return ell_finite_field.EllipticCurve_finite_field(x, y)

    elif rings.is_Field(R):
        return ell_field.EllipticCurve_field(x, y)

    return ell_generic.EllipticCurve_generic(x, y)
Example #44
0
#  Distributed under the terms of the GNU General Public License (GPL)
#                  http://www.gnu.org/licenses/
#*****************************************************************************

from sage.categories.all import GroupAlgebras
from sage.structure.parent_gens import ParentWithGens
from sage.algebras.algebra import Algebra
from sage.algebras.algebra_element import AlgebraElement
from sage.rings.all import IntegerRing
from sage.groups.group import Group
from sage.structure.formal_sum import FormalSums, FormalSum
from sage.sets.set import Set

from sage.misc.misc import deprecation
deprecation(
    "The module group_algebra is deprecated and will be removed in a future version of Sage. Use group_algebra_new instead."
)


class GroupAlgebra(Algebra):
    def __init__(self, group, base_ring=IntegerRing()):
        r""" Create the given group algebra.
        INPUT:
            -- (Group) group: a generic group.
            -- (Ring) base_ring: a commutative ring.
        OUTPUT:
            -- a GroupAlgebra instance.

        EXAMPLES::

            sage: from sage.algebras.group_algebra import GroupAlgebra
Example #45
0
def EllipticCurve(x=None, y=None, j=None):
    r"""
    There are several ways to construct an elliptic curve:
    
    .. math::
    
       y^2 + a_1 xy + a_3 y = x^3 + a_2 x^2 + a_4 x + a_6.       
    
    
    - EllipticCurve([a1,a2,a3,a4,a6]): Elliptic curve with given
      a-invariants. The invariants are coerced into the parent of the
      first element. If all are integers, they are coerced into the
      rational numbers.
    
    - EllipticCurve([a4,a6]): Same as above, but a1=a2=a3=0.
    
    - EllipticCurve(label): Returns the elliptic curve over Q from the
      Cremona database with the given label. The label is a string, such
      as "11a" or "37b2". The letters in the label *must* be lower case
      (Cremona's new labeling).
    
    - EllipticCurve(R, [a1,a2,a3,a4,a6]): Create the elliptic curve
      over R with given a-invariants. Here R can be an arbitrary ring.
      Note that addition need not be defined.
    
            
    - EllipticCurve(j): Return an elliptic curve with j-invariant
      `j`.  Warning: this is deprecated.  Use ``EllipticCurve_from_j(j)`` 
      or ``EllipticCurve(j=j)`` instead.         

    In each case above where the input is a list of length 2 or 5, one
    can instead give a 2 or 5-tuple instead.
    
    EXAMPLES: We illustrate creating elliptic curves.
    
    ::
    
        sage: EllipticCurve([0,0,1,-1,0])
        Elliptic Curve defined by y^2 + y = x^3 - x over Rational Field
    
    We create a curve from a Cremona label::
    
        sage: EllipticCurve('37b2')
        Elliptic Curve defined by y^2 + y = x^3 + x^2 - 1873*x - 31833 over Rational Field
        sage: EllipticCurve('5077a')
        Elliptic Curve defined by y^2 + y = x^3 - 7*x + 6 over Rational Field
        sage: EllipticCurve('389a')
        Elliptic Curve defined by y^2 + y = x^3 + x^2 - 2*x over Rational Field

    Unicode labels are allowed::

        sage: EllipticCurve(u'389a')
        Elliptic Curve defined by y^2 + y = x^3 + x^2 - 2*x over Rational Field
    
    We create curves over a finite field as follows::
    
        sage: EllipticCurve([GF(5)(0),0,1,-1,0])
        Elliptic Curve defined by y^2 + y = x^3 + 4*x over Finite Field of size 5
        sage: EllipticCurve(GF(5), [0, 0,1,-1,0])
        Elliptic Curve defined by y^2 + y = x^3 + 4*x over Finite Field of size 5

    Elliptic curves over `\ZZ/N\ZZ` with `N` prime are of type
    "elliptic curve over a finite field"::

        sage: F = Zmod(101)
        sage: EllipticCurve(F, [2, 3])
        Elliptic Curve defined by y^2 = x^3 + 2*x + 3 over Ring of integers modulo 101
        sage: E = EllipticCurve([F(2), F(3)])
        sage: type(E)
        <class 'sage.schemes.elliptic_curves.ell_finite_field.EllipticCurve_finite_field_with_category'>
        sage: E.category()
        Category of schemes over Ring of integers modulo 101

    In contrast, elliptic curves over `\ZZ/N\ZZ` with `N` composite
    are of type "generic elliptic curve"::

        sage: F = Zmod(95)
        sage: EllipticCurve(F, [2, 3])
        Elliptic Curve defined by y^2 = x^3 + 2*x + 3 over Ring of integers modulo 95
        sage: E = EllipticCurve([F(2), F(3)])
        sage: type(E)
        <class 'sage.schemes.elliptic_curves.ell_generic.EllipticCurve_generic_with_category'>
        sage: E.category()
        Category of schemes over Ring of integers modulo 95

    The following is a curve over the complex numbers::
    
        sage: E = EllipticCurve(CC, [0,0,1,-1,0])
        sage: E
        Elliptic Curve defined by y^2 + 1.00000000000000*y = x^3 + (-1.00000000000000)*x over Complex Field with 53 bits of precision
        sage: E.j_invariant()
        2988.97297297297
    
    We can also create elliptic curves by giving the Weierstrass equation::
    
        sage: x, y = var('x,y')
        sage: EllipticCurve(y^2 + y ==  x^3 + x - 9)
        Elliptic Curve defined by y^2 + y = x^3 + x - 9 over Rational Field
        
        sage: R.<x,y> = GF(5)[]
        sage: EllipticCurve(x^3 + x^2 + 2 - y^2 - y*x)
        Elliptic Curve defined by y^2 + x*y  = x^3 + x^2 + 2 over Finite Field of size 5

    We can explicitly specify the `j`-invariant::

        sage: E = EllipticCurve(j=1728); E; E.j_invariant(); E.label()
        Elliptic Curve defined by y^2 = x^3 - x over Rational Field
        1728
        '32a2'

        sage: E = EllipticCurve(j=GF(5)(2)); E; E.j_invariant()
        Elliptic Curve defined by y^2 = x^3 + x + 1 over Finite Field of size 5
        2

    See trac #6657::    

        sage: EllipticCurve(GF(144169),j=1728)
        Elliptic Curve defined by y^2 = x^3 + x over Finite Field of size 144169


    TESTS::
    
        sage: R = ZZ['u', 'v']
        sage: EllipticCurve(R, [1,1])
        Elliptic Curve defined by y^2 = x^3 + x + 1 over Multivariate Polynomial Ring in u, v
        over Integer Ring
    
    We create a curve and a point over QQbar (see #6879)::
    
        sage: E = EllipticCurve(QQbar,[0,1])
        sage: E(0)
        (0 : 1 : 0)
        sage: E.base_field()
        Algebraic Field

        sage: E = EllipticCurve(RR,[1,2]); E; E.base_field()
        Elliptic Curve defined by y^2 = x^3 + 1.00000000000000*x + 2.00000000000000 over Real Field with 53 bits of precision
        Real Field with 53 bits of precision
        sage: EllipticCurve(CC,[3,4]); E; E.base_field()
        Elliptic Curve defined by y^2 = x^3 + 3.00000000000000*x + 4.00000000000000 over Complex Field with 53 bits of precision
        Elliptic Curve defined by y^2 = x^3 + 1.00000000000000*x + 2.00000000000000 over Real Field with 53 bits of precision
        Real Field with 53 bits of precision
        sage: E = EllipticCurve(QQbar,[5,6]); E; E.base_field()
        Elliptic Curve defined by y^2 = x^3 + 5*x + 6 over Algebraic Field
        Algebraic Field

    See trac #6657::

        sage: EllipticCurve(3,j=1728)
        Traceback (most recent call last):
        ...
        ValueError: First parameter (if present) must be a ring when j is specified

        sage: EllipticCurve(GF(5),j=3/5)
        Traceback (most recent call last):
        ...
        ValueError: First parameter must be a ring containing 3/5

    If the universe of the coefficients is a general field, the object
    constructed has type EllipticCurve_field.  Otherwise it is
    EllipticCurve_generic.  See trac #9816::

        sage: E = EllipticCurve([QQbar(1),3]); E
        Elliptic Curve defined by y^2 = x^3 + x + 3 over Algebraic Field
        sage: type(E)
        <class 'sage.schemes.elliptic_curves.ell_field.EllipticCurve_field_with_category'>

        sage: E = EllipticCurve([RR(1),3]); E
        Elliptic Curve defined by y^2 = x^3 + 1.00000000000000*x + 3.00000000000000 over Real Field with 53 bits of precision
        sage: type(E)
        <class 'sage.schemes.elliptic_curves.ell_field.EllipticCurve_field_with_category'>

        sage: E = EllipticCurve([i,i]); E
        Elliptic Curve defined by y^2 = x^3 + I*x + I over Symbolic Ring
        sage: type(E)
        <class 'sage.schemes.elliptic_curves.ell_field.EllipticCurve_field_with_category'>
        sage: E.category()
        Category of schemes over Symbolic Ring
        sage: is_field(SR)
        True

        sage: F = FractionField(PolynomialRing(QQ,'t'))
        sage: t = F.gen()
        sage: E = EllipticCurve([t,0]); E
        Elliptic Curve defined by y^2 = x^3 + t*x over Fraction Field of Univariate Polynomial Ring in t over Rational Field
        sage: type(E)
        <class 'sage.schemes.elliptic_curves.ell_field.EllipticCurve_field_with_category'>
        sage: E.category()
        Category of schemes over Fraction Field of Univariate Polynomial Ring in t over Rational Field

    See :trac:`12517`::

        sage: E = EllipticCurve([1..5])
        sage: EllipticCurve(E.a_invariants())
        Elliptic Curve defined by y^2 + x*y + 3*y = x^3 + 2*x^2 + 4*x + 5 over Rational Field
    """
    import ell_generic, ell_field, ell_finite_field, ell_number_field, ell_rational_field, ell_padic_field  # here to avoid circular includes

    if j is not None:
        if not x is None:
            if rings.is_Ring(x):
                try:
                    j = x(j)
                except (ZeroDivisionError, ValueError, TypeError):
                    raise ValueError, "First parameter must be a ring containing %s" % j
            else:
                raise ValueError, "First parameter (if present) must be a ring when j is specified"
        return EllipticCurve_from_j(j)

    assert x is not None

    if is_SymbolicEquation(x):
        x = x.lhs() - x.rhs()

    if parent(x) is SR:
        x = x._polynomial_(rings.QQ["x", "y"])

    if rings.is_MPolynomial(x) and y is None:
        f = x
        if f.degree() != 3:
            raise ValueError, "Elliptic curves must be defined by a cubic polynomial."
        if f.degrees() == (3, 2):
            x, y = f.parent().gens()
        elif f.degree() == (2, 3):
            y, x = f.parent().gens()
        elif len(f.parent().gens()) == 2 or len(f.parent().gens()) == 3 and f.is_homogeneous():
            # We'd need a point too...
            raise NotImplementedError, "Construction of an elliptic curve from a generic cubic not yet implemented."
        else:
            raise ValueError, "Defining polynomial must be a cubic polynomial in two variables."

        try:
            if f.coefficient(x ** 3) < 0:
                f = -f
            # is there a nicer way to extract the coefficients?
            a1 = a2 = a3 = a4 = a6 = 0
            for coeff, mon in f:
                if mon == x ** 3:
                    assert coeff == 1
                elif mon == x ** 2:
                    a2 = coeff
                elif mon == x:
                    a4 = coeff
                elif mon == 1:
                    a6 = coeff
                elif mon == y ** 2:
                    assert coeff == -1
                elif mon == x * y:
                    a1 = -coeff
                elif mon == y:
                    a3 = -coeff
                else:
                    assert False
            return EllipticCurve([a1, a2, a3, a4, a6])
        except AssertionError:
            raise NotImplementedError, "Construction of an elliptic curve from a generic cubic not yet implemented."

    if rings.is_Ring(x):
        if rings.is_RationalField(x):
            return ell_rational_field.EllipticCurve_rational_field(x, y)
        elif rings.is_FiniteField(x) or (rings.is_IntegerModRing(x) and x.characteristic().is_prime()):
            return ell_finite_field.EllipticCurve_finite_field(x, y)
        elif rings.is_pAdicField(x):
            return ell_padic_field.EllipticCurve_padic_field(x, y)
        elif rings.is_NumberField(x):
            return ell_number_field.EllipticCurve_number_field(x, y)
        elif rings.is_Field(x):
            return ell_field.EllipticCurve_field(x, y)
        return ell_generic.EllipticCurve_generic(x, y)

    if isinstance(x, unicode):
        x = str(x)

    if isinstance(x, str):
        return ell_rational_field.EllipticCurve_rational_field(x)

    if rings.is_RingElement(x) and y is None:
        from sage.misc.misc import deprecation

        deprecation("'EllipticCurve(j)' is deprecated; use 'EllipticCurve_from_j(j)' or 'EllipticCurve(j=j)' instead.")
        # Fixed for all characteristics and cases by John Cremona
        j = x
        F = j.parent().fraction_field()
        char = F.characteristic()
        if char == 2:
            if j == 0:
                return EllipticCurve(F, [0, 0, 1, 0, 0])
            else:
                return EllipticCurve(F, [1, 0, 0, 0, 1 / j])
        if char == 3:
            if j == 0:
                return EllipticCurve(F, [0, 0, 0, 1, 0])
            else:
                return EllipticCurve(F, [0, j, 0, 0, -j ** 2])
        if j == 0:
            return EllipticCurve(F, [0, 0, 0, 0, 1])
        if j == 1728:
            return EllipticCurve(F, [0, 0, 0, 1, 0])
        k = j - 1728
        return EllipticCurve(F, [0, 0, 0, -3 * j * k, -2 * j * k ** 2])

    if not isinstance(x, (list, tuple)):
        raise TypeError, "invalid input to EllipticCurve constructor"

    x = Sequence(x)
    if not (len(x) in [2, 5]):
        raise ValueError, "sequence of coefficients must have length 2 or 5"
    R = x.universe()

    if isinstance(x[0], (rings.Rational, rings.Integer, int, long)):
        return ell_rational_field.EllipticCurve_rational_field(x, y)

    elif rings.is_NumberField(R):
        return ell_number_field.EllipticCurve_number_field(x, y)

    elif rings.is_pAdicField(R):
        return ell_padic_field.EllipticCurve_padic_field(x, y)

    elif rings.is_FiniteField(R) or (rings.is_IntegerModRing(R) and R.characteristic().is_prime()):
        return ell_finite_field.EllipticCurve_finite_field(x, y)

    elif rings.is_Field(R):
        return ell_field.EllipticCurve_field(x, y)

    return ell_generic.EllipticCurve_generic(x, y)
Example #46
0
def setup_for_eval_on_grid(funcs, ranges, plot_points=None, return_vars=False):
    """
    Calculate the necessary parameters to construct a list of points,
    and make the functions fast_callable.

    INPUT:
    
    -  ``funcs`` - a function, or a list, tuple, or vector of functions
    
    - ``ranges`` - a list of ranges.  A range can be a 2-tuple of
      numbers specifying the minimum and maximum, or a 3-tuple giving
      the variable explicitly.

    - ``plot_points`` - a tuple of integers specifying the number of
      plot points for each range.  If a single number is specified, it
      will be the value for all ranges.  This defaults to 2.
     
    - ``return_vars`` - (default False) If True, return the variables,
      in order.
    
    
    OUTPUT:
    
    
    - ``fast_funcs`` - if only one function passed, then a fast
       callable function.  If funcs is a list or tuple, then a tuple
       of fast callable functions is returned.

    - ``range_specs`` - a list of range_specs: for each range, a
       tuple is returned of the form (range_min, range_max,
       range_step) such that ``srange(range_min, range_max,
       range_step, include_endpoint=True)`` gives the correct points
       for evaluation.
    
    EXAMPLES::
    
        sage: x,y,z=var('x,y,z')
        sage: f(x,y)=x+y-z
        sage: g(x,y)=x+y
        sage: h(y)=-y
        sage: sage.plot.misc.setup_for_eval_on_grid(f, [(0, 2),(1,3),(-4,1)], plot_points=5)
        (<sage.ext...>, [(0.0, 2.0, 0.5), (1.0, 3.0, 0.5), (-4.0, 1.0, 1.25)])
        sage: sage.plot.misc.setup_for_eval_on_grid([g,h], [(0, 2),(-1,1)], plot_points=5)
        ((<sage.ext...>, <sage.ext...>), [(0.0, 2.0, 0.5), (-1.0, 1.0, 0.5)])
        sage: sage.plot.misc.setup_for_eval_on_grid([sin,cos], [(-1,1)], plot_points=9)
        ((<sage.ext...>, <sage.ext...>), [(-1.0, 1.0, 0.25)])
        sage: sage.plot.misc.setup_for_eval_on_grid([lambda x: x^2,cos], [(-1,1)], plot_points=9)
        ((<function <lambda> ...>, <sage.ext...>), [(-1.0, 1.0, 0.25)])
        sage: sage.plot.misc.setup_for_eval_on_grid([x+y], [(x,-1,1),(y,-2,2)])
        ((<sage.ext...>,), [(-1.0, 1.0, 2.0), (-2.0, 2.0, 4.0)])
        sage: sage.plot.misc.setup_for_eval_on_grid(x+y, [(x,-1,1),(y,-1,1)], plot_points=[4,9])
        (<sage.ext...>, [(-1.0, 1.0, 0.6666666666666666), (-1.0, 1.0, 0.25)])
        sage: sage.plot.misc.setup_for_eval_on_grid(x+y, [(x,-1,1),(y,-1,1)], plot_points=[4,9,10])
        Traceback (most recent call last):
        ...
        ValueError: plot_points must be either an integer or a list of integers, one for each range
        sage: sage.plot.misc.setup_for_eval_on_grid(x+y, [(1,-1),(y,-1,1)], plot_points=[4,9,10])
        Traceback (most recent call last):
        ...
        ValueError: Some variable ranges specify variables while others do not
        sage: sage.plot.misc.setup_for_eval_on_grid(x+y, [(1,-1),(-1,1)], plot_points=5)
        doctest:...: DeprecationWarning: Unnamed ranges for more than one variable is deprecated and will be removed from a future release of Sage; you can used named ranges instead, like (x,0,2)
        (<sage.ext...>, [(1.0, -1.0, 0.5), (-1.0, 1.0, 0.5)])
        sage: sage.plot.misc.setup_for_eval_on_grid(x+y, [(y,1,-1),(x,-1,1)], plot_points=5)
        (<sage.ext...>, [(1.0, -1.0, 0.5), (-1.0, 1.0, 0.5)])
        sage: sage.plot.misc.setup_for_eval_on_grid(x+y, [(x,1,-1),(x,-1,1)], plot_points=5)
        Traceback (most recent call last):
        ...
        ValueError: range variables should be distinct, but there are duplicates
        sage: sage.plot.misc.setup_for_eval_on_grid(x+y, [(x,1,1),(y,-1,1)])
        Traceback (most recent call last):
        ...
        ValueError: plot start point and end point must be different
        sage: sage.plot.misc.setup_for_eval_on_grid(x+y, [(x,1,-1),(y,-1,1)], return_vars=True)
        (<sage.ext...>, [(1.0, -1.0, 2.0), (-1.0, 1.0, 2.0)], [x, y])
        sage: sage.plot.misc.setup_for_eval_on_grid(x+y, [(y,1,-1),(x,-1,1)], return_vars=True)
        (<sage.ext...>, [(1.0, -1.0, 2.0), (-1.0, 1.0, 2.0)], [y, x])
    """
    if max(map(len, ranges)) != min(map(len, ranges)):
        raise ValueError, "Some variable ranges specify variables while others do not"

    if len(ranges[0]) == 3:
        vars = [r[0] for r in ranges]
        ranges = [r[1:] for r in ranges]
        if len(set(vars)) < len(vars):
            raise ValueError, "range variables should be distinct, but there are duplicates"
    else:
        vars, free_vars = unify_arguments(funcs)
        if len(free_vars) > 1:
            from sage.misc.misc import deprecation
            deprecation(
                "Unnamed ranges for more than one variable is deprecated and will be removed from a future release of Sage; you can used named ranges instead, like (x,0,2)"
            )

    # pad the variables if we don't have enough
    nargs = len(ranges)
    if len(vars) < nargs:
        vars += ('_', ) * (nargs - len(vars))

    ranges = [[float(z) for z in r] for r in ranges]

    if plot_points is None:
        plot_points = 2

    if not isinstance(plot_points, (list, tuple)):
        plot_points = [plot_points] * len(ranges)
    elif len(plot_points) != nargs:
        raise ValueError, "plot_points must be either an integer or a list of integers, one for each range"

    plot_points = [int(p) if p >= 2 else 2 for p in plot_points]
    range_steps = [
        abs(range[1] - range[0]) / (p - 1)
        for range, p in zip(ranges, plot_points)
    ]
    if min(range_steps) == float(0):
        raise ValueError, "plot start point and end point must be different"

    options = {}
    if nargs == 1:
        options['expect_one_var'] = True

    if is_Vector(funcs):
        funcs = list(funcs)

    #TODO: raise an error if there is a function/method in funcs that takes more values than we have ranges

    if return_vars:
        return fast_float(funcs, *vars, **options), [
            tuple(range + [range_step])
            for range, range_step in zip(ranges, range_steps)
        ], vars
    else:
        return fast_float(funcs, *vars, **options), [
            tuple(range + [range_step])
            for range, range_step in zip(ranges, range_steps)
        ]
Example #47
0
def integrate(expression, v=None, a=None, b=None, algorithm=None):
    r"""
    Returns the indefinite integral with respect to the variable
    `v`, ignoring the constant of integration. Or, if endpoints
    `a` and `b` are specified, returns the definite
    integral over the interval `[a, b]`.

    If ``self`` has only one variable, then it returns the
    integral with respect to that variable.

    If definite integration fails, it could be still possible to
    evaluate the definite integral using indefinite integration with
    the Newton - Leibniz theorem (however, the user has to ensure that the
    indefinite integral is continuous on the compact interval `[a,b]` and
    this theorem can be applied).

    INPUT:
 
    - ``v`` - a variable or variable name.  This can also be a tuple of
      the variable (optional) and endpoints (i.e., ``(x,0,1)`` or ``(0,1)``).
 
    - ``a`` - (optional) lower endpoint of definite integral
 
    - ``b`` - (optional) upper endpoint of definite integral
 
    - ``algorithm`` - (default: 'maxima') one of
 
       - 'maxima' - use maxima (the default)
             
       - 'sympy' - use sympy (also in Sage)
               
       - 'mathematica_free' - use http://integrals.wolfram.com/
 
     EXAMPLES::

        sage: x = var('x')
        sage: h = sin(x)/(cos(x))^2
        sage: h.integral(x)
        1/cos(x)

    ::

        sage: f = x^2/(x+1)^3
        sage: f.integral(x)
        1/2*(4*x + 3)/(x^2 + 2*x + 1) + log(x + 1)

    ::

        sage: f = x*cos(x^2)
        sage: f.integral(x, 0, sqrt(pi))
        0
        sage: f.integral(x, a=-pi, b=pi)
        0

    ::

        sage: f(x) = sin(x)
        sage: f.integral(x, 0, pi/2)
        x |--> 1

    The variable is required, but the endpoints are optional::

        sage: y=var('y')
        sage: integral(sin(x), x)
        -cos(x)
        sage: integral(sin(x), y)
        y*sin(x)
        sage: integral(sin(x), x, pi, 2*pi)
        -2
        sage: integral(sin(x), y, pi, 2*pi)
        pi*sin(x)
        sage: integral(sin(x), (x, pi, 2*pi))
        -2
        sage: integral(sin(x), (y, pi, 2*pi))
        pi*sin(x)

    Constraints are sometimes needed::

        sage: var('x, n')
        (x, n)
        sage: integral(x^n,x)
        Traceback (most recent call last):
        ...
        ValueError: Computation failed since Maxima requested additional
        constraints; using the 'assume' command before integral evaluation
        *may* help (example of legal syntax is 'assume(n+1>0)', see `assume?`
        for more details)
        Is  n+1  zero or nonzero?
        sage: assume(n > 0)
        sage: integral(x^n,x)
        x^(n + 1)/(n + 1)
        sage: forget()

    Usually the constraints are of sign, but others are possible::

        sage: assume(n==-1)
        sage: integral(x^n,x)
        log(x)

    Note that an exception is raised when a definite integral is
    divergent::

        sage: forget() # always remember to forget assumptions you no longer need
        sage: integrate(1/x^3,(x,0,1))
        Traceback (most recent call last):
        ...
        ValueError: Integral is divergent.
        sage: integrate(1/x^3,x,-1,3)
        Traceback (most recent call last):
        ...
        ValueError: Integral is divergent.

    But Sage can calculate the convergent improper integral of
    this function::

        sage: integrate(1/x^3,x,1,infinity)
        1/2

    The examples in the Maxima documentation::

        sage: var('x, y, z, b')
        (x, y, z, b)
        sage: integral(sin(x)^3, x)
        1/3*cos(x)^3 - cos(x)
        sage: integral(x/sqrt(b^2-x^2), b)
        x*log(2*b + 2*sqrt(b^2 - x^2))
        sage: integral(x/sqrt(b^2-x^2), x)
        -sqrt(b^2 - x^2)
        sage: integral(cos(x)^2 * exp(x), x, 0, pi)
        3/5*e^pi - 3/5
        sage: integral(x^2 * exp(-x^2), x, -oo, oo)
        1/2*sqrt(pi)

    We integrate the same function in both Mathematica and Sage (via
    Maxima)::

        sage: _ = var('x, y, z')
        sage: f = sin(x^2) + y^z
        sage: g = mathematica(f)                           # optional  -- requires mathematica
        sage: print g                                      # optional -- requires mathematica
                  z        2
                 y  + Sin[x ]
        sage: print g.Integrate(x)                         # optional -- requires mathematica
                    z        Pi                2
                 x y  + Sqrt[--] FresnelS[Sqrt[--] x]
                             2                 Pi
        sage: print f.integral(x)
        y^z*x + 1/8*((I - 1)*sqrt(2)*erf((1/2*I - 1/2)*sqrt(2)*x) + (I + 1)*sqrt(2)*erf((1/2*I + 1/2)*sqrt(2)*x))*sqrt(pi)

    Alternatively, just use algorithm='mathematica_free' to integrate via Mathematica
    over the internet (does NOT require a Mathematica license!)::

        sage: _ = var('x, y, z')
        sage: f = sin(x^2) + y^z
        sage: f.integrate(algorithm="mathematica_free")       # optional -- requires internet
        sqrt(pi)*sqrt(1/2)*fresnels(sqrt(2)*x/sqrt(pi)) + y^z*x

    We can also use Sympy::

        sage: _ = var('x, y, z')
        sage: (x^y-z).integrate(y)
        -y*z + x^y/log(x)
        sage: (x^y-z).integrate(y,algorithm="sympy")
        -y*z + x^y/log(x)

        
    We integrate the above function in maple now::

        sage: g = maple(f); g                             # optional -- requires maple
        sin(x^2)+y^z
        sage: g.integrate(x)                              # optional -- requires maple
        1/2*2^(1/2)*Pi^(1/2)*FresnelS(2^(1/2)/Pi^(1/2)*x)+y^z*x

    We next integrate a function with no closed form integral. Notice
    that the answer comes back as an expression that contains an
    integral itself.

    ::

        sage: A = integral(1/ ((x-4) * (x^3+2*x+1)), x); A
        1/73*log(x - 4) - 1/73*integrate((x^2 + 4*x + 18)/(x^3 + 2*x + 1), x)

    We now show that floats are not converted to rationals
    automatically since we by default have keepfloat: true in maxima.

    ::

        sage: integral(e^(-x^2),(x, 0, 0.1))
        0.0562314580091*sqrt(pi)

    ALIASES: integral() and integrate() are the same.

    EXAMPLES:

    Here is an example where we have to use assume::

        sage: a,b = var('a,b')
        sage: integrate(1/(x^3 *(a+b*x)^(1/3)), x)
        Traceback (most recent call last):
        ...
        ValueError: Computation failed since Maxima requested additional
        constraints; using the 'assume' command before integral evaluation
        *may* help (example of legal syntax is 'assume(a>0)', see `assume?`
        for more details)
        Is  a  positive or negative?

    So we just assume that `a>0` and the integral works::

        sage: assume(a>0)
        sage: integrate(1/(x^3 *(a+b*x)^(1/3)), x)
        2/9*sqrt(3)*b^2*arctan(1/3*(2*(b*x + a)^(1/3) + a^(1/3))*sqrt(3)/a^(1/3))/a^(7/3) + 2/9*b^2*log((b*x + a)^(1/3) - a^(1/3))/a^(7/3) - 1/9*b^2*log((b*x + a)^(2/3) + (b*x + a)^(1/3)*a^(1/3) + a^(2/3))/a^(7/3) + 1/6*(4*(b*x + a)^(5/3)*b^2 - 7*(b*x + a)^(2/3)*a*b^2)/((b*x + a)^2*a^2 - 2*(b*x + a)*a^3 + a^4)

    TESTS:

    The following integral was broken prior to Maxima 5.15.0 -
    see #3013::

        sage: integrate(sin(x)*cos(10*x)*log(x), x)
        1/198*(11*cos(9*x) - 9*cos(11*x))*log(x) + 1/44*Ei(-11*I*x) - 1/36*Ei(-9*I*x) - 1/36*Ei(9*I*x) + 1/44*Ei(11*I*x)

    It is no longer possible to use certain functions without an
    explicit variable.  Instead, evaluate the function at a variable,
    and then take the integral::
    
        sage: integrate(sin)
        Traceback (most recent call last):
        ...
        TypeError

        sage: integrate(sin(x), x)
        -cos(x)
        sage: integrate(sin(x), x, 0, 1)
        -cos(1) + 1

    Check if #780 is fixed::

        sage: _ = var('x,y')
        sage: f = log(x^2+y^2)
        sage: res = integral(f,x,0.0001414, 1.); res
        Traceback (most recent call last):
        ...
        ValueError: Computation failed since Maxima requested additional
        constraints; using the 'assume' command before integral evaluation
        *may* help (example of legal syntax is 'assume((y-1)*(y+1)>0)',
        see `assume?` for more details)
        Is  (y-1)*(y+1)  positive, negative, or zero?
        sage: assume(y>1)
        sage: res = integral(f,x,0.0001414, 1.); res
        2*y*arctan(1/y) - 2*y*arctan(0.0001414/y) - 0.0001414*log(y^2 + 1.999396e-08) + log(y^2 + 1.0) - 1.9997172
        sage: nres = numerical_integral(f.subs(y=2), 0.0001414, 1.); nres
        (1.4638323264144..., 1.6251803529759...e-14)
        sage: res.subs(y=2).n()
        1.46383232641443
        sage: nres = numerical_integral(f.subs(y=.5), 0.0001414, 1.); nres
        (-0.669511708872807, 7.768678110854711e-15)
        sage: res.subs(y=.5).n()
        -0.669511708872807

    Check if #6816 is fixed::

        sage: var('t,theta')
        (t, theta)
        sage: integrate(t*cos(-theta*t),t,0,pi)
        (pi*theta*sin(pi*theta) + cos(pi*theta))/theta^2 - 1/theta^2
        sage: integrate(t*cos(-theta*t),(t,0,pi))
        (pi*theta*sin(pi*theta) + cos(pi*theta))/theta^2 - 1/theta^2
        sage: integrate(t*cos(-theta*t),t)
        (t*theta*sin(t*theta) + cos(t*theta))/theta^2
        sage: integrate(x^2,(x)) # this worked before
        1/3*x^3
        sage: integrate(x^2,(x,)) # this didn't
        1/3*x^3
        sage: integrate(x^2,(x,1,2))
        7/3
        sage: integrate(x^2,(x,1,2,3))
        Traceback (most recent call last):
        ...
        ValueError: invalid input (x, 1, 2, 3) - please use variable, with or without two endpoints

    Note that this used to be the test, but it is
    actually divergent (though Maxima as yet does
    not say so)::

        sage: integrate(t*cos(-theta*t),(t,-oo,oo))
        integrate(t*cos(t*theta), t, -Infinity, +Infinity)

    Check if #6189 is fixed (which, by the way, also
    demonstrates it's not always good to expand)::

        sage: n = N; n
        <function numerical_approx at ...>
        sage: F(x) = 1/sqrt(2*pi*1^2)*exp(-1/(2*1^2)*(x-0)^2)
        sage: G(x) = 1/sqrt(2*pi*n(1)^2)*exp(-1/(2*n(1)^2)*(x-n(0))^2)
        sage: integrate( (F(x)-F(x))^2, x, -infinity, infinity).n()
        0.000000000000000
        sage: integrate( ((F(x)-G(x))^2).expand(), x, -infinity, infinity).n()
        -6.26376265908397e-17
        sage: integrate( (F(x)-G(x))^2, x, -infinity, infinity).n()
        -6.26376265908397e-17

    This was broken before Maxima 5.20::

        sage: exp(-x*i).integral(x,0,1)
        I*e^(-I) - I

    Test deprecation warning when variable is not specified::

        sage: x.integral()
        doctest:...: DeprecationWarning: Variable of integration should be specified explicitly.
        1/2*x^2

    Test that #8729 is fixed::

        sage: t = var('t')
        sage: a = sqrt((sin(t))^2 + (cos(t))^2)
        sage: integrate(a, t, 0, 2*pi)
        2*pi
        sage: a.simplify_full().simplify_trig()
        1

    Maxima uses Cauchy Principal Value calculations to
    integrate certain convergent integrals.  Here we test
    that this does not raise an error message (see #11987)::

        sage: integrate(sin(x)*sin(x/3)/x^2, x, 0, oo)
        1/6*pi

    Maxima returned a negative value for this integral prior to
    maxima-5.24 (trac #10923). Ideally we would get an answer in terms
    of the gamma function; however, we get something equivalent::

        sage: actual_result = integral(e^(-1/x^2), x, 0, 1)
        sage: actual_result.full_simplify()
        ((e*erf(1) - e)*sqrt(pi) + 1)*e^(-1)
        sage: ideal_result = 1/2*gamma(-1/2, 1)
        sage: error = actual_result - ideal_result
        sage: error.numerical_approx() # abs tol 10e-10
        0

    """
    if isinstance(v, (list, tuple)) and a is None and b is None:
        if len(v) == 1:  # bare variable in a tuple
            v = v[0]
        elif len(v) == 3:  # variable and endpoints
            v, a, b = v
        elif len(v) == 2:  # endpoints only
            a, b = v
            v = None
        elif len(v) == 0:
            v = None
        else:
            raise ValueError, "invalid input %s - please use variable, with or without two endpoints" % repr(
                v)
    elif b is None and a is not None:
        # two arguments, must be endpoints
        a, b = v, a
        v = None

    if v is None:
        from sage.misc.misc import deprecation
        deprecation("Variable of integration should be specified explicitly.")
        v = expression.default_variable()
        if isinstance(expression, Function):
            # a bare function like sin
            expression = expression(v)

    if (a is None) ^ (b is None):
        raise TypeError, 'only one endpoint given'

    # Check algorithm
    if algorithm is not None:
        integrator = available_integrators.get(algorithm)
        if not integrator:
            raise ValueError, "Unknown algorithm: %s" % algorithm
        return integrator(expression, v, a, b)

    if a is None:
        return indefinite_integral(expression, v)
    else:
        return definite_integral(expression, v, a, b)
Example #48
0
def integrate(expression, v=None, a=None, b=None, algorithm=None):
    r"""
    Returns the indefinite integral with respect to the variable
    `v`, ignoring the constant of integration. Or, if endpoints
    `a` and `b` are specified, returns the definite
    integral over the interval `[a, b]`.

    If ``self`` has only one variable, then it returns the
    integral with respect to that variable.

    If definite integration fails, it could be still possible to
    evaluate the definite integral using indefinite integration with
    the Newton - Leibniz theorem (however, the user has to ensure that the
    indefinite integral is continuous on the compact interval `[a,b]` and
    this theorem can be applied).

    INPUT:
 
    - ``v`` - a variable or variable name.  This can also be a tuple of
      the variable (optional) and endpoints (i.e., ``(x,0,1)`` or ``(0,1)``).
 
    - ``a`` - (optional) lower endpoint of definite integral
 
    - ``b`` - (optional) upper endpoint of definite integral
 
    - ``algorithm`` - (default: 'maxima') one of
 
       - 'maxima' - use maxima (the default)
             
       - 'sympy' - use sympy (also in Sage)
               
       - 'mathematica_free' - use http://integrals.wolfram.com/
 
     EXAMPLES::

        sage: x = var('x')
        sage: h = sin(x)/(cos(x))^2
        sage: h.integral(x)
        1/cos(x)

    ::

        sage: f = x^2/(x+1)^3
        sage: f.integral(x)
        1/2*(4*x + 3)/(x^2 + 2*x + 1) + log(x + 1)

    ::

        sage: f = x*cos(x^2)
        sage: f.integral(x, 0, sqrt(pi))
        0
        sage: f.integral(x, a=-pi, b=pi)
        0

    ::

        sage: f(x) = sin(x)
        sage: f.integral(x, 0, pi/2)
        x |--> 1

    The variable is required, but the endpoints are optional::

        sage: y=var('y')
        sage: integral(sin(x), x)
        -cos(x)
        sage: integral(sin(x), y)
        y*sin(x)
        sage: integral(sin(x), x, pi, 2*pi)
        -2
        sage: integral(sin(x), y, pi, 2*pi)
        pi*sin(x)
        sage: integral(sin(x), (x, pi, 2*pi))
        -2
        sage: integral(sin(x), (y, pi, 2*pi))
        pi*sin(x)

    Constraints are sometimes needed::

        sage: var('x, n')
        (x, n)
        sage: integral(x^n,x)
        Traceback (most recent call last):
        ...
        ValueError: Computation failed since Maxima requested additional
        constraints; using the 'assume' command before integral evaluation
        *may* help (example of legal syntax is 'assume(n+1>0)', see `assume?`
        for more details)
        Is  n+1  zero or nonzero?
        sage: assume(n > 0)
        sage: integral(x^n,x)
        x^(n + 1)/(n + 1)
        sage: forget()

    Usually the constraints are of sign, but others are possible::

        sage: assume(n==-1)
        sage: integral(x^n,x)
        log(x)

    Note that an exception is raised when a definite integral is
    divergent::

        sage: forget() # always remember to forget assumptions you no longer need
        sage: integrate(1/x^3,(x,0,1))
        Traceback (most recent call last):
        ...
        ValueError: Integral is divergent.
        sage: integrate(1/x^3,x,-1,3)
        Traceback (most recent call last):
        ...
        ValueError: Integral is divergent.

    But Sage can calculate the convergent improper integral of
    this function::

        sage: integrate(1/x^3,x,1,infinity)
        1/2

    The examples in the Maxima documentation::

        sage: var('x, y, z, b')
        (x, y, z, b)
        sage: integral(sin(x)^3, x)
        1/3*cos(x)^3 - cos(x)
        sage: integral(x/sqrt(b^2-x^2), b)
        x*log(2*b + 2*sqrt(b^2 - x^2))
        sage: integral(x/sqrt(b^2-x^2), x)
        -sqrt(b^2 - x^2)
        sage: integral(cos(x)^2 * exp(x), x, 0, pi)
        3/5*e^pi - 3/5
        sage: integral(x^2 * exp(-x^2), x, -oo, oo)
        1/2*sqrt(pi)

    We integrate the same function in both Mathematica and Sage (via
    Maxima)::

        sage: _ = var('x, y, z')
        sage: f = sin(x^2) + y^z
        sage: g = mathematica(f)                           # optional  -- requires mathematica
        sage: print g                                      # optional -- requires mathematica
                  z        2
                 y  + Sin[x ]
        sage: print g.Integrate(x)                         # optional -- requires mathematica
                    z        Pi                2
                 x y  + Sqrt[--] FresnelS[Sqrt[--] x]
                             2                 Pi
        sage: print f.integral(x)
        y^z*x + 1/8*((I + 1)*sqrt(2)*erf((1/2*I + 1/2)*sqrt(2)*x) + (I - 1)*sqrt(2)*erf((1/2*I - 1/2)*sqrt(2)*x))*sqrt(pi)

    Alternatively, just use algorithm='mathematica_free' to integrate via Mathematica
    over the internet (does NOT require a Mathematica license!)::

        sage: _ = var('x, y, z')
        sage: f = sin(x^2) + y^z
        sage: f.integrate(algorithm="mathematica_free")       # optional -- requires internet
        sqrt(pi)*sqrt(1/2)*fresnels(sqrt(2)*x/sqrt(pi)) + y^z*x

    We can also use Sympy::

        sage: _ = var('x, y, z')
        sage: (x^y-z).integrate(y)
        -y*z + x^y/log(x)
        sage: (x^y-z).integrate(y,algorithm="sympy")
        -y*z + x^y/log(x)

        
    We integrate the above function in maple now::

        sage: g = maple(f); g                             # optional -- requires maple
        sin(x^2)+y^z
        sage: g.integrate(x)                              # optional -- requires maple
        1/2*2^(1/2)*Pi^(1/2)*FresnelS(2^(1/2)/Pi^(1/2)*x)+y^z*x

    We next integrate a function with no closed form integral. Notice
    that the answer comes back as an expression that contains an
    integral itself.

    ::

        sage: A = integral(1/ ((x-4) * (x^3+2*x+1)), x); A
        1/73*log(x - 4) - 1/73*integrate((x^2 + 4*x + 18)/(x^3 + 2*x + 1), x)

    We now show that floats are not converted to rationals
    automatically since we by default have keepfloat: true in maxima.

    ::

        sage: integral(e^(-x^2),(x, 0, 0.1))
        0.0562314580091*sqrt(pi)

    ALIASES: integral() and integrate() are the same.

    EXAMPLES:

    Here is an example where we have to use assume::

        sage: a,b = var('a,b')
        sage: integrate(1/(x^3 *(a+b*x)^(1/3)), x)
        Traceback (most recent call last):
        ...
        ValueError: Computation failed since Maxima requested additional
        constraints; using the 'assume' command before integral evaluation
        *may* help (example of legal syntax is 'assume(a>0)', see `assume?`
        for more details)
        Is  a  positive or negative?

    So we just assume that `a>0` and the integral works::

        sage: assume(a>0)
        sage: integrate(1/(x^3 *(a+b*x)^(1/3)), x)
        2/9*sqrt(3)*b^2*arctan(1/3*(2*(b*x + a)^(1/3) + a^(1/3))*sqrt(3)/a^(1/3))/a^(7/3) + 2/9*b^2*log((b*x + a)^(1/3) - a^(1/3))/a^(7/3) - 1/9*b^2*log((b*x + a)^(2/3) + (b*x + a)^(1/3)*a^(1/3) + a^(2/3))/a^(7/3) + 1/6*(4*(b*x + a)^(5/3)*b^2 - 7*(b*x + a)^(2/3)*a*b^2)/((b*x + a)^2*a^2 - 2*(b*x + a)*a^3 + a^4)

    TESTS:

    The following integral was broken prior to Maxima 5.15.0 -
    see #3013::

        sage: integrate(sin(x)*cos(10*x)*log(x), x)
        1/198*(11*cos(9*x) - 9*cos(11*x))*log(x) + 1/44*Ei(-11*I*x) + 1/44*Ei(11*I*x) - 1/36*Ei(-9*I*x) - 1/36*Ei(9*I*x)

    It is no longer possible to use certain functions without an
    explicit variable.  Instead, evaluate the function at a variable,
    and then take the integral::
    
        sage: integrate(sin)
        Traceback (most recent call last):
        ...
        TypeError

        sage: integrate(sin(x), x)
        -cos(x)
        sage: integrate(sin(x), x, 0, 1)
        -cos(1) + 1

    Check if #780 is fixed::

        sage: _ = var('x,y')
        sage: f = log(x^2+y^2)
        sage: res = integral(f,x,0.0001414, 1.); res
        Traceback (most recent call last):
        ...
        ValueError: Computation failed since Maxima requested additional constraints; using the 'assume' command before integral evaluation *may* help (example of legal syntax is 'assume(50015104*y^2-50015103>0)', see `assume?` for more details)
        Is  50015104*y^2-50015103  positive, negative, or zero?
        sage: assume(y>1)
        sage: res = integral(f,x,0.0001414, 1.); res
        2*y*arctan(1/y) - 2*y*arctan(0.0001414/y) - 0.0001414*log(y^2 + 1.999396e-08) + log(y^2 + 1.0) - 1.9997172
        sage: nres = numerical_integral(f.subs(y=2), 0.0001414, 1.); nres
        (1.4638323264144..., 1.6251803529759...e-14)
        sage: res.subs(y=2).n()
        1.46383232641443
        sage: nres = numerical_integral(f.subs(y=.5), 0.0001414, 1.); nres
        (-0.669511708872807, 7.768678110854711e-15)
        sage: res.subs(y=.5).n()
        -0.669511708872807

    Check if #6816 is fixed::

        sage: var('t,theta')
        (t, theta)
        sage: integrate(t*cos(-theta*t),t,0,pi)
        (pi*theta*sin(pi*theta) + cos(pi*theta))/theta^2 - 1/theta^2
        sage: integrate(t*cos(-theta*t),(t,0,pi))
        (pi*theta*sin(pi*theta) + cos(pi*theta))/theta^2 - 1/theta^2
        sage: integrate(t*cos(-theta*t),t)
        (t*theta*sin(t*theta) + cos(t*theta))/theta^2
        sage: integrate(x^2,(x)) # this worked before
        1/3*x^3
        sage: integrate(x^2,(x,)) # this didn't
        1/3*x^3
        sage: integrate(x^2,(x,1,2))
        7/3
        sage: integrate(x^2,(x,1,2,3))
        Traceback (most recent call last):
        ...
        ValueError: invalid input (x, 1, 2, 3) - please use variable, with or without two endpoints

    Note that this used to be the test, but it is
    actually divergent (though Maxima as yet does
    not say so)::

        sage: integrate(t*cos(-theta*t),(t,-oo,oo))
        integrate(t*cos(t*theta), t, -Infinity, +Infinity)

    Check if #6189 is fixed (which, by the way, also
    demonstrates it's not always good to expand)::

        sage: n = N; n
        <function numerical_approx at ...>
        sage: F(x) = 1/sqrt(2*pi*1^2)*exp(-1/(2*1^2)*(x-0)^2)
        sage: G(x) = 1/sqrt(2*pi*n(1)^2)*exp(-1/(2*n(1)^2)*(x-n(0))^2)
        sage: integrate( (F(x)-F(x))^2, x, -infinity, infinity).n()
        0.000000000000000
        sage: integrate( ((F(x)-G(x))^2).expand(), x, -infinity, infinity).n()
        -6.26376265908397e-17
        sage: integrate( (F(x)-G(x))^2, x, -infinity, infinity).n()
        -6.26376265908397e-17

    This was broken before Maxima 5.20::

        sage: exp(-x*i).integral(x,0,1)
        I*e^(-I) - I

    Test deprecation warning when variable is not specified::

        sage: x.integral()
        doctest:...: DeprecationWarning: Variable of integration should be specified explicitly.
        1/2*x^2

    Test that #8729 is fixed::

        sage: t = var('t')
        sage: a = sqrt((sin(t))^2 + (cos(t))^2)
        sage: integrate(a, t, 0, 2*pi)
        2*pi
        sage: a.simplify_full().simplify_trig()
        1

    Maxima uses Cauchy Principal Value calculations to
    integrate certain convergent integrals.  Here we test
    that this does not raise an error message (see #11987)::

        sage: integrate(sin(x)*sin(x/3)/x^2, x, 0, oo)
        1/6*pi

    Maxima returned a negative value for this integral prior to
    maxima-5.24 (trac #10923). Ideally we would get an answer in terms
    of the gamma function; however, we get something equivalent::

        sage: actual_result = integral(e^(-1/x^2), x, 0, 1)
        sage: actual_result.full_simplify()
        ((e*erf(1) - e)*sqrt(pi) + 1)*e^(-1)
        sage: ideal_result = 1/2*gamma(-1/2, 1)
        sage: error = actual_result - ideal_result
        sage: error.numerical_approx() # abs tol 1e-10
        0

    We won't get an evaluated answer here, which is better than
    the previous (wrong) answer of zero. See :trac:`10914`::

        sage: f = abs(sin(x))
        sage: integrate(f, x, 0, 2*pi)
        integrate(abs(sin(x)), x, 0, 2*pi)

    Another incorrect integral fixed upstream in Maxima, from
    :trac:`11233`::

        sage: a,t = var('a,t')
        sage: assume(a>0)
        sage: assume(x>0)
        sage: f = log(1 + a/(x * t)^2)
        sage: F = integrate(f, t, 1, Infinity)
        sage: F(x=1, a=7).numerical_approx() # abs tol 1e-10
        4.32025625668262

    """
    if isinstance(v, (list, tuple)) and a is None and b is None:
        if len(v)==1: # bare variable in a tuple
            v=v[0]
        elif len(v)==3: # variable and endpoints
            v,a,b=v
        elif len(v)==2: # endpoints only
            a,b=v
            v=None
        elif len(v)==0:
            v=None
        else:
            raise ValueError, "invalid input %s - please use variable, with or without two endpoints"%repr(v)
    elif b is None and a is not None:
        # two arguments, must be endpoints
        a, b = v, a
        v = None

    if v is None:
        from sage.misc.misc import deprecation
        deprecation("Variable of integration should be specified explicitly.")
        v = expression.default_variable()
        if isinstance(expression, Function):
            # a bare function like sin
            expression = expression(v)

    if (a is None) ^ (b is None):
        raise TypeError, 'only one endpoint given'

    # Check algorithm
    if algorithm is not None:
        integrator = available_integrators.get(algorithm)
        if not integrator:
            raise ValueError, "Unknown algorithm: %s" % algorithm
        return integrator(expression, v, a, b)

    if a is None:
        return indefinite_integral(expression, v)
    else:
        return definite_integral(expression, v, a, b)
Example #49
0
#                  http://www.gnu.org/licenses/
#*****************************************************************************


from sage.categories.all import GroupAlgebras
from sage.structure.parent_gens import ParentWithGens
from sage.algebras.algebra import Algebra
from sage.algebras.algebra_element import AlgebraElement
from sage.rings.all import IntegerRing
from sage.groups.group import Group
from sage.structure.formal_sum import FormalSums, FormalSum
from sage.sets.set import Set


from sage.misc.misc import deprecation
deprecation("The module group_algebra is deprecated and will be removed in a future version of Sage. Use group_algebra_new instead.")


class GroupAlgebra(Algebra):

    def __init__(self, group, base_ring = IntegerRing()):
        r""" Create the given group algebra.
        INPUT:
            -- (Group) group: a generic group.
            -- (Ring) base_ring: a commutative ring.
        OUTPUT:
            -- a GroupAlgebra instance.

        EXAMPLES::

            sage: from sage.algebras.group_algebra import GroupAlgebra
Example #50
0
def setup_for_eval_on_grid(funcs, ranges, plot_points=None, return_vars=False):
    """
    Calculate the necessary parameters to construct a list of points,
    and make the functions fast_callable.

    INPUT:
    
    -  ``funcs`` - a function, or a list, tuple, or vector of functions
    
    - ``ranges`` - a list of ranges.  A range can be a 2-tuple of
      numbers specifying the minimum and maximum, or a 3-tuple giving
      the variable explicitly.

    - ``plot_points`` - a tuple of integers specifying the number of
      plot points for each range.  If a single number is specified, it
      will be the value for all ranges.  This defaults to 2.
     
    - ``return_vars`` - (default False) If True, return the variables,
      in order.
    
    
    OUTPUT:
    
    
    - ``fast_funcs`` - if only one function passed, then a fast
       callable function.  If funcs is a list or tuple, then a tuple
       of fast callable functions is returned.

    - ``range_specs`` - a list of range_specs: for each range, a
       tuple is returned of the form (range_min, range_max,
       range_step) such that ``srange(range_min, range_max,
       range_step, include_endpoint=True)`` gives the correct points
       for evaluation.
    
    EXAMPLES::
    
        sage: x,y,z=var('x,y,z')
        sage: f(x,y)=x+y-z
        sage: g(x,y)=x+y
        sage: h(y)=-y
        sage: sage.plot.misc.setup_for_eval_on_grid(f, [(0, 2),(1,3),(-4,1)], plot_points=5)
        (<sage.ext...>, [(0.0, 2.0, 0.5), (1.0, 3.0, 0.5), (-4.0, 1.0, 1.25)])
        sage: sage.plot.misc.setup_for_eval_on_grid([g,h], [(0, 2),(-1,1)], plot_points=5)
        ((<sage.ext...>, <sage.ext...>), [(0.0, 2.0, 0.5), (-1.0, 1.0, 0.5)])
        sage: sage.plot.misc.setup_for_eval_on_grid([sin,cos], [(-1,1)], plot_points=9)
        ((<sage.ext...>, <sage.ext...>), [(-1.0, 1.0, 0.25)])
        sage: sage.plot.misc.setup_for_eval_on_grid([lambda x: x^2,cos], [(-1,1)], plot_points=9)
        ((<function <lambda> ...>, <sage.ext...>), [(-1.0, 1.0, 0.25)])
        sage: sage.plot.misc.setup_for_eval_on_grid([x+y], [(x,-1,1),(y,-2,2)])
        ((<sage.ext...>,), [(-1.0, 1.0, 2.0), (-2.0, 2.0, 4.0)])
        sage: sage.plot.misc.setup_for_eval_on_grid(x+y, [(x,-1,1),(y,-1,1)], plot_points=[4,9])
        (<sage.ext...>, [(-1.0, 1.0, 0.6666666666666666), (-1.0, 1.0, 0.25)])
        sage: sage.plot.misc.setup_for_eval_on_grid(x+y, [(x,-1,1),(y,-1,1)], plot_points=[4,9,10])
        Traceback (most recent call last):
        ...
        ValueError: plot_points must be either an integer or a list of integers, one for each range
        sage: sage.plot.misc.setup_for_eval_on_grid(x+y, [(1,-1),(y,-1,1)], plot_points=[4,9,10])
        Traceback (most recent call last):
        ...
        ValueError: Some variable ranges specify variables while others do not
        sage: sage.plot.misc.setup_for_eval_on_grid(x+y, [(1,-1),(-1,1)], plot_points=5)
        doctest:...: DeprecationWarning: Unnamed ranges for more than one variable is deprecated and will be removed from a future release of Sage; you can used named ranges instead, like (x,0,2)
        (<sage.ext...>, [(1.0, -1.0, 0.5), (-1.0, 1.0, 0.5)])
        sage: sage.plot.misc.setup_for_eval_on_grid(x+y, [(y,1,-1),(x,-1,1)], plot_points=5)
        (<sage.ext...>, [(1.0, -1.0, 0.5), (-1.0, 1.0, 0.5)])
        sage: sage.plot.misc.setup_for_eval_on_grid(x+y, [(x,1,-1),(x,-1,1)], plot_points=5)
        Traceback (most recent call last):
        ...
        ValueError: range variables should be distinct, but there are duplicates
        sage: sage.plot.misc.setup_for_eval_on_grid(x+y, [(x,1,1),(y,-1,1)])
        Traceback (most recent call last):
        ...
        ValueError: plot start point and end point must be different
        sage: sage.plot.misc.setup_for_eval_on_grid(x+y, [(x,1,-1),(y,-1,1)], return_vars=True)
        (<sage.ext...>, [(1.0, -1.0, 2.0), (-1.0, 1.0, 2.0)], [x, y])
        sage: sage.plot.misc.setup_for_eval_on_grid(x+y, [(y,1,-1),(x,-1,1)], return_vars=True)
        (<sage.ext...>, [(1.0, -1.0, 2.0), (-1.0, 1.0, 2.0)], [y, x])
    """
    if max(map(len, ranges)) != min(map(len, ranges)):
        raise ValueError, "Some variable ranges specify variables while others do not"

    if len(ranges[0])==3:
        vars = [r[0] for r in ranges]
        ranges = [r[1:] for r in ranges]
        if len(set(vars))<len(vars):
            raise ValueError, "range variables should be distinct, but there are duplicates"
    else:
        vars, free_vars = unify_arguments(funcs)
        if len(free_vars)>1:
            from sage.misc.misc import deprecation
            deprecation("Unnamed ranges for more than one variable is deprecated and will be removed from a future release of Sage; you can used named ranges instead, like (x,0,2)")

    # pad the variables if we don't have enough
    nargs = len(ranges)
    if len(vars)<nargs:
        vars += ('_',)*(nargs-len(vars))

    ranges = [[float(z) for z in r] for r in ranges]

    if plot_points is None:
        plot_points=2

    if not isinstance(plot_points, (list, tuple)):
        plot_points = [plot_points]*len(ranges)
    elif len(plot_points)!=nargs:
        raise ValueError, "plot_points must be either an integer or a list of integers, one for each range"
        
    plot_points = [int(p) if p>=2 else 2 for p in plot_points]
    range_steps = [abs(range[1] - range[0])/(p-1) for range, p in zip(ranges, plot_points)]
    if min(range_steps) == float(0):
        raise ValueError, "plot start point and end point must be different"
    
    options={}
    if nargs==1:
        options['expect_one_var']=True

    if is_Vector(funcs):
        funcs = list(funcs)

    #TODO: raise an error if there is a function/method in funcs that takes more values than we have ranges

    if return_vars:
        return fast_float(funcs, *vars,**options), [tuple(range+[range_step]) for range,range_step in zip(ranges, range_steps)], vars
    else:
        return fast_float(funcs, *vars,**options), [tuple(range+[range_step]) for range,range_step in zip(ranges, range_steps)]