Ticket #7661: trac_7661-maxima_convert_back.take2.patch

File trac_7661-maxima_convert_back.take2.patch, 18.8 KB (added by burcin, 11 years ago)

apply only this patch

  • sage/calculus/calculus.py

    # HG changeset patch
    # User Burcin Erocal <burcin@erocal.org>
    # Date 1270839171 -7200
    # Node ID 70c87157c24e7cd2a06a6ad006ba03f1a7ac5545
    # Parent  b016b621382817c725745151bcf9f2a51f1c7f5d
    trac 7661: fix problems with conversion of maxima elements to symbolic
    expressions
    
    diff --git a/sage/calculus/calculus.py b/sage/calculus/calculus.py
    a b  
    292292    x |--> 1/2
    293293"""
    294294
    295 import weakref
    296295import re
    297 from sage.rings.all import (CommutativeRing, RealField, is_Polynomial,
    298                             is_MPolynomial, is_MPolynomialRing, is_FractionFieldElement,
    299                             is_RealNumber, is_ComplexNumber, RR, is_NumberFieldElement,
    300                             Integer, Rational, CC, QQ, CDF, ZZ,
    301                             PolynomialRing, ComplexField, RealDoubleElement,
    302                             algdep, Integer, RealNumber, RealIntervalField)
    303 
     296from sage.rings.all import RR, Integer, CC, QQ, RealDoubleElement, algdep
    304297from sage.rings.real_mpfr import create_RealNumber
    305298
    306 from sage.structure.element import RingElement, is_Element
    307 from sage.structure.parent_base import ParentWithBase
    308 
    309 import operator
    310299from sage.misc.latex import latex, latex_variable_name
    311 from sage.misc.misc import uniq as unique
    312 from sage.structure.sage_object import SageObject
    313 
    314300from sage.interfaces.maxima import Maxima
    315 
    316 import sage.numerical.optimize
    317 
    318301from sage.misc.parser import Parser
    319302
    320 import math
    321 
    322 import sage.ext.fast_eval as fast_float
    323 
    324303from sage.symbolic.ring import var, SR, is_SymbolicVariable
    325304from sage.symbolic.expression import Expression
    326305from sage.symbolic.function import Function
    327306from sage.symbolic.function_factory import function_factory, function
    328307from sage.symbolic.integration.integral import indefinite_integral, \
    329308        definite_integral
    330 
    331 arc_functions =  ['asin', 'acos', 'atan', 'asinh', 'acosh', 'atanh', 'acoth', 'asech', 'acsch', 'acot', 'acsc', 'asec']
     309import sage.symbolic.pynac
    332310
    333311maxima = Maxima(init_code = ['display2d:false', 'domain: complex', 'keepfloat: true', 'load(to_poly_solver)', 'load(simplify_sum)'],
    334312                script_subdirectory=None)
     
    10241002        else:
    10251003            raise NotImplementedError, "sympy does not support one-sided limits"
    10261004
     1005    return l.sage()
    10271006    return ex.parent()(l)
    10281007
    10291008lim = limit
     
    14341413register_symbol(minus_infinity, dict(maxima='minf'))
    14351414
    14361415from sage.misc.multireplace import multiple_replace
    1437 
    14381416import re
    14391417
    1440 
    14411418maxima_tick = re.compile("'[a-z|A-Z|0-9|_]*")
    14421419
    14431420maxima_qp = re.compile("\?\%[a-z|A-Z|0-9|_]*")  # e.g., ?%jacobi_cd
     
    14531430   
    14541431    INPUT:
    14551432   
    1456    
    14571433    -  ``x`` - a string
    14581434   
    14591435    -  ``equals_sub`` - (default: False) if True, replace
     
    14761452        sage: a.sage()
    14771453        x != 0
    14781454    """
    1479     syms = dict(_syms)
     1455    syms = sage.symbolic.pynac.symbol_table.get('maxima', {}).copy()
    14801456
    14811457    if len(x) == 0:
    14821458        raise RuntimeError, "invalid symbolic expression -- ''"
     
    15541530        is_simplified = False
    15551531
    15561532
    1557 # External access used by restore
    1558 from sage.symbolic.pynac import symbol_table
    1559 _syms = syms_cur = symbol_table.get('maxima', {})
    1560 syms_default = dict(syms_cur)
    1561 
    15621533# Comma format options for Maxima
    15631534def mapped_opts(v):
    15641535    """
     
    15671538   
    15681539    INPUT:
    15691540   
    1570    
    15711541    -  ``v`` - an object
    15721542   
    1573    
    15741543    OUTPUT: a string.
    15751544   
    15761545    The main use of this is to turn Python bools into lower case
     
    16031572
    16041573# Parser for symbolic ring elements
    16051574
     1575# We keep two dictionaries syms_cur and syms_default to keep the current symbol
     1576# table and the state of the table at startup respectively. These are used by
     1577# the restore() function (see sage.misc.reset).
     1578#
     1579# The dictionary _syms is used as a lookup table for the system function
     1580# registry by _find_func() below. It gets updated by
     1581# symbolic_expression_from_string() before calling the parser.
     1582from sage.symbolic.pynac import symbol_table
     1583_syms = syms_cur = symbol_table.get('functions', {})
     1584syms_default = dict(syms_cur)
     1585
     1586# This dictionary is used to pass a lookup table other than the system registry
     1587# to the parser. A global variable is necessary since the parser calls the
     1588# _find_var() and _find_func() functions below without extra arguments.
    16061589_augmented_syms = {}
    16071590
     1591from sage.symbolic.ring import pynac_symbol_registry
     1592
    16081593def _find_var(name):
    16091594    """
    16101595    Function to pass to Parser for constructing
     
    16191604        I
    16201605    """
    16211606    try:
    1622         return (_augmented_syms or _syms)[name]
     1607        res = _augmented_syms.get(name)
     1608        if res is None:
     1609            return pynac_symbol_registry[name]
     1610        # _augmented_syms might contain entries pointing to functions if
     1611        # previous computations polluted the maxima workspace
     1612        if not isinstance(res, Function):
     1613            return res
    16231614    except KeyError:
    16241615        pass
     1616
     1617    # try to find the name in the global namespace
     1618    # needed for identifiers like 'e', etc.
    16251619    try:
    16261620        return SR(sage.all.__dict__[name])
    16271621    except (KeyError, TypeError):
     
    16461640        0
    16471641    """
    16481642    try:
    1649         func = _syms.get(name)
     1643        func = _augmented_syms.get(name)
    16501644        if func is None:
    1651             func = _augmented_syms[name]
     1645            func = _syms[name]
    16521646        if not isinstance(func, Expression):
    16531647            return func
    16541648    except KeyError:
     
    16601654    except (KeyError, TypeError):
    16611655        return function_factory(name)
    16621656
    1663 SR_parser = Parser(make_int      = lambda x: SR(Integer(x)), 
     1657SR_parser = Parser(make_int      = lambda x: SR(Integer(x)),
    16641658                   make_float    = lambda x: SR(RealDoubleElement(x)),
    16651659                   make_var      = _find_var,
    16661660                   make_function = _find_func)
     
    16731667   
    16741668    INPUT:
    16751669   
    1676    
    16771670    -  ``s`` - a string
    16781671   
    16791672    -  ``syms`` - (default: None) dictionary of
     
    16891682        sage: sage.calculus.calculus.symbolic_expression_from_string('[sin(0)*x^2,3*spam+e^pi]',syms={'spam':y},accept_sequence=True)
    16901683        [0, 3*y + e^pi]
    16911684    """
    1692     # from sage.functions.constants import I # can't import this at the top, but need it now
    1693     # _syms['i'] = _syms['I'] = I
     1685    global _syms
     1686    _syms = sage.symbolic.pynac.symbol_table['functions'].copy()
    16941687    parse_func = SR_parser.parse_sequence if accept_sequence else SR_parser.parse_expression
    16951688    if syms is None:
    16961689        return parse_func(s)
     
    17011694            return parse_func(s)
    17021695        finally:
    17031696            _augmented_syms = {}
    1704 
    1705 def symbolic_expression_from_maxima_element(x, maxima=maxima):
    1706     """
    1707     Given an element of the calculus copy of the Maxima interface,
    1708     create the corresponding Sage symbolic expression.
    1709    
    1710     EXAMPLES::
    1711    
    1712         sage: a = sage.calculus.calculus.maxima('x^(sqrt(y)+%pi) + sin(%e + %pi)')
    1713         sage: sage.calculus.calculus.symbolic_expression_from_maxima_element(a)
    1714         x^(pi + sqrt(y)) - sin(e)
    1715         sage: var('x, y')
    1716         (x, y)
    1717         sage: v = sage.calculus.calculus.maxima.vandermonde_matrix([x, y, 1/2])
    1718         sage: sage.calculus.calculus.symbolic_expression_from_maxima_element(v)
    1719         [  1   x x^2]
    1720         [  1   y y^2]
    1721         [  1 1/2 1/4]
    1722     """
    1723     return symbolic_expression_from_maxima_string(x.name(), maxima=maxima)
  • sage/functions/other.py

    diff --git a/sage/functions/other.py b/sage/functions/other.py
    a b  
    33"""
    44from sage.symbolic.function import GinacFunction, BuiltinFunction
    55from sage.symbolic.expression import Expression
     6from sage.symbolic.pynac import register_symbol, symbol_table
    67from sage.libs.pari.gen import pari
    78from sage.symbolic.all import SR
    89from sage.rings.all import Integer, Rational, RealField, CC, RR, \
     
    4849            Traceback (most recent call last):
    4950            ...
    5051            TypeError: unable to simplify to complex approximation
     52
     53        TESTS:
     54
     55        Check if conversion from maxima elements work::
     56
     57            sage: merf = maxima(erf(x)).sage().operator()
     58            sage: merf == erf
     59            True
    5160        """
    5261        BuiltinFunction.__init__(self, "erf", latex_name=r"\text{erf}")
    5362
     
    690699        raise TypeError, "Symbolic function gamma takes at most 2 arguments (%s given)"%(len(args)+1)
    691700    return incomplete_gamma(a,args[0],**kwds)
    692701
     702# We have to add the wrapper function manually to the symbol_table when we have
     703# two functions with different number of arguments and the same name
     704symbol_table['functions']['gamma'] = gamma
     705
    693706class Function_psi1(GinacFunction):
    694707    def __init__(self):
    695708        r"""
     
    836849        raise TypeError, "Symbolic function psi takes at most 2 arguments (%s given)"%(len(args)+1)
    837850    return psi2(x,args[0],**kwds)
    838851
     852# We have to add the wrapper function manually to the symbol_table when we have
     853# two functions with different number of arguments and the same name
     854symbol_table['functions']['psi'] = psi
    839855
    840856class Function_factorial(GinacFunction):
    841857    def __init__(self):
     
    11161132            pass
    11171133        return _do_sqrt(x, *args, **kwds)
    11181134
    1119 # register sqrt in pynac symbol_table for conversion back from maxima
    1120 from sage.symbolic.pynac import register_symbol#, symbol_table
    1121 register_symbol(sqrt, dict(maxima='sqrt', mathematica='Sqrt', maple='sqrt'))
     1135# register sqrt in pynac symbol_table for conversion back from other systems
     1136register_symbol(sqrt, dict(mathematica='Sqrt'))
     1137symbol_table['functions']['sqrt'] = sqrt
    11221138   
    11231139Function_sqrt = type('deprecated_sqrt', (),
    11241140        {'__call__': staticmethod(sqrt),
  • sage/functions/special.py

    diff --git a/sage/functions/special.py b/sage/functions/special.py
    a b  
    394394import sage.rings.ring as ring
    395395from sage.functions.other import real, imag
    396396from sage.symbolic.function import BuiltinFunction
    397 from sage.calculus.calculus import maxima, symbolic_expression_from_maxima_element
     397from sage.calculus.calculus import maxima
    398398
    399399def meval(x):
    400     from sage.calculus.calculus import symbolic_expression_from_maxima_element
    401     return symbolic_expression_from_maxima_element(maxima(x), maxima)
     400    return maxima(x).sage()
    402401
    403402_done = False
    404403def _init():
     
    513512        if self.name() in repr(s):
    514513            return None
    515514        else:
    516             return  symbolic_expression_from_maxima_element(s)
     515            return s.sage()
    517516
    518517from sage.misc.cachefunc import cached_function
    519518
  • sage/interfaces/maxima.py

    diff --git a/sage/interfaces/maxima.py b/sage/interfaces/maxima.py
    a b  
    17691769            sqrt(2) + sqrt(3) + 2.5
    17701770            sage: type(d)
    17711771            <type 'sage.symbolic.expression.Expression'>           
     1772
     1773            sage: a = sage.calculus.calculus.maxima('x^(sqrt(y)+%pi) + sin(%e + %pi)')
     1774            sage: a._sage_()
     1775            x^(pi + sqrt(y)) - sin(e)
     1776            sage: var('x, y')
     1777            (x, y)
     1778            sage: v = sage.calculus.calculus.maxima.vandermonde_matrix([x, y, 1/2])
     1779            sage: v._sage_()
     1780            [  1   x x^2]
     1781            [  1   y y^2]
     1782            [  1 1/2 1/4]
     1783
     1784        Check if #7661 is fixed::
     1785
     1786            sage: var('delta')
     1787            delta
     1788            sage: (2*delta).simplify()
     1789            2*delta
    17721790        """
    1773         from sage.calculus.calculus import symbolic_expression_from_maxima_string
    1774         #return symbolic_expression_from_maxima_string(self.name(), maxima=self.parent())
    1775         return symbolic_expression_from_maxima_string(repr(self))
     1791        import sage.calculus.calculus as calculus
     1792        return calculus.symbolic_expression_from_maxima_string(self.name(),
     1793                maxima=self.parent())
    17761794
    17771795    def _symbolic_(self, R):
    17781796        """
  • sage/plot/plot3d/plot3d.py

    diff --git a/sage/plot/plot3d/plot3d.py b/sage/plot/plot3d/plot3d.py
    a b  
    174174            [3, -1, 4]
    175175        """
    176176        from sage.symbolic.expression import is_Expression
    177         from sage.calculus.calculus import is_RealNumber
     177        from sage.rings.real_mpfr import is_RealNumber
    178178        from sage.rings.integer import is_Integer
    179179        if params is not None and (is_Expression(func) or is_RealNumber(func) or is_Integer(func)):
    180180            return self.transform(**{
  • sage/symbolic/expression.pyx

    diff --git a/sage/symbolic/expression.pyx b/sage/symbolic/expression.pyx
    a b  
    65146514            [x == 1/2*pi]
    65156515            sage: solve(cos(x)==0,x,to_poly_solve=True)
    65166516            [x == 1/2*pi]
    6517             sage: from sage.calculus.calculus import maxima, symbolic_expression_from_maxima_element
     6517            sage: from sage.calculus.calculus import maxima
    65186518            sage: sol = maxima(cos(x)==0).to_poly_solve(x)
    6519             sage: symbolic_expression_from_maxima_element(sol)
     6519            sage: sol.sage()
    65206520            [[x == -1/2*pi + 2*pi*z57], [x == 1/2*pi + 2*pi*z59]]
    65216521
    65226522        If a returned unsolved expression has a denominator, but the
     
    65246524
    65256525            sage: solve(cos(x) * sin(x) == 1/2, x, to_poly_solve=True)
    65266526            [sin(x) == 1/2/cos(x)]
    6527             sage: from sage.calculus.calculus import maxima, symbolic_expression_from_maxima_element
     6527            sage: from sage.calculus.calculus import maxima
    65286528            sage: sol = maxima(cos(x) * sin(x) == 1/2).to_poly_solve(x)
    6529             sage: symbolic_expression_from_maxima_element(sol)
     6529            sage: sol.sage()
    65306530            [[x == 1/4*pi + pi*z73]]
    65316531
    65326532        Some basic inequalities can be also solved::
     
    66466646        # but also allows for the possibility of approximate   #
    66476647        # solutions being returned.                            #
    66486648        ########################################################
    6649         if to_poly_solve and not multiplicities: 
     6649        if to_poly_solve and not multiplicities:
    66506650            if len(X)==0: # if Maxima's solve gave no solutions, only try it
    66516651                try:
    66526652                    s = m.to_poly_solve(x)
     
    66566656                    X = []
    66576657
    66586658            for eq in X:
    6659                 if repr(x) in map(repr, eq.rhs().variables()) or repr(x) in repr(eq.lhs()): # If the RHS of one solution also has the variable, or if the LHS is not the variable, try another way to get solutions
    6660                     from sage.calculus.calculus import symbolic_expression_from_maxima_element
     6659                # If the RHS of one solution also has the variable, or if
     6660                # the LHS is not the variable, try another way to get solutions
     6661                if repr(x) in map(repr, eq.rhs().variables()) or \
     6662                        repr(x) in repr(eq.lhs()):
    66616663                    try:
    6662                         Y = symbolic_expression_from_maxima_element((eq._maxima_()).to_poly_solve(x)) # try to solve it using to_poly_solve
    6663                         X.remove(eq)
    6664                         X.extend([y[0] for y in Y]) # replace with the new solutions
     6664                        # try to solve it using to_poly_solve
     6665                        Y = eq._maxima_().to_poly_solve(x).sage()
     6666                        X.remove(eq)
     6667                        # replace with the new solutions
     6668                        X.extend([y[0] for y in Y])
    66656669                    except TypeError, mess:
    6666                         if "Error executing code in Maxima" in str(mess) or "unable to make sense of Maxima expression" in str(mess):
     6670                        if "Error executing code in Maxima" in str(mess) or \
     6671                                "unable to make sense of Maxima expression" in\
     6672                                str(mess):
    66676673                            if explicit_solutions:
    66686674                                X.remove(eq) # this removes an implicit solution
    66696675                            else:
  • sage/symbolic/random_tests.py

    diff --git a/sage/symbolic/random_tests.py b/sage/symbolic/random_tests.py
    a b  
    1515# For creating expressions with the full power of Pynac's simple expression
    1616# subset (with no quantifiers/operators; that is, no derivatives, integrals,
    1717# etc.)
    18 
    1918full_binary = [(0.3, operator.add), (0.1, operator.sub), (0.3, operator.mul), (0.2, operator.div), (0.1, operator.pow)]
    2019full_unary = [(0.8, operator.neg), (0.2, operator.inv)]
    21 full_functions = [(1.0, f, f.number_of_arguments()) for f in sage.symbolic.pynac.symbol_table['functions'].values() if f.number_of_arguments() > 0 and 'elliptic' not in str(f) and 'dickman_rho' not in str(f)]
    22 full_nullary = [(1.0, c) for c in [pi, e]] + [(0.05, c) for c in [golden_ratio, log2, euler_gamma, catalan, khinchin, twinprime, mertens, brun]]
    23 full_internal = [(0.6, full_binary, 2), (0.2, full_unary, 1), (0.2, full_functions)]
     20full_functions = [(1.0, f, f.number_of_arguments())
     21        for f in sage.symbolic.pynac.symbol_table['functions'].values()
     22            if hasattr(f, 'number_of_arguments') and
     23                f.number_of_arguments() > 0 ]
     24full_nullary = [(1.0, c) for c in [pi, e]] + [(0.05, c) for c in
     25        [golden_ratio, log2, euler_gamma, catalan, khinchin, twinprime,
     26            mertens, brun]]
     27full_internal = [(0.6, full_binary, 2), (0.2, full_unary, 1),
     28        (0.2, full_functions)]
    2429
    2530def normalize_prob_list(pl, extra=()):
    2631    r"""
     
    202207
    203208        sage: from sage.symbolic.random_tests import *
    204209        sage: random_expr(50, nvars=3, coeff_generator=CDF.random_element)
    205         sinh(sinh((-0.314177274493 + 0.144437996366*I)/csc(-v1^2*e/v3) + erf((-0.708874026302 - 0.954135400334*I)*v3) + 0.0275857401668 - 0.479027260657*I))^(-cosh(-polylog((v2^2 + (0.067987275089 + 1.08529153495*I)*v3)^(-v1 - v3), (5.29385548262 + 2.57440711353*I)*e/cosh((-0.436810529675 + 0.736945423566*I)*arccot(pi)))))
     210        sinh(elliptic_kc(-1/csc(-((2.62756608636 + 1.20798164491*I)*v3 + (2.62756608636 + 1.20798164491*I)*e)*pi*v1) + erf((-0.708874026302 - 0.954135400334*I)*v3) - elliptic_pi(0.520184609653 - 0.734276246499*I, v3, pi)))^(-elliptic_f((v2^2 + (0.067987275089 + 1.08529153495*I)*v3)^(-v1 - v3), (5.29385548262 + 2.57440711353*I)*e/arccoth(v2*arccot(0.812302592816 - 0.302973871736*I))))
    206211        sage: random_expr(5, verbose=True)
    207         About to apply <built-in function add> to [v1, v1]
    208         About to apply <built-in function mul> to [v1, -1/2]
    209         About to apply <built-in function mul> to [2*v1, -1/2*v1]
    210         -v1^2
     212        About to apply <built-in function mul> to [v1, v1]
     213        About to apply <built-in function add> to [v1^2, v1]
     214        About to apply <built-in function neg> to [v1^2 + v1]
     215        -v1^2 - v1
    211216    """
    212217    vars = [(1.0, sage.calculus.calculus.var('v%d' % (n+1))) for n in range(nvars)]
    213218    if ncoeffs is None:
  • sage/symbolic/ring.pyx

    diff --git a/sage/symbolic/ring.pyx b/sage/symbolic/ring.pyx
    a b  
    3535
    3636from sage.rings.all import RR, CC
    3737           
    38 cdef dict pynac_symbol_registry = {}
     38pynac_symbol_registry = {}
    3939
    4040cdef class SymbolicRing(CommutativeRing):
    4141    """