Ticket #7377: trac_7377-doctests-p3.patch

File trac_7377-doctests-p3.patch, 136.1 KB (added by jpflori, 8 years ago)

Rebased on Sage 4.7.alpha3, put back forgotten interface.py

  • sage/calculus/calculus.py

    # HG changeset patch
    # User Jean-Pierre Flori <flori@enst.fr>
    # Date 1299854441 -3600
    # Node ID 88910e6cc47b225ea59c52d4293671bed6adec0e
    # Parent  1bd1f40c456f506a6b0b92288d5f1c1f6335eee6
    Doctests.
    
    diff -r 1bd1f40c456f -r 88910e6cc47b sage/calculus/calculus.py
    a b  
    5757    sage: f = x + y + z/(2*sin(y*z/55))
    5858    sage: g = f^f; g
    5959    (x + y + 1/2*z/sin(1/55*y*z))^(x + y + 1/2*z/sin(1/55*y*z))
    60    
     60
    6161Differentiation and integration are available, but behind the
    6262scenes through Maxima::
    6363
     
    108108    sage: diff(T) # Jacobian matrix
    109109    [   (r, theta) |--> cos(theta) (r, theta) |--> -r*sin(theta)]
    110110    [   (r, theta) |--> sin(theta)  (r, theta) |--> r*cos(theta)]
    111     sage: T.diff().det() # Jacobian 
     111    sage: T.diff().det() # Jacobian
    112112    (r, theta) |--> r*sin(theta)^2 + r*cos(theta)^2
    113    
    114 When the order of variables is ambiguous, Sage will raise an exception when differentiating::
     113
     114When the order of variables is ambiguous, Sage will raise an
     115exception when differentiating::
    115116
    116117    sage: f = sin(x+y); f.derivative()
    117118    Traceback (most recent call last):
     
    146147
    147148    sage: f = sin(x)
    148149    sage: f(y)
    149     doctest:...: DeprecationWarning: 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=...)
     150    doctest:...: DeprecationWarning: Substitution using function-call
     151    syntax and unnamed arguments is deprecated and will be removed
     152    from a future release of Sage; you can use named arguments instead,
     153    like EXPR(x=..., y=...)
    150154    sin(y)
    151155    sage: f(pi)
    152156    0
     
    388392# This is not the same instance of Maxima as the general purpose one
    389393#from sage.interfaces.maxima import Maxima
    390394#maxima = Maxima(init_code = ['display2d : false', 'domain : complex',
    391 #                             'keepfloat : true', 'load(to_poly_solver)', 'load(simplify_sum)'],
     395#                             'keepfloat : true', 'load(to_poly_solver)',
     396#                             'load(simplify_sum)'],
    392397#                script_subdirectory=None)
    393398
    394399########################################################
     
    406411    - ``a`` - lower endpoint of the sum
    407412
    408413    - ``b`` - upper endpoint of the sum
    409    
     414
    410415    - ``algorithm`` - (default: 'maxima')  one of
    411416      - 'maxima' - use Maxima (the default)
    412417      - 'maple' - (optional) use Maple
     
    483488        sage: symbolic_sum(a*q^k, k, 0, n)
    484489        (a*q^(n + 1) - a)/(q - 1)
    485490
    486     For the geometric series, we will have to assume 
     491    For the geometric series, we will have to assume
    487492    the right values for the sum to converge::
    488493
    489494        sage: assume(abs(q) < 1)
     
    518523    Trac #10564 is fixed::
    519524
    520525        sage: sum (n^3 * x^n, n, 0, infinity)
    521         (x^3 + 4*x^2 + x)/(x^4 - 4*x^3 + 6*x^2 - 4*x + 1)       
     526        (x^3 + 4*x^2 + x)/(x^4 - 4*x^3 + 6*x^2 - 4*x + 1)
    522527
    523528    .. note::
    524529
    525        #. Sage can currently only understand a subset of the output of Maxima, Maple and
    526           Mathematica, so even if the chosen backend can perform the summation the
    527           result might not be convertable into a Sage expression.
     530       #. Sage can currently only understand a subset of the output of Maxima,
    528531
     532          Maple and Mathematica, so even if the chosen backend can perform
     533
     534          the summation the result might not be convertable into a Sage
     535
     536          expression.
    529537    """
    530538    if not is_SymbolicVariable(v):
    531539        if isinstance(v, str):
     
    573581
    574582    INPUT:
    575583
     584    - ``x`` - variable to integrate with respect to
    576585
    577     -  ``x`` - variable to integrate with respect to
     586    - ``a`` - lower endpoint of integration
    578587
    579     -  ``a`` - lower endpoint of integration
     588    - ``b`` - upper endpoint of integration
    580589
    581     -  ``b`` - upper endpoint of integration
     590    - ``desired_relative_error`` - (default: '1e-8') the
     591      desired relative error
    582592
    583     -  ``desired_relative_error`` - (default: '1e-8') the
    584        desired relative error
    585 
    586     -  ``maximum_num_subintervals`` - (default: 200)
    587        maxima number of subintervals
    588 
     593    - ``maximum_num_subintervals`` - (default: 200)
     594      maxima number of subintervals
    589595
    590596    OUTPUT:
    591597
     598    - float: approximation to the integral
    592599
    593     -  float: approximation to the integral
     600    - float: estimated absolute error of the
     601      approximation
    594602
    595     -  float: estimated absolute error of the
    596        approximation
     603    - the number of integrand evaluations
    597604
    598     -  the number of integrand evaluations
     605    - an error code:
    599606
    600     -  an error code:
     607      - ``0`` - no problems were encountered
    601608
    602        -  ``0`` - no problems were encountered
     609      - ``1`` - too many subintervals were done
    603610
    604        -  ``1`` - too many subintervals were done
     611      - ``2`` - excessive roundoff error
    605612
    606        -  ``2`` - excessive roundoff error
     613      - ``3`` - extremely bad integrand behavior
    607614
    608        -  ``3`` - extremely bad integrand behavior
     615      - ``4`` - failed to converge
    609616
    610        -  ``4`` - failed to converge
     617      - ``5`` - integral is probably divergent or slowly
     618        convergent
    611619
    612        -  ``5`` - integral is probably divergent or slowly
    613           convergent
    614 
    615        -  ``6`` - the input is invalid
    616 
     620      - ``6`` - the input is invalid
    617621
    618622    ALIAS: nintegrate is the same as nintegral
    619623
     
    631635        sage: f = f.nintegral(x,0,1,1e-14)
    632636        Traceback (most recent call last):
    633637        ...
    634         ValueError: Maxima (via quadpack) cannot compute the integral to that precision
     638        ValueError: Maxima (via quadpack) cannot compute the integral
     639        to that precision
    635640
    636641    EXAMPLES::
    637642
     
    701706        else:
    702707            raise TypeError, err
    703708
    704     #This is just a work around until there is a response to 
     709    #This is just a work around until there is a response to
    705710    #http://www.math.utexas.edu/pipermail/maxima/2008/012975.html
    706711    if 'quad_qags' in str(v):
    707712        raise ValueError, "Maxima (via quadpack) cannot compute the integral to that precision"
     
    716721
    717722    INPUT:
    718723
    719     -  ``var`` - polynomial variable name (default 'x')
     724    - ``var`` - polynomial variable name (default 'x')
    720725
    721     -  ``algorithm`` - 'algebraic' or 'numerical' (default
    722        both, but with numerical first)
     726    - ``algorithm`` - 'algebraic' or 'numerical' (default
     727      both, but with numerical first)
    723728
    724     -  ``bits`` - the number of bits to use in numerical
    725        approx
     729    - ``bits`` - the number of bits to use in numerical
     730      approx
    726731
    727     -  ``degree`` - the expected algebraic degree
     732    - ``degree`` - the expected algebraic degree
    728733
    729     -  ``epsilon`` - return without error as long as
    730        f(self) epsilon, in the case that the result cannot be proven.
     734    - ``epsilon`` - return without error as long as
     735      f(self) epsilon, in the case that the result cannot be proven.
    731736
    732        All of the above parameters are optional, with epsilon=0, bits and
    733        degree tested up to 1000 and 24 by default respectively. The
    734        numerical algorithm will be faster if bits and/or degree are given
    735        explicitly. The algebraic algorithm ignores the last three
    736        parameters.
     737      All of the above parameters are optional, with epsilon=0, bits and
     738      degree tested up to 1000 and 24 by default respectively. The
     739      numerical algorithm will be faster if bits and/or degree are given
     740      explicitly. The algebraic algorithm ignores the last three
     741      parameters.
    737742
    738743
    739744    OUTPUT: The minimal polynomial of self. If the numerical algorithm
     
    806811
    807812    The minpoly function is used implicitly when creating
    808813    number fields::
    809    
     814
    810815        sage: x = var('x')
    811816        sage: eqn =  x^3 + sqrt(2)*x + 5 == 0
    812817        sage: a = solve(eqn, x)[0].rhs()
     
    898903
    899904            for degree in degree_list:
    900905
    901                 f = QQ[var](algdep(a, degree)) # TODO: use the known_bits parameter?           
    902                 # If indeed we have found a minimal polynomial, 
    903                 # it should be accurate to a much higher precision. 
     906                f = QQ[var](algdep(a, degree)) # TODO: use the known_bits parameter?
     907                # If indeed we have found a minimal polynomial,
     908                # it should be accurate to a much higher precision.
    904909                error = abs(f(aa))
    905910                dx = ~RR(Integer(1) << (check_bits - degree - 2))
    906911                expected_error = abs(f.derivative()(CC(aa))) * dx
    907912
    908913                if error < expected_error:
    909                     # Degree might have been an over-estimate, factor because we want (irreducible) minpoly.
     914                    # Degree might have been an over-estimate,
     915                    # factor because we want (irreducible) minpoly.
    910916                    ff = f.factor()
    911917                    for g, e in ff:
    912918                        lead = g.leading_coefficient()
     
    930936    if algorithm is None or algorithm == 'algebraic':
    931937        from sage.rings.all import QQbar
    932938        return QQ[var](QQbar(ex).minpoly())
    933        
     939
    934940    raise ValueError, "Unknown algorithm: %s" % algorithm
    935941
    936942
     
    943949    from the given direction.
    944950
    945951    ::
    946    
     952
    947953       expr.limit(x = a)
    948954       expr.limit(x = a, dir='above')
    949955
    950956    INPUT:
    951957
    952     -  ``dir`` - (default: None); dir may have the value
    953        'plus' (or '+' or 'right') for a limit from above,
    954        'minus' (or '-' or 'left') for a limit from below, or may be omitted
    955        (implying a two-sided limit is to be computed).
     958    - ``dir`` - (default: None); dir may have the value
     959      'plus' (or '+' or 'right') for a limit from above,
     960      'minus' (or '-' or 'left') for a limit from below, or may be omitted
     961      (implying a two-sided limit is to be computed).
    956962
    957     -  ``taylor`` - (default: False); if True, use Taylor
    958        series, which allows more limits to be computed (but may also
    959        crash in some obscure cases due to bugs in Maxima).
     963    - ``taylor`` - (default: False); if True, use Taylor
     964      series, which allows more limits to be computed (but may also
     965      crash in some obscure cases due to bugs in Maxima).
    960966
    961     -  ``**argv`` - 1 named parameter
     967    - ``**argv`` - 1 named parameter
    962968
    963969    .. note::
    964970
     
    989995
    990996    Notice that Maxima may ask for more information::
    991997
    992         sage: var('a')   
     998        sage: var('a')
    993999        a
    9941000        sage: limit(x^a,x=0)
    9951001        Traceback (most recent call last):
    9961002        ...
    997         ValueError: Computation failed since Maxima requested additional constraints; using the 'assume' command before limit evaluation *may* help (see `assume?` for more details)
     1003        ValueError: Computation failed since Maxima requested additional
     1004        constraints; using the 'assume' command before limit evaluation
     1005        *may* help (see `assume?` for more details)
    9981006        Is  a  positive, negative, or zero?
    9991007
    10001008    With this example, Maxima is looking for a LOT of information::
     
    10031011        sage: limit(x^a,x=0)
    10041012        Traceback (most recent call last):
    10051013        ...
    1006         ValueError: Computation failed since Maxima requested additional constraints; using the 'assume' command before limit evaluation *may* help (see `assume?` for more details)
    1007         Is a an integer?
     1014        ValueError: Computation failed since Maxima requested additional
     1015        constraints; using the 'assume' command before limit evaluation
     1016        *may* help (see `assume?` for more details)
     1017        Is a an integer?
    10081018        sage: assume(a,'integer')
    10091019        sage: limit(x^a,x=0)
    10101020        Traceback (most recent call last):
    10111021        ...
    1012         ValueError: Computation failed since Maxima requested additional constraints; using the 'assume' command before limit evaluation *may* help (see `assume?` for more details)
     1022        ValueError: Computation failed since Maxima requested additional
     1023        constraints; using the 'assume' command before limit evaluation
     1024        *may* help (see `assume?` for more details)
    10131025        Is a an even number?
    10141026        sage: assume(a,'even')
    10151027        sage: limit(x^a,x=0)
     
    10591071
    10601072        sage: lim(x^2, x=2, dir='nugget')
    10611073        Traceback (most recent call last):
    1062         ...
    1063         ValueError: dir must be one of None, 'plus', '+', 'right', 'minus', '-', 'left'
     1074        ...
     1075        ValueError: dir must be one of None, 'plus', '+', 'right',
     1076        'minus', '-', 'left'
    10641077
    10651078    We check that Trac ticket 3718 is fixed, so that
    10661079    Maxima gives correct limits for the floor function::
     
    10931106    Check that Trac 8942 is fixed::
    10941107
    10951108        sage: f(x) = (cos(pi/4-x) - tan(x)) / (1 - sin(pi/4+x))
    1096         sage: limit(f(x), x = pi/4, dir='minus')           
     1109        sage: limit(f(x), x = pi/4, dir='minus')
    10971110        +Infinity
    1098         sage: limit(f(x), x = pi/4, dir='plus')           
     1111        sage: limit(f(x), x = pi/4, dir='plus')
    10991112        -Infinity
    1100         sage: limit(f(x), x = pi/4) 
     1113        sage: limit(f(x), x = pi/4)
    11011114        Infinity
    11021115
    11031116    Check that we give deprecation warnings for 'above' and 'below' #9200::
    11041117
    11051118        sage: limit(1/x, x=0, dir='above')
    1106         doctest:...: DeprecationWarning: (Since Sage version 4.6) the keyword 'above' is deprecated. Please use 'right' or '+' instead.
     1119        doctest:...: DeprecationWarning: (Since Sage version 4.6) the keyword
     1120        'above' is deprecated. Please use 'right' or '+' instead.
    11071121        +Infinity
    11081122        sage: limit(1/x, x=0, dir='below')
    1109         doctest:...: DeprecationWarning: (Since Sage version 4.6) the keyword 'below' is deprecated. Please use 'left' or '-' instead.
     1123        doctest:...: DeprecationWarning: (Since Sage version 4.6) the keyword
     1124        'below' is deprecated. Please use 'left' or '-' instead.
    11101125        -Infinity
    11111126    """
    11121127    if not isinstance(ex, Expression):
     
    11561171    #return l.sage()
    11571172    return ex.parent()(l)
    11581173
    1159 # lim is alias for limit 
     1174# lim is alias for limit
    11601175lim = limit
    11611176
    11621177###################################################################
     
    11721187    The function that is returned may be be viewed as a function of
    11731188    `s`.
    11741189
    1175     DEFINITION: The Laplace transform of a function `f(t)`,
     1190    DEFINITION:
     1191
     1192    The Laplace transform of a function `f(t)`,
    11761193    defined for all real numbers `t \geq 0`, is the function
    11771194    `F(s)` defined by
    11781195
    11791196    .. math::
    11801197
    1181                       F(s) = \int_{0}^{\infty} e^{-st} f(t) dt.         
     1198                      F(s) = \int_{0}^{\infty} e^{-st} f(t) dt.
    11821199
     1200    EXAMPLES:
    11831201
    1184 
    1185     EXAMPLES: We compute a few Laplace transforms::
     1202    We compute a few Laplace transforms::
    11861203
    11871204        sage: var('x, s, z, t, t0')
    11881205        (x, s, z, t, t0)
     
    11921209        z/s + 1/(s - 1)
    11931210        sage: log(t/t0).laplace(t, s)
    11941211        -(euler_gamma + log(s) - log(1/t0))/s
    1195          
     1212
    11961213    We do a formal calculation::
    11971214
    11981215        sage: f = function('f', x)
     
    12011218        sage: g.laplace(x, s)
    12021219        s*laplace(f(x), x, s) - f(0)
    12031220
    1204     EXAMPLE: A BATTLE BETWEEN the X-women and the Y-men (by David
     1221    EXAMPLES:
     1222
     1223    A BATTLE BETWEEN the X-women and the Y-men (by David
    12051224    Joyner): Solve
    12061225
    12071226    .. math::
    12081227
    1209                    x' = -16y, x(0)=270,  y' = -x + 1, y(0) = 90.         
    1210 
     1228                   x' = -16y, x(0)=270,  y' = -x + 1, y(0) = 90.
    12111229
    12121230    This models a fight between two sides, the "X-women" and the
    12131231    "Y-men", where the X-women have 270 initially and the Y-men have
     
    12281246        s*laplace(x(t), t, s) + 16*laplace(y(t), t, s) - x(0)
    12291247        sage: de2.laplace(t, s)
    12301248        s*laplace(y(t), t, s) - 1/s + laplace(x(t), t, s) - y(0)
    1231        
     1249
    12321250    Next we form the augmented matrix of the above system::
    12331251
    1234         sage: A = matrix([[s, 16, 270],[1, s, 90+1/s]])   
     1252        sage: A = matrix([[s, 16, 270],[1, s, 90+1/s]])
    12351253        sage: E = A.echelon_form()
    12361254        sage: xt = E[0,2].inverse_laplace(s,t)
    12371255        sage: yt = E[1,2].inverse_laplace(s,t)
     
    12471265
    12481266        sage: var('a,s,t')
    12491267        (a, s, t)
    1250         sage: f = exp (2*t + a) * sin(t) * t; f       
     1268        sage: f = exp (2*t + a) * sin(t) * t; f
    12511269        t*e^(a + 2*t)*sin(t)
    12521270        sage: L = laplace(f, t, s); L
    12531271        2*(s - 2)*e^a/(s^2 - 4*s + 5)^2
    12541272        sage: inverse_laplace(L, s, t)
    12551273        t*e^(a + 2*t)*sin(t)
    1256        
     1274
    12571275    Unable to compute solution::
    1258    
     1276
    12591277        sage: laplace(1/s, s, t)
    12601278        laplace(1/s, s, t)
    1261    
    12621279    """
    12631280    if not isinstance(ex, (Expression, Function)):
    12641281        ex = SR(ex)
     
    12791296
    12801297    .. math::
    12811298
    1282                       F(s) = \frac{1}{2\pi i} \int_{\gamma-i\infty}^{\gamma + i\infty} e^{st} F(s) dt,         
    1283 
     1299                      F(s) = \frac{1}{2\pi i} \int_{\gamma-i\infty}^{\gamma + i\infty} e^{st} F(s) dt,
    12841300
    12851301    where `\gamma` is chosen so that the contour path of
    12861302    integration is in the region of convergence of `F(s)`.
     
    13021318        t |--> t*cos(t)
    13031319        sage: inverse_laplace(1/(s^3+1), s, t)
    13041320        1/3*(sqrt(3)*sin(1/2*sqrt(3)*t) - cos(1/2*sqrt(3)*t))*e^(1/2*t) + 1/3*e^(-t)
    1305    
     1321
    13061322    No explicit inverse Laplace transform, so one is returned formally
    13071323    as a function ``ilt``::
    1308        
     1324
    13091325        sage: inverse_laplace(cos(s), s, t)
    13101326        ilt(cos(s), s, t)
    1311 
    13121327    """
    13131328    if not isinstance(ex, Expression):
    13141329        ex = SR(ex)
     
    13671382    Return comparison of the two variables x and y, which is just the
    13681383    comparison of the underlying string representations of the
    13691384    variables. This is used internally by the Calculus package.
    1370    
     1385
    13711386    INPUT:
    1372    
    1373     -  ``x, y`` - symbolic variables
    1374    
     1387
     1388    - ``x, y`` - symbolic variables
     1389
    13751390    OUTPUT: Python integer; either -1, 0, or 1.
    1376    
     1391
    13771392    EXAMPLES::
    1378    
     1393
    13791394        sage: sage.calculus.calculus.var_cmp(x,x)
    13801395        0
    13811396        sage: sage.calculus.calculus.var_cmp(x,var('z'))
     
    13891404    """
    13901405    This function is called to create formal wrappers of limits that
    13911406    Maxima can't compute:
    1392    
     1407
    13931408    EXAMPLES::
    1394    
     1409
    13951410        sage: a = lim(exp(x^2)*(1-erf(x)), x=infinity); a
    13961411        limit(-e^(x^2)*erf(x) + e^(x^2), x, +Infinity)
    1397         sage: a = sage.calculus.calculus.dummy_limit(sin(x)/x, x, 0);a 
     1412        sage: a = sage.calculus.calculus.dummy_limit(sin(x)/x, x, 0);a
    13981413        limit(sin(x)/x, x, 0)
    13991414    """
    14001415    return _limit(args[0], var(repr(args[1])), SR(args[2]))
     
    14221437    for i in range(1, len(args), 2):
    14231438        args[i] = Integer(args[i])
    14241439    return f.diff(*args)
    1425  
     1440
    14261441def dummy_integrate(*args):
    14271442    """
    14281443    This function is called to create formal wrappers of integrals that
    14291444    Maxima can't compute:
    1430    
     1445
    14311446    EXAMPLES::
    1432    
     1447
    14331448        sage: from sage.calculus.calculus import dummy_integrate
    14341449        sage: f(x) = function('f',x)
    14351450        sage: dummy_integrate(f(x), x)
     
    14371452        sage: a,b = var('a,b')
    14381453        sage: dummy_integrate(f(x), x, a, b)
    14391454        integrate(f(x), x, a, b)
    1440 
    14411455    """
    14421456    if len(args) == 4:
    14431457        return definite_integral(*args, hold=True)
     
    14481462    """
    14491463    This function is called to create formal wrappers of laplace transforms
    14501464    that Maxima can't compute:
    1451    
     1465
    14521466    EXAMPLES::
    1453    
     1467
    14541468        sage: from sage.calculus.calculus import dummy_laplace
    14551469        sage: s,t = var('s,t')
    14561470        sage: f(t) = function('f',t)
     
    14631477    """
    14641478    This function is called to create formal wrappers of inverse laplace
    14651479    transforms that Maxima can't compute:
    1466    
     1480
    14671481    EXAMPLES::
    1468    
     1482
    14691483        sage: from sage.calculus.calculus import dummy_inverse_laplace
    14701484        sage: s,t = var('s,t')
    14711485        sage: F(s) = function('F',s)
     
    14761490
    14771491#######################################################
    14781492#
    1479 # Helper functions for printing latex expression 
     1493# Helper functions for printing latex expression
    14801494#
    14811495#######################################################
    14821496
    14831497def _limit_latex_(self, f, x, a):
    14841498    r"""
    14851499    Return latex expression for limit of a symbolic function.
    1486    
     1500
    14871501    EXAMPLES::
    1488    
     1502
    14891503        sage: from sage.calculus.calculus import _limit_latex_
    14901504        sage: var('x,a')
    14911505        (x, a)
     
    14941508        '\\lim_{x \\to a}\\, f\\left(x\\right)'
    14951509        sage: latex(limit(f, x=oo))
    14961510        \lim_{x \to +\infty}\, f\left(x\right)
    1497    
     1511
    14981512    """
    14991513    return "\\lim_{%s \\to %s}\\, %s"%(latex(x), latex(a), latex(f))
    15001514
    15011515def _laplace_latex_(self, *args):
    15021516    r"""
    15031517    Return LaTeX expression for Laplace transform of a symbolic function.
    1504    
     1518
    15051519    EXAMPLES::
    1506    
     1520
    15071521        sage: from sage.calculus.calculus import _laplace_latex_
    15081522        sage: var('s,t')
    15091523        (s, t)
     
    15121526        '\\mathcal{L}\\left(f\\left(t\\right), t, s\\right)'
    15131527        sage: latex(laplace(f, t, s))
    15141528        \mathcal{L}\left(f\left(t\right), t, s\right)
    1515    
     1529
    15161530    """
    15171531    return "\\mathcal{L}\\left(%s\\right)"%(', '.join([latex(x) for x in args]))
    15181532
    15191533def _inverse_laplace_latex_(self, *args):
    15201534    r"""
    1521     Return LaTeX expression for inverse Laplace transform of a symbolic function.
    1522    
     1535    Return LaTeX expression for inverse Laplace transform
     1536    of a symbolic function.
     1537
    15231538    EXAMPLES::
    1524    
     1539
    15251540        sage: from sage.calculus.calculus import _inverse_laplace_latex_
    15261541        sage: var('s,t')
    15271542        (s, t)
     
    15301545        '\\mathcal{L}^{-1}\\left(F\\left(s\\right), s, t\\right)'
    15311546        sage: latex(inverse_laplace(F,s,t))
    15321547        \mathcal{L}^{-1}\left(F\left(s\right), s, t\right)
    1533    
    15341548    """
    15351549    return "\\mathcal{L}^{-1}\\left(%s\\right)"%(', '.join([latex(x) for x in args]))
    15361550
     
    15681582    """
    15691583    Given a string representation of a Maxima expression, parse it and
    15701584    return the corresponding Sage symbolic expression.
    1571    
     1585
    15721586    INPUT:
    1573    
    1574     -  ``x`` - a string
    1575    
    1576     -  ``equals_sub`` - (default: False) if True, replace
    1577        '=' by '==' in self
    1578    
    1579     -  ``maxima`` - (default: the calculus package's
    1580        Maxima) the Maxima interpreter to use.
    1581    
    1582    
     1587
     1588    - ``x`` - a string
     1589
     1590    - ``equals_sub`` - (default: False) if True, replace
     1591      '=' by '==' in self
     1592
     1593    - ``maxima`` - (default: the calculus package's
     1594      Maxima) the Maxima interpreter to use.
     1595
    15831596    EXAMPLES::
    1584    
     1597
    15851598        sage: from sage.calculus.calculus import symbolic_expression_from_maxima_string as sefms
    15861599        sage: sefms('x^%e + %e^%pi + %i + sin(0)')
    15871600        x^e + e^pi + I
     
    15941607        x != 0
    15951608
    15961609    TESTS:
    1597    
     1610
    15981611    Trac #8459 fixed::
    15991612
    16001613        sage: maxima('3*li[2](u)+8*li[33](exp(u))').sage()
    16011614        3*polylog(2, u) + 8*polylog(33, e^u)
    1602            
    16031615    """
    16041616    syms = sage.symbolic.pynac.symbol_table.get('maxima', {}).copy()
    16051617
     
    16091621
    16101622    # This is inefficient since it so rarely is needed:
    16111623    #r = maxima._eval_line('listofvars(_tmp_);')[1:-1]
    1612    
     1624
    16131625    s = maxima._eval_line('_tmp_;')
    1614    
     1626
    16151627    formal_functions = maxima_tick.findall(s)
    16161628    if len(formal_functions) > 0:
    16171629        for X in formal_functions:
     
    16191631        # You might think there is a potential very subtle bug if 'foo
    16201632        # is in a string literal -- but string literals should *never*
    16211633        # ever be part of a symbolic expression.
    1622         s = s.replace("'","") 
     1634        s = s.replace("'","")
    16231635
    16241636    delayed_functions = maxima_qp.findall(s)
    16251637    if len(delayed_functions) > 0:
     
    16301642                syms[X[2:]] = function_factory(X[2:])
    16311643        s = s.replace("?%","")
    16321644
    1633     s = polylog_ex.sub('polylog(\\1,',s) 
     1645    s = polylog_ex.sub('polylog(\\1,',s)
    16341646    s = multiple_replace(symtable, s)
    16351647    s = s.replace("%","")
    16361648
    16371649    s = s.replace("#","!=") # a lot of this code should be refactored somewhere...
    16381650
    16391651    s = maxima_polygamma.sub('psi(\g<1>,',s) # this replaces psi[n](foo) with psi(n,foo), ensuring that derivatives of the digamma function are parsed properly below
    1640    
     1652
    16411653    if equals_sub:
    16421654        s = s.replace('=','==')
    16431655
     
    16601672        r = create_RealNumber(s[start:end]).str(no_sci=2, truncate=True)
    16611673        s = s.replace(s[start:end], r)
    16621674        search = sci_not.search(s)
    1663      
     1675
    16641676    # have to do this here, otherwise maxima_tick catches it
    16651677    syms['limit'] = dummy_limit
    16661678    syms['diff'] = dummy_diff
     
    16871699    """
    16881700    Used internally when creating a string of options to pass to
    16891701    Maxima.
    1690    
     1702
    16911703    INPUT:
    1692    
    1693     -  ``v`` - an object
    1694    
     1704
     1705    - ``v`` - an object
     1706
    16951707    OUTPUT: a string.
    1696    
     1708
    16971709    The main use of this is to turn Python bools into lower case
    16981710    strings.
    1699    
     1711
    17001712    EXAMPLES::
    1701    
     1713
    17021714        sage: sage.calculus.calculus.mapped_opts(True)
    17031715        'true'
    17041716        sage: sage.calculus.calculus.mapped_opts(False)
     
    17131725def maxima_options(**kwds):
    17141726    """
    17151727    Used internally to create a string of options to pass to Maxima.
    1716    
     1728
    17171729    EXAMPLES::
    1718    
     1730
    17191731        sage: sage.calculus.calculus.maxima_options(an_option=True, another=False, foo='bar')
    17201732        'an_option=true,foo=bar,another=false'
    17211733    """
     
    17361748syms_default = dict(syms_cur)
    17371749
    17381750# This dictionary is used to pass a lookup table other than the system registry
    1739 # to the parser. A global variable is necessary since the parser calls the 
     1751# to the parser. A global variable is necessary since the parser calls the
    17401752# _find_var() and _find_func() functions below without extra arguments.
    17411753_augmented_syms = {}
    17421754
     
    17441756
    17451757def _find_var(name):
    17461758    """
    1747     Function to pass to Parser for constructing 
     1759    Function to pass to Parser for constructing
    17481760    variables from strings.  For internal use.
    17491761
    17501762    EXAMPLES::
    1751    
     1763
    17521764        sage: y = var('y')
    17531765        sage: sage.calculus.calculus._find_var('y')
    17541766        y
     
    17721784        return SR(sage.all.__dict__[name])
    17731785    except (KeyError, TypeError):
    17741786        return var(name)
    1775        
     1787
    17761788def _find_func(name, create_when_missing = True):
    17771789    """
    1778     Function to pass to Parser for constructing 
     1790    Function to pass to Parser for constructing
    17791791    functions from strings.  For internal use.
    17801792
    17811793    EXAMPLES::
    1782    
     1794
    17831795        sage: sage.calculus.calculus._find_func('limit')
    17841796        limit
    17851797        sage: sage.calculus.calculus._find_func('zeta_zeros')
     
    18141826                   make_float    = lambda x: SR(RealDoubleElement(x)),
    18151827                   make_var      = _find_var,
    18161828                   make_function = _find_func)
    1817                    
     1829
    18181830def symbolic_expression_from_string(s, syms=None, accept_sequence=False):
    18191831    """
    1820     Given a string, (attempt to) parse it and return the 
     1832    Given a string, (attempt to) parse it and return the
    18211833    corresponding Sage symbolic expression.  Normally used
    18221834    to return Maxima output to the user.
    1823    
     1835
    18241836    INPUT:
    1825    
    1826     -  ``s`` - a string
    1827    
    1828     -  ``syms`` - (default: None) dictionary of
    1829        strings to be regarded as symbols or functions
    18301837
    1831     -  ``accept_sequence`` - (default: False) controls whether
    1832        to allow a (possibly nested) set of lists and tuples
    1833        as input
    1834    
     1838    - ``s`` - a string
     1839
     1840    - ``syms`` - (default: None) dictionary of
     1841      strings to be regarded as symbols or functions
     1842
     1843    - ``accept_sequence`` - (default: False) controls whether
     1844      to allow a (possibly nested) set of lists and tuples
     1845      as input
     1846
    18351847    EXAMPLES::
    1836    
     1848
    18371849        sage: y = var('y')
    18381850        sage: sage.calculus.calculus.symbolic_expression_from_string('[sin(0)*x^2,3*spam+e^pi]',syms={'spam':y},accept_sequence=True)
    18391851        [0, 3*y + e^pi]
  • sage/calculus/functional.py

    diff -r 1bd1f40c456f -r 88910e6cc47b sage/calculus/functional.py
    a b  
    203203        sage: (x,y) = (t^4,t)
    204204        sage: (dx,dy) = (diff(x,t), diff(y,t))
    205205        sage: integral(sin(x)*dx, t,-1, 1)
    206         0   
     206        0
    207207        sage: restore('x,y')   # restore the symbolic variables x and y
    208208   
    209209    Sage is unable to do anything with the following integral::
     
    242242        sage: integral(abs(x)*x, x, 0, a)
    243243        Traceback (most recent call last):
    244244        ...
    245         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)
     245        ValueError: Computation failed since Maxima requested additional
     246        constraints; using the 'assume' command before integral evaluation
     247        *may* help (example of legal syntax is 'assume(a>0)',
     248        see `assume?` for more details)
    246249        Is  a  positive, negative, or zero?
    247250        sage: assume(a>0)
    248251        sage: integral(abs(x)*x, x, 0, a)
     
    266269         -6.9388939039072284e-17]
    267270        sage: h.factor()
    268271        0
    269         sage: bool(h == 0) 
     272        sage: bool(h == 0)
    270273        True
    271274    """
    272275    try:
     
    293296   
    294297    INPUT:
    295298   
    296    
    297     -  ``dir`` - (default: None); dir may have the value
     299    - ``dir`` - (default: None); dir may have the value
    298300       'plus' (or 'above') for a limit from above, 'minus' (or 'below')
    299301       for a limit from below, or may be omitted (implying a two-sided
    300302       limit is to be computed).
    301303   
    302     -  ``taylor`` - (default: False); if True, use Taylor
     304    - ``taylor`` - (default: False); if True, use Taylor
    303305       series, which allows more limits to be computed (but may also
    304306       crash in some obscure cases due to bugs in Maxima).
    305307   
    306     -  ``\*\*argv`` - 1 named parameter
    307    
     308    - ``\*\*argv`` - 1 named parameter
    308309   
    309310    ALIAS: You can also use lim instead of limit.
    310311   
     
    316317        +Infinity
    317318        sage: lim(exp(x), x=-oo)
    318319        0
    319         sage: lim(1/x, x=0) 
     320        sage: lim(1/x, x=0)
    320321        Infinity
    321322        sage: limit(sqrt(x^2+x+1)+x, taylor=True, x=-oo)
    322323        -1/2
     
    341342    variable `v` around the point `a`, containing terms
    342343    through `(x - a)^n`. Functions in more variables are also
    343344    supported.
    344      
     345   
    345346    INPUT:
    346      
    347     -  ``*args`` - the following notation is supported
    348          
    349        - ``x, a, n`` - variable, point, degree
    350        
    351        - ``(x, a), (y, b), ..., n`` - variables with points, degree of polynomial
    352      
     347   
     348    - ``*args`` - the following notation is supported
     349   
     350    - ``x, a, n`` - variable, point, degree
     351   
     352    - ``(x, a), (y, b), ..., n`` - variables with points, degree of polynomial
     353   
    353354    EXAMPLES::
    354355   
    355356        sage: var('x,k,n')
     
    366367
    367368        sage: taylor ((x + 1)^n, x, 0, 4)
    368369        1/24*(n^4 - 6*n^3 + 11*n^2 - 6*n)*x^4 + 1/6*(n^3 - 3*n^2 + 2*n)*x^3 + 1/2*(n^2 - n)*x^2 + n*x + 1
    369                  
    370     Taylor polynomial in two variables:: 
     370       
     371    Taylor polynomial in two variables::
    371372
    372         sage: x,y=var('x y'); taylor(x*y^3,(x,1),(y,-1),4) 
     373        sage: x,y=var('x y'); taylor(x*y^3,(x,1),(y,-1),4)
    373374        (y + 1)^3*(x - 1) + (y + 1)^3 - 3*(y + 1)^2*(x - 1) - 3*(y + 1)^2 + 3*(y + 1)*(x - 1) - x + 3*y + 3
    374375    """
    375376    if not isinstance(f, Expression):
     
    425426        0.28867513459481287
    426427        sage: float(expand(t1 + t2))
    427428        -0.288675134594812...
    428         sage: float(expand(tt1 + t2))       
     429        sage: float(expand(tt1 + t2))
    429430        -0.288675134594812...
    430431    """
    431432    try:
    432433        return x.expand(*args, **kwds)
    433434    except AttributeError:
    434435        return x
    435 
  • sage/interfaces/interface.py

    diff -r 1bd1f40c456f -r 88910e6cc47b sage/interfaces/interface.py
    a b  
    1717- Simon King (2010-09-25): Expect._local_tmpfile() depends on
    1818  Expect.pid() and is cached; Expect.quit() clears that cache,
    1919  which is important for forking.
     20
     21- Jean-Pierre Flori (2010,2011): Split non Pexpect stuff into a parent class.
    2022"""
    2123
    2224#*****************************************************************************
  • sage/interfaces/maxima.py

    diff -r 1bd1f40c456f -r 88910e6cc47b sage/interfaces/maxima.py
    a b  
    11r"""
    2 Interface to Maxima
     2Pexpect interface to Maxima
    33
    44Maxima is a free GPL'd general purpose computer algebra system
    55whose development started in 1968 at MIT. It contains symbolic
     
    2626- William Stein (2006-02-24): *greatly* improved robustness by adding
    2727  sequence numbers to IO bracketing in _eval_line
    2828
     29- Robert Bradshaw, Nils Bruin, Jean-Pierre Flori (2010,2011): Binary library
     30  interface
     31
     32This is the interface used by the maxima object::
     33
     34    sage: type(maxima)
     35    <class 'sage.interfaces.maxima.Maxima'>
     36
    2937If the string "error" (case insensitive) occurs in the output of
    3038anything from Maxima, a RuntimeError exception is raised.
    3139
     
    119127::
    120128
    121129    sage: a = maxima('(1 + sqrt(2))^5')
    122     sage: float(a)               
     130    sage: float(a)
    123131    82.012193308819747
    124132    sage: a.numer()
    125133    82.01219330881975
     
    460468##import sage.rings.all
    461469import sage.rings.complex_number
    462470
    463 from expect import Expect, ExpectElement, FunctionElement, ExpectFunction, gc_disabled, AsciiArtString
     471from expect import (Expect, ExpectElement, FunctionElement,
     472                    ExpectFunction, gc_disabled, AsciiArtString)
    464473
    465 from maxima_abstract import MaximaAbstract, MaximaAbstractFunction, MaximaAbstractElement, MaximaAbstractFunctionElement, MaximaAbstractElementFunction
     474from maxima_abstract import (MaximaAbstract, MaximaAbstractFunction,
     475                             MaximaAbstractElement,
     476                             MaximaAbstractFunctionElement,
     477                             MaximaAbstractElementFunction)
    466478
    467 # Thanks to the MRO for multiple inheritance used by the Sage's Python , this should work as expected
     479# Thanks to the MRO for multiple inheritance used by the Sage's Python,
     480# this should work as expected
    468481class Maxima(MaximaAbstract, Expect):
    469482    """
    470483    Interface to the Maxima interpreter.
     484
     485    EXAMPLES::
     486
     487        sage: m = Maxima()
     488        sage: m == maxima
     489        False
    471490    """
    472491    def __init__(self, script_subdirectory=None, logfile=None, server=None,
    473492                 init_code = None):
     
    476495
    477496        TESTS::
    478497       
     498            sage: Maxima == loads(dumps(Maxima))
     499            True
    479500            sage: maxima == loads(dumps(maxima))
    480501            True
    481502
     503        Unpickling a Maxima Pexpect interface gives the default interface::
     504
     505            sage: m = Maxima()
     506            sage: maxima == loads(dumps(m))
     507            True
     508
    482509        We make sure labels are turned off (see trac 6816)::
    483510       
    484511            sage: 'nolabels : true' in maxima._Expect__init_code
     
    501528       
    502529        if not os.path.exists(STARTUP):
    503530            raise RuntimeError, 'You must get the file local/bin/sage-maxima.lisp'
     531
     532        #self.__init_code = init_code
    504533        if init_code is None:
    505534            # display2d -- no ascii art output
    506535            # keepfloat -- don't automatically convert floats to rationals
    507536            init_code = ['display2d : false', 'keepfloat : true']
    508            
     537       
    509538        # Turn off the prompt labels, since computing them *very
    510539        # dramatically* slows down the maxima interpret after a while.
    511540        # See the function makelabel in suprv1.lisp.
    512541        # Many thanks to andrej.vodopivec@gmail.com and also
    513542        # Robert Dodier for figuring this out!
    514         # See trac # 6818. 
     543        # See trac # 6818.
    515544        init_code.append('nolabels : true')
    516                
     545       
    517546        MaximaAbstract.__init__(self,"maxima")
    518547        Expect.__init__(self,
    519548                        name = 'maxima',
    520549                        prompt = '\(\%i[0-9]+\)',
    521550                        command = 'maxima-noreadline --userdir="%s" -p "%s"'%(SAGE_MAXIMA_DIR,STARTUP),
    522                         maxread = 10000, 
     551                        maxread = 10000,
    523552                        script_subdirectory = script_subdirectory,
    524553                        restart_on_ctrlc = False,
    525554                        verbose_start = False,
     
    561590        self._sendline(r":lisp (defun tex-derivative (x l r) (tex (if $derivabbrev (tex-dabbrev x) (tex-d x '\\partial)) l r lop rop ))")
    562591
    563592        # Remove limit on the max heapsize (since otherwise it defaults
    564         # to 256MB with ECL). 
     593        # to 256MB with ECL).
    565594        self._sendline(":lisp (ext:set-limit 'ext:heap-size 0)")
    566595        self._eval_line('0;')
    567596
    568597    def __reduce__(self):
    569598        """
     599        Implementation of __reduce__ for ``Maxima``.
     600
    570601        EXAMPLES::
    571602       
    572603            sage: maxima.__reduce__()
    573604            (<function reduce_load_Maxima at 0x...>, ())
    574605        """
    575         return reduce_load_Maxima, tuple([])
     606        return reduce_load_Maxima, tuple([]) #(self.__init_code,)
    576607
    577608    def _sendline(self, str):
     609        """
     610        Send a string followed by a newline character.
     611
     612        EXAMPLES::
     613
     614            sage: maxima._sendline('t : 9;')
     615            sage: maxima.get('t')
     616            '9'
     617        """
    578618        self._sendstr(str)
    579619        os.write(self._expect.child_fd, os.linesep)
    580620
     
    582622        """
    583623        Wait for a given expression expr (which could be a regular
    584624        expression or list of regular expressions) to appear in the output
    585         for at most timeout seconds. 
     625        for at most timeout seconds.
    586626
    587627        See `sage.interfaces.expect.Expect._expect_expr` for full details
    588628        on its use and functionality.
     
    597637            sage: maxima('integrate(1/(x^3*(a+b*x)^(1/3)),x)')
    598638            Traceback (most recent call last):
    599639            ...
    600             TypeError: Computation failed since Maxima requested additional constraints (try the command "maxima.assume('a>0')" before integral or limit evaluation, for example):
     640            TypeError: Computation failed since Maxima requested additional
     641            constraints (try the command "maxima.assume('a>0')"
     642            before integral or limit evaluation, for example):
    601643            Is  a  positive or negative?
    602644            sage: maxima.assume('a>0')
    603645            [a>0]
     
    606648            sage: maxima('integrate(x^n,x)')
    607649            Traceback (most recent call last):
    608650            ...
    609             TypeError: Computation failed since Maxima requested additional constraints (try the command "maxima.assume('n+1>0')" before integral or limit evaluation, for example):
     651            TypeError: Computation failed since Maxima requested additional
     652            constraints (try the command "maxima.assume('n+1>0')" before
     653            integral or limit evaluation, for example):
    610654            Is  n+1  zero or nonzero?
    611655            sage: maxima.assume('n+1>0')
    612656            [n>-1]
     
    616660            [[a>0,n>-1]]
    617661            sage: maxima.facts()
    618662            []
    619             sage: var('a')   
     663            sage: var('a')
    620664            a
    621665            sage: maxima('limit(x^a,x,0)')
    622666            Traceback (most recent call last):
    623667            ...
    624             TypeError: Computation failed since Maxima requested additional constraints (try the command "maxima.assume('a>0')" before integral or limit evaluation, for example):
     668            TypeError: Computation failed since Maxima requested additional
     669            constraints (try the command "maxima.assume('a>0')" before
     670            integral or limit evaluation, for example):
    625671            Is  a  positive, negative, or zero?
    626672        """
    627673        if expr is None:
     
    671717    def _eval_line(self, line, allow_use_file=False,
    672718                   wait_for_prompt=True, reformat=True, error_check=True):
    673719        """
     720        Return result of line evaluation.
     721
    674722        EXAMPLES:
    675723       
    676724        We check that errors are correctly checked::
     
    693741        self._synchronize()
    694742
    695743        if len(line) > self.__eval_using_file_cutoff:
    696             # This implicitly uses the set method, then displays the result of the thing that was set.
    697             # This only works when the input line is an expression.   But this is our only choice, since
    698             # batchmode doesn't display expressions to screen.   
     744            # This implicitly uses the set method, then displays
     745            # the result of the thing that was set.
     746            # This only works when the input line is an expression.
     747            # But this is our only choice, since
     748            # batchmode doesn't display expressions to screen.
    699749            a = self(line)
    700750            return repr(a)
    701751        else:
     
    706756            return
    707757        assert line_echo.strip() == line.strip()
    708758
    709         # This broke in maxima-5.22.1 as discussed in http://trac.sagemath.org/sage_trac/ticket/10187
     759        # This broke in maxima-5.22.1 as discussed in
     760        # http://trac.sagemath.org/sage_trac/ticket/10187
    710761        #self._expect_expr(self._display_prompt)
    711762        #pre_out = self._before()
    712763        #self._expect_expr()
     
    731782        # i = o.rfind('(%o')
    732783        # return o[:i]
    733784
    734         self._expect_expr(self._display_prompt)   
     785        self._expect_expr(self._display_prompt)
    735786        out = self._before()        # input echo + output prompt + output
    736787        if error_check:
    737788            self._error_check(line, out)
     
    778829        r = randrange(2147483647)
    779830        s = marker + str(r+1)
    780831
    781         # The 0; *is* necessary... it comes up in certain rare cases
    782         # that are revealed by extensive testing.  Don't delete it. -- william stein
     832        # The 0; *is* necessary... it comes up in certain rare cases
     833        # that are revealed by extensive testing.
     834        # Don't delete it. -- william stein
    783835        cmd = '''0;sconcat("%s",(%s+1));\n'''%(marker,r)
    784836        self._sendstr(cmd)
    785837        try:
     
    794846            self.quit()
    795847
    796848    def _batch(self, s, batchload=True):
     849        """
     850        Call Maxima's batch or batchload command with a file
     851        containing the given string as argument.
     852
     853        EXAMPLES::
     854
     855            sage: maxima._batch('10003;')
     856            '...batchload...'
     857            sage: maxima._batch('10003;',batchload=False)
     858            '...batch...10003...'
     859        """
    797860        filename = '%s-%s'%(self._local_tmpfile(),randrange(2147483647))
    798861        F = open(filename, 'w')
    799862        F.write(s)
     
    815878        self._sendline(cmd)
    816879        self._expect_expr(s)
    817880        out = self._before()
    818         self._error_check(str, out)
     881        self._error_check(cmd, out)
    819882        os.unlink(filename)
    820883        return out
    821884
    822885    def _quit_string(self):
    823886        """
     887        Return string representation of quit command.
     888       
    824889        EXAMPLES::
    825890       
    826891            sage: maxima._quit_string()
     
    830895
    831896    def _crash_msg(self):
    832897        """
     898        Return string representation of crash message.
     899
    833900        EXAMPLES::
    834901       
    835902            sage: maxima._crash_msg()
     
    837904        """
    838905        print "Maxima crashed -- automatically restarting."
    839906
    840     def _error_check(self, str, out):
     907    def _error_check(self, cmd, out):
     908        """
     909        Check string for errors.
     910
     911        EXAMPLES::
     912       
     913            sage: maxima._error_check("1+1;","Principal Value")
     914            Traceback (most recent call last):
     915            ...
     916            TypeError: Error executing code in Maxima
     917            CODE:
     918                1+1;
     919            Maxima ERROR:
     920                Principal Value
     921        """
    841922        r = self._error_re
    842923        m = r.search(out)
    843924        if not m is None:
    844             self._error_msg(str, out)
    845            
    846     def _error_msg(self, str, out):
    847         raise TypeError, "Error executing code in Maxima\nCODE:\n\t%s\nMaxima ERROR:\n\t%s"%(str, out.replace('-- an error.  To debug this try debugmode(true);',''))
     925            self._error_msg(cmd, out)
     926
     927    def _error_msg(self, cmd, out):
     928        """
     929        Raise error with formatted description.
     930
     931        EXAMPLES::
     932
     933            sage: maxima._error_msg("1+1;","Principal Value")
     934            Traceback (most recent call last):
     935            ...
     936            TypeError: Error executing code in Maxima
     937            CODE:
     938                1+1;
     939            Maxima ERROR:
     940                Principal Value
     941        """
     942        raise TypeError, "Error executing code in Maxima\nCODE:\n\t%s\nMaxima ERROR:\n\t%s"%(cmd, out.replace('-- an error.  To debug this try debugmode(true);',''))
    848943
    849944    ###########################################
    850     # Direct access to underlying lisp interpreter. 
     945    # Direct access to underlying lisp interpreter.
    851946    ###########################################
    852947    def lisp(self, cmd):
    853948        """
    854         Send a lisp command to maxima.
     949        Send a lisp command to Maxima.
    855950       
    856951        .. note::
    857952
     
    864959            19
    865960            (
    866961        """
    867         self._eval_line(':lisp %s\n""'%cmd, allow_use_file=False, wait_for_prompt=False, reformat=False, error_check=False)
     962        self._eval_line(':lisp %s\n""'%cmd, allow_use_file=False,
     963               wait_for_prompt=False, reformat=False, error_check=False)
    868964        self._expect_expr('(%i)')
    869965        return self._before()
    870966
     
    878974       
    879975        INPUT:
    880976       
     977        - ``var`` - string
    881978       
    882         -  ``var`` - string
    883        
    884         -  ``value`` - string
    885        
     979        - ``value`` - string
    886980       
    887981        EXAMPLES::
    888982       
     
    9351029
    9361030    def _function_class(self):
    9371031        """
     1032        Return the Python class of Maxima functions.
     1033
    9381034        EXAMPLES::
    9391035       
    9401036            sage: maxima._function_class()
     
    9541050        return MaximaElement
    9551051
    9561052    def _function_element_class(self):
    957         """     
     1053        """
     1054        Return the Python class of Maxima functions of elements.
     1055
    9581056        EXAMPLES::
    9591057       
    9601058            sage: maxima._function_element_class()
     
    9641062
    9651063    def _object_function_class(self):
    9661064        """
     1065        Return the Python class of Maxima user-defined functions.
     1066
    9671067        EXAMPLES::
    9681068       
    9691069            sage: maxima._object_function_class()
     
    9711071        """
    9721072        return MaximaElementFunction
    9731073
    974     ##some old helper functions to wrap the calculus use of the maxima interface.
    975     ##these routines expect arguments living in the symbolic ring and return something
    976     ##that is hopefully coercible into the symbolic ring again.
     1074    ## some old helper functions to wrap the calculus use
     1075    ## of the Maxima interface. these routines expect arguments
     1076    ## living in the symbolic ring and return something
     1077    ## that is hopefully coercible into the symbolic ring again.
    9771078##
    9781079##    def sr_integral(self,*args):
    9791080##        return args[0]._maxima_().integrate(*args[1:])
     
    10061107    """
    10071108    return isinstance(x, MaximaElement)
    10081109
    1009 # Thanks to the MRO for multiple inheritance used by the Sage's Python , this should work as expected
     1110# Thanks to the MRO for multiple inheritance used by the Sage's Python,
     1111# this should work as expected
    10101112class MaximaElement(MaximaAbstractElement, ExpectElement):
     1113    """
     1114    Element of Maxima through Pexpect interface.
     1115
     1116    EXAMPLES:
     1117
     1118    Elements of this class should not be created directly.
     1119    The targeted parent should be used instead::
     1120
     1121        sage: maxima(3)
     1122        3
     1123        sage: maxima(cos(x)+e^234)
     1124        cos(x)+%e^234
     1125    """
     1126
    10111127    def __init__(self, parent, value, is_name=False, name=None):
     1128        """
     1129        Create a Maxima element.
     1130        See ``MaximaElement`` for full documentation.
     1131
     1132        EXAMPLES::
     1133
     1134           sage: maxima(zeta(7))
     1135           zeta(7)
     1136
     1137        TESTS::
     1138
     1139            sage: from sage.interfaces.maxima import MaximaElement
     1140            sage: loads(dumps(MaximaElement))==MaximaElement
     1141            True
     1142            sage: a = maxima(5)
     1143            sage: type(a)
     1144            <class 'sage.interfaces.maxima.MaximaElement'>
     1145            sage: loads(dumps(a))==a
     1146            True
     1147        """
    10121148        ExpectElement.__init__(self, parent, value, is_name=False, name=None)
    10131149
    10141150    def display2d(self, onscreen=True):
    10151151        """
     1152        Return the 2d string representation of this Maxima object.
     1153
    10161154        EXAMPLES::
    10171155       
    1018             sage: F = maxima('x^5 - y^5').factor() 
    1019             sage: F.display2d ()             
     1156            sage: F = maxima('x^5 - y^5').factor()
     1157            sage: F.display2d()
    10201158                                   4      3    2  2    3      4
    10211159                       - (y - x) (y  + x y  + x  y  + x  y + x )
    10221160        """
     
    10261164            P._eval_line('display2d : true$')
    10271165            s = P._eval_line('disp(%s)$'%self.name(), reformat=False)
    10281166            P._eval_line('display2d : false$')
    1029            
    10301167        s = s.strip('\r\n')
    10311168
    10321169        # if ever want to dedent, see
     
    10371174            return s
    10381175
    10391176
    1040 # Thanks to the MRO for multiple inheritance used by the Sage's Python , this should work as expected
     1177# Thanks to the MRO for multiple inheritance used by the Sage's Python,
     1178# this should work as expected
    10411179class MaximaFunctionElement(MaximaAbstractFunctionElement, FunctionElement):
    10421180    pass
    10431181#    def __init__(self, obj, name):
     
    10451183#        FunctionElement.__init__(self, obj, name)
    10461184
    10471185
    1048 # Thanks to the MRO for multiple inheritance used by the Sage's Python , this should work as expected
     1186# Thanks to the MRO for multiple inheritance used by the Sage's Python,
     1187# this should work as expected
    10491188class MaximaFunction(MaximaAbstractFunction, ExpectFunction):
    10501189    pass
    10511190#    def __init__(self, parent, name):
     
    10531192#        ExpectFunction.__init__(self, parent, name)
    10541193
    10551194
    1056 # Thanks to the MRO for multiple inheritance used by the Sage's Python , this should work as expected
     1195# Thanks to the MRO for multiple inheritance used by the Sage's Python,
     1196# this should work as expected
    10571197class MaximaElementFunction(MaximaElement, MaximaAbstractElementFunction):
     1198    """
     1199    Maxima user-defined functions.
     1200
     1201    EXAMPLES:
     1202
     1203    Elements of this class should not be created directly.
     1204    The method ``function`` of the targeted parent should be used instead::
     1205
     1206        sage: maxima.function('x,y','h(x)*y')
     1207        h(x)*y
     1208    """
     1209
    10581210    def __init__(self, parent, name, defn, args, latex):
     1211        """
     1212        Create a Maxima function.
     1213        See ``MaximaElementFunction`` for full documentation.
     1214
     1215        EXAMPLES::
     1216       
     1217            sage: maxima.function('x,y','cos(x)+y')
     1218            cos(x)+y
     1219
     1220        TESTS::
     1221
     1222            sage: f = maxima.function('x,y','x+y^9')
     1223            sage: f == loads(dumps(f))
     1224            True
     1225
     1226        Unpickling a Maxima Pexpect interface gives the default interface::
     1227
     1228            sage: m = Maxima()
     1229            sage: g = m.function('x,y','x+y^9')
     1230            sage: h = loads(dumps(g))
     1231            sage: g.parent() == h.parent()
     1232            False
     1233        """
    10591234        MaximaElement.__init__(self, parent, name, is_name=True)
    1060         MaximaAbstractElementFunction.__init__(self, parent, name, defn, args, latex)
     1235        MaximaAbstractElementFunction.__init__(self, parent,
     1236                                name, defn, args, latex)
    10611237
    10621238
    10631239# An instance
    1064 maxima = Maxima(init_code = ['display2d : false; domain : complex; keepfloat : true'],
     1240maxima = Maxima(init_code = ['display2d : false',
     1241                'domain : complex', 'keepfloat : true'],
    10651242                script_subdirectory=None)
    10661243
    10671244
    1068 def reduce_load_Maxima():
     1245def reduce_load_Maxima(): #(init_code=None):
    10691246    """
     1247    Unpickle a Maxima Pexpect interface.
     1248
    10701249    EXAMPLES::
    10711250   
    10721251        sage: from sage.interfaces.maxima import reduce_load_Maxima
    10731252        sage: reduce_load_Maxima()
    10741253        Maxima
    10751254    """
    1076     return maxima
     1255    return maxima #Maxima(init_code=init_code)
    10771256
     1257# This is defined for compatibility with the old Maxima interface.
    10781258def reduce_load_Maxima_function(parent, defn, args, latex):
     1259    """
     1260    Unpickle a Maxima function.
     1261
     1262    EXAMPLES::
     1263
     1264        sage: from sage.interfaces.maxima import reduce_load_Maxima_function
     1265        sage: f = maxima.function('x,y','sin(x+y)')
     1266        sage: _,args = f.__reduce__()
     1267        sage: g = reduce_load_Maxima_function(*args)
     1268        sage: g == f
     1269        True
     1270    """
    10791271    return parent.function(args, defn, defn, latex)
    10801272
    10811273def __doctest_cleanup():
     1274    """
     1275    Kill all Pexpect interfaces.
     1276
     1277    EXAMPLES::
     1278   
     1279        sage: from sage.interfaces.maxima import __doctest_cleanup
     1280        sage: maxima(1)
     1281        1
     1282        sage: maxima.is_running()
     1283        True
     1284        sage: __doctest_cleanup()
     1285        sage: maxima.is_running()
     1286        False
     1287    """
    10821288    import sage.interfaces.quit
    10831289    sage.interfaces.quit.expect_quitall()
  • sage/interfaces/maxima_abstract.py

    diff -r 1bd1f40c456f -r 88910e6cc47b sage/interfaces/maxima_abstract.py
    a b  
    11r"""
    2 Interface to Maxima
     2Abstract interface to Maxima
    33
    44Maxima is a free GPL'd general purpose computer algebra system
    55whose development started in 1968 at MIT. It contains symbolic
     
    2626- William Stein (2006-02-24): *greatly* improved robustness by adding
    2727  sequence numbers to IO bracketing in _eval_line
    2828
    29 If the string "error" (case insensitive) occurs in the output of
    30 anything from Maxima, a RuntimeError exception is raised.
     29- Robert Bradshaw, Nils Bruin, Jean-Pierre Flori (2010,2011): Binary library
     30  interface
     31
     32This is an abstract class implementing the functions shared between the Pexpect
     33and library interfaces to Maxima.
    3134"""
    3235
    3336#*****************************************************************************
     
    5760##import sage.rings.all
    5861import sage.rings.complex_number
    5962
    60 from interface import Interface, InterfaceElement, InterfaceFunctionElement, InterfaceFunction, AsciiArtString
     63from interface import (Interface, InterfaceElement, InterfaceFunctionElement,
     64  InterfaceFunction, AsciiArtString)
    6165
    6266# The Maxima "apropos" command, e.g., apropos(det) gives a list
    6367# of all identifiers that begin in a certain way.  This could
     
    6569# documentation from the system -- this could also be useful.
    6670
    6771class MaximaAbstract(Interface):
     72    r"""
     73    Abstract interface to Maxima.
     74
     75    INPUT:
     76
     77    - ``name`` - string
     78
     79    OUTPUT: the interface
     80
     81    EXAMPLES:
     82   
     83    This class should not be instantiated directly,
     84    but through its subclasses Maxima (Pexpect interface)
     85    or MaximaLib (library interface)::
     86
     87        sage: m = Maxima()
     88        sage: from sage.interfaces.maxima_abstract import MaximaAbstract
     89        sage: isinstance(m,MaximaAbstract)
     90        True
    6891    """
    69     Interface to the Maxima interpreter.
    70     """
    71     def __init__(self, name):
    72         """
     92
     93    def __init__(self, name='maxima_abstract'):
     94        r"""
    7395        Create an instance of an abstract interface to Maxima.
     96        See ``MaximaAbstract`` for full documentation.
     97
     98        EXAMPLES::
     99
     100            sage: from sage.interfaces.maxima_abstract import MaximaAbstract
     101            sage: isinstance(maxima,MaximaAbstract)
     102            True
     103
     104        TESTS::
     105
     106            sage: from sage.interfaces.maxima_abstract import MaximaAbstract
     107            sage: loads(dumps(MaximaAbstract)) == MaximaAbstract
     108            True
    74109        """
    75110        Interface.__init__(self,name)
    76111
     
    78113    # System -- change directory, etc
    79114    ###########################################
    80115    def chdir(self, dir):
    81         """
     116        r"""
    82117        Change Maxima's current working directory.
    83118       
     119        INPUT:
     120
     121        - ``dir`` - string
     122
     123        OUTPUT: none
     124
    84125        EXAMPLES::
    85126       
    86127            sage: maxima.chdir('/')
     
    91132    # Interactive help
    92133    ###########################################
    93134    def _command_runner(self, command, s, redirect=True):
    94         """
     135        r"""
    95136        Run ``command`` in a new Maxima session and return its
    96137        output as an ``AsciiArtString``.
     138
     139        INPUT:
    97140       
    98         If redirect is set to False, then the output of the command is not
    99         returned as a string. Instead, it behaves like os.system. This is
    100         used for interactive things like Maxima's demos. See maxima.demo?
     141        - ``command`` - string; function to call
     142
     143        - ``s`` - string; argument to the function
     144
     145        - ``redirect`` - boolean (default: True); if redirect is set to False,
     146          then the output of the command is not returned as a string.
     147          Instead, it behaves like os.system. This is used for interactive
     148          things like Maxima's demos. See maxima.demo?
     149
     150        OUTPUT:
     151
     152        Output of ``command(s)`` as an ``AsciiArtString`` if ``redirect`` is set
     153        to False; None otherwise.
    101154       
    102155        EXAMPLES::
    103156       
     
    125178            subprocess.Popen(cmd, shell=True)
    126179
    127180    def help(self, s):
    128         """
     181        r"""
     182        Return Maxima's help for ``s``.
     183
     184        INPUT:
     185
     186        - ``s`` - string
     187
     188        OUTPUT:
     189
     190        Maxima's help for ``s``
     191
    129192        EXAMPLES::
    130193       
    131194            sage: maxima.help('gcd')
    132195            -- Function: gcd (<p_1>, <p_2>, <x_1>, ...)
    133196            ...
    134197        """
     198        # Should this be implemented without launching a new Maxima session
     199        # i.e. using eval_line ?
    135200        return self._command_runner("describe", s)
    136201
    137202    def example(self, s):
    138         """
     203        r"""
     204        Return Maxima's examples for ``s``.
     205
     206        INPUT:
     207
     208        - ``s`` - string
     209
     210        OUTPUT:
     211
     212        Maxima's examples for ``s``
     213
    139214        EXAMPLES::
    140215       
    141216            sage: maxima.example('arrays')
     
    152227                                                  24
    153228                                                 done
    154229        """
     230        # Should this be implemented without launching a new Maxima session
     231        # i.e. using eval_line ?
    155232        return self._command_runner("example", s)
    156233
    157234    describe = help
    158235
    159236    def demo(self, s):
    160         """
     237        r"""
     238        Run Maxima's demo for ``s``.
     239
     240        INPUT:
     241
     242        - ``s`` - string
     243
     244        OUTPUT: none
     245
    161246        EXAMPLES::
    162247       
    163248            sage: maxima.demo('array') # not tested
     
    166251        At the _ prompt, type ';' followed by enter to get next demo
    167252        subscrmap : true _
    168253        """
     254        # Should this be implemented without launching a new Maxima session
     255        # i.e. using eval_line ?
    169256        return self._command_runner("demo", s, redirect=False)
    170257
    171258    def completions(self, s, verbose=True):
    172         """
     259        r"""
    173260        Return all commands that complete the command starting with the
    174         string s. This is like typing s[tab] in the Maxima interpreter.
     261        string ``s``. This is like typing s[tab] in the Maxima interpreter.
     262
     263        INPUT:
     264
     265        - ``s`` - string
     266
     267        - ``verbose`` - boolean (default: True)
     268
     269        OUTPUT: array of strings
    175270       
    176271        EXAMPLES::
    177272       
     
    191286    def _commands(self, verbose=True):
    192287        """
    193288        Return list of all commands defined in Maxima.
     289
     290        INPUT:
     291
     292        - ``verbose`` - boolean (default: True)
     293
     294        OUTPUT: array of strings
    194295       
    195296        EXAMPLES::
    196297       
     298            # The output is kind of random
    197299            sage: sorted(maxima._commands(verbose=False))
    198             ['Alpha',
    199              'Beta',
     300            [...
     301             'display',
    200302             ...
    201              'zunderflow']
     303             'gcd',
     304             ...
     305             'verbose',
     306             ...]
    202307        """
    203308        try:
    204309            return self.__commands
     
    210315        return self.__commands
    211316
    212317    def trait_names(self, verbose=True, use_disk_cache=True):
    213         """
     318        r"""
    214319        Return all Maxima commands, which is useful for tab completion.
     320
     321        INPUT:
     322
     323        - ``verbose`` - boolean (default: True)
     324
     325        - ``use_disk_cache`` - boolean (default: True); if set to True,
     326          try to read cached result from disk
     327
     328        OUTPUT: array of strings
    215329       
    216330        EXAMPLES::
    217331       
     
    247361        Start the interactive Maxima console. This is a completely separate
    248362        maxima session from this interface. To interact with this session,
    249363        you should instead use ``maxima.interact()``.
     364
     365        INPUT: none
    250366       
     367        OUTPUT: none
     368
    251369        EXAMPLES::
    252370       
    253371            sage: maxima.console()             # not tested (since we can't)
     
    273391    def cputime(self, t=None):
    274392        r"""
    275393        Returns the amount of CPU time that this Maxima session has used.
    276         If \var{t} is not None, then it returns the difference between
    277         the current CPU time and \var{t}.
     394
     395        INPUT:
     396
     397        - ``t`` - float (default: None); If \var{t} is not None, then
     398          it returns the difference between the current CPU time and \var{t}.
     399
     400        OUTPUT: float
    278401       
    279402        EXAMPLES:
    280403            sage: t = maxima.cputime()
     
    288411            return float(self.eval('elapsed_run_time()'))
    289412
    290413    def version(self):
    291         """
     414        r"""
    292415        Return the version of Maxima that Sage includes.
     416
     417        INPUT: none
     418       
     419        OUTPUT: none
    293420       
    294421        EXAMPLES::
    295422       
     
    303430    ###
    304431
    305432    def _assign_symbol(self):
     433        r"""
     434        Return the assign symbol in Maxima.
     435
     436        INPUT: none
     437       
     438        OUTPUT: string
     439
     440        EXAMPLES::
     441
     442            sage: maxima._assign_symbol()
     443            ':'
     444            sage: maxima.eval('t : 8')
     445            '8'
     446            sage: maxima.eval('t')
     447            '8'
     448        """
    306449        return ":"
    307450
    308451    def _true_symbol(self):
    309452        """
    310453        Return the true symbol in Maxima.
     454
     455        INPUT: none
     456       
     457        OUTPUT: string
    311458       
    312459        EXAMPLES::
    313460       
     
    321468    def _false_symbol(self):
    322469        """
    323470        Return the false symbol in Maxima.
     471
     472        INPUT: none
     473       
     474        OUTPUT: string
    324475       
    325476        EXAMPLES::
    326477       
     
    335486        """
    336487        Returns the equality symbol in Maxima.
    337488
     489        INPUT: none
     490       
     491        OUTPUT: string
     492
    338493        EXAMPLES::
    339494
    340495             sage: maxima._equality_symbol()
    341496             '='
     497             sage: var('x y')
     498             (x, y)
     499             sage: maxima(x == y)
     500             x=y
    342501        """
    343502        return '='
    344503
    345504    def _inequality_symbol(self):
    346505        """
    347         Returns the equality symbol in Maxima.
     506        Returns the inequality symbol in Maxima.
     507
     508        INPUT: none
     509       
     510        OUTPUT: string
    348511
    349512        EXAMPLES::
    350513
     
    357520
    358521    def _function_class(self):
    359522        """
     523        Return the Python class of Maxima functions.
     524
     525        INPUT: none
     526       
     527        OUTPUT: type
     528
    360529        EXAMPLES::
    361530       
    362531            sage: maxima._function_class()
     
    367536    def _object_class(self):
    368537        """
    369538        Return the Python class of Maxima elements.
     539
     540        INPUT: none
     541       
     542        OUTPUT: type
    370543       
    371544        EXAMPLES::
    372545       
     
    376549        return MaximaAbstractElement
    377550
    378551    def _function_element_class(self):
    379         """     
     552        """
     553        Return the Python class of Maxima functions of elements.
     554
     555        INPUT: none
     556       
     557        OUTPUT: type
     558
    380559        EXAMPLES::
    381560       
    382561            sage: maxima._function_element_class()
     
    386565
    387566    def _object_function_class(self):
    388567        """
     568        Return the Python class of Maxima user-defined functions.
     569
     570        INPUT: none
     571       
     572        OUTPUT: type
     573
    389574        EXAMPLES::
    390575       
    391576            sage: maxima._object_function_class()
     
    393578        """
    394579        return MaximaAbstractElementFunction
    395580
    396     ####
    397     #
    398     ####
     581    ####################
     582    # Maxima functions #
     583    ####################
    399584
    400585    def function(self, args, defn, rep=None, latex=None):
    401586        """
     
    403588       
    404589        INPUT:
    405590       
    406        
    407         -  ``args`` - a string with variable names separated by
     591        - ``args`` - a string with variable names separated by
    408592           commas
    409593       
    410         -  ``defn`` - a string (or Maxima expression) that
     594        - ``defn`` - a string (or Maxima expression) that
    411595           defines a function of the arguments in Maxima.
    412596       
    413         -  ``rep`` - an optional string; if given, this is how
     597        - ``rep`` - an optional string; if given, this is how
    414598           the function will print.
    415599       
     600        OUTPUT: Maxima function
    416601       
    417602        EXAMPLES::
    418603       
     
    433618            sage: g(1,2,3)
    434619            3*(cos(2)+sin(1))
    435620       
    436         The function definition can be a maxima object::
     621        The function definition can be a Maxima object::
    437622       
    438623            sage: an_expr = maxima('sin(x)*gamma(x)')
    439624            sage: t = maxima.function('x', an_expr)
     
    462647        f = self._object_function_class()(self, name, rep, args, latex)
    463648        return f
    464649
    465     #####
    466     # Maxima functions
    467     #####
    468    
    469650##     def display2d(self, flag=True):
    470651##         """
    471652##         Set the flag that determines whether Maxima objects are
     
    496677       
    497678        INPUT:
    498679       
    499        
    500         -  ``f`` - a string representing a function (such as
     680        - ``f`` - a string representing a function (such as
    501681           f="sin(x)") [var, xmin, xmax]
    502682       
    503         -  ``options`` - an optional string representing plot2d
     683        - ``options`` - an optional string representing plot2d
    504684           options in gnuplot format
    505685       
    506        
    507686        EXAMPLES::
    508687       
    509688            sage: maxima.plot2d('sin(x)','[x,-5,5]')   # not tested
     
    516695
    517696    def plot2d_parametric(self, r, var, trange, nticks=50, options=None):
    518697        r"""
    519         Plots r = [x(t), y(t)] for t = tmin...tmax using gnuplot with
    520         options
     698        Plot r = [x(t), y(t)] for t = tmin...tmax using gnuplot with
     699        options.
    521700       
    522701        INPUT:
    523        
    524        
    525         -  ``r`` - a string representing a function (such as
     702
     703        - ``r`` - a string representing a function (such as
    526704           r="[x(t),y(t)]")
    527705       
    528         -  ``var`` - a string representing the variable (such
     706        - ``var`` - a string representing the variable (such
    529707           as var = "t")
    530708       
    531         -  ``trange`` - [tmin, tmax] are numbers with tmintmax
     709        - ``trange`` - [tmin, tmax] are numbers with tmintmax
    532710       
    533         -  ``nticks`` - int (default: 50)
     711        - ``nticks`` - int (default: 50)
    534712       
    535         -  ``options`` - an optional string representing plot2d
     713        - ``options`` - an optional string representing plot2d
    536714           options in gnuplot format
    537715       
    538        
    539716        EXAMPLES::
    540717       
    541718            sage: maxima.plot2d_parametric(["sin(t)","cos(t)"], "t",[-3.1,3.1])   # not tested
     
    570747       
    571748        INPUT:
    572749       
    573        
    574         -  ``f`` - a string representing a function (such as
     750        - ``f`` - a string representing a function (such as
    575751           f="sin(x)") [var, min, max]
    576752       
    577        
     753        - ``args`` should be of the form '[x, xmin, xmax]', '[y, ymin, ymax]',
     754          '[grid, nx, ny]', options
     755
    578756        EXAMPLES::
    579757       
    580758            sage: maxima.plot3d('1 + x^3 - y^2', '[x,-2,2]', '[y,-2,2]', '[grid,12,12]')    # not tested
     
    594772       
    595773        INPUT:
    596774       
    597        
    598         -  ``x, y, z`` - a string representing a function (such
     775        - ``x, y, z`` - a string representing a function (such
    599776           as ``x="u2+v2"``, ...) vars is a list or two strings
    600777           representing variables (such as vars = ["u","v"])
    601778       
    602         -  ``urange`` - [umin, umax]
     779        - ``urange`` - [umin, umax]
    603780       
    604         -  ``vrange`` - [vmin, vmax] are lists of numbers with
     781        - ``vrange`` - [vmin, vmax] are lists of numbers with
    605782           umin umax, vmin vmax
    606783       
    607         -  ``options`` - optional string representing plot2d
     784        - ``options`` - optional string representing plot2d
    608785           options in gnuplot format
    609786       
    610        
    611787        OUTPUT: displays a plot on screen or saves to a file
    612788       
    613789        EXAMPLES::
     
    649825       
    650826        INPUT:
    651827       
    652        
    653828        -  ``de`` - a string representing the ODE
    654829       
    655         -  ``vars`` - a list of strings representing the two
     830        - ``vars`` - a list of strings representing the two
    656831           variables.
    657832       
    658         -  ``ics`` - a triple of numbers [a,b1,b2] representing
     833        - ``ics`` - a triple of numbers [a,b1,b2] representing
    659834           y(a)=b1, y'(a)=b2
    660835       
    661        
    662836        EXAMPLES::
    663837       
    664838            sage: maxima.de_solve('diff(y,x,2) + 3*x = y', ['x','y'], [1,1,1])
     
    692866       
    693867        INPUT:
    694868       
    695        
    696         -  ``de`` - a string representing the ODE (e.g., de =
     869        - ``de`` - a string representing the ODE (e.g., de =
    697870           "diff(f(x),x,2)=diff(f(x),x)+sin(x)")
    698871       
    699         -  ``vars`` - a list of strings representing the
     872        - ``vars`` - a list of strings representing the
    700873           variables (e.g., vars = ["x","f"])
    701874       
    702         -  ``ics`` - a list of numbers representing initial
     875        - ``ics`` - a list of numbers representing initial
    703876           conditions, with symbols allowed which are represented by strings
    704877           (eg, f(0)=1, f'(0)=2 is ics = [0,1,2])
    705878       
    706        
    707879        EXAMPLES::
    708880       
    709881            sage: maxima.clear('x'); maxima.clear('f')
     
    712884       
    713885        ::
    714886       
    715             sage: maxima.clear('x'); maxima.clear('f')           
     887            sage: maxima.clear('x'); maxima.clear('f')
    716888            sage: f = maxima.de_solve_laplace("diff(f(x),x,2) = 2*diff(f(x),x)-f(x)", ["x","f"])
    717889            sage: f
    718890            f(x)=x*%e^x*('at('diff(f(x),x,1),x=0))-f(0)*x*%e^x+f(0)*%e^x
     
    742914        """
    743915        Wraps maxima's linsolve.
    744916       
    745         INPUT: eqns is a list of m strings, each representing a linear
    746         question in m = n variables vars is a list of n strings, each
    747         representing a variable
     917        INPUT:
     918
     919        - ``eqns`` - a list of m strings; each representing a linear
     920          question in m = n variables
     921
     922        - ``vars`` - a list of n strings; each
     923          representing a variable
    748924       
    749925        EXAMPLES::
    750926       
    751             sage: eqns = ["x + z = y","2*a*x - y = 2*a^2","y - 2*z = 2"]   
    752             sage: vars = ["x","y","z"]                                     
     927            sage: eqns = ["x + z = y","2*a*x - y = 2*a^2","y - 2*z = 2"]
     928            sage: vars = ["x","y","z"]
    753929            sage: maxima.solve_linear(eqns, vars)
    754930            [x=a+1,y=2*a,z=a-1]
    755931        """
     
    770946    def unit_quadratic_integer(self, n):
    771947        r"""
    772948        Finds a unit of the ring of integers of the quadratic number field
    773         `\QQ(\sqrt{n})`, `n>1`, using the qunit maxima
    774         command.
     949        `\QQ(\sqrt{n})`, `n>1`, using the qunit maxima command.
     950
     951        INPUT:
     952
     953        - ``n`` - an integer
    775954       
    776955        EXAMPLES::
    777956       
    778             sage: u = maxima.unit_quadratic_integer(101); u     
     957            sage: u = maxima.unit_quadratic_integer(101); u
    779958            a + 10
    780             sage: u.parent()                                       
     959            sage: u.parent()
    781960            Number Field in a with defining polynomial x^2 - 101
    782             sage: u = maxima.unit_quadratic_integer(13)           
    783             sage: u                                               
     961            sage: u = maxima.unit_quadratic_integer(13)
     962            sage: u
    784963            5*a + 18
    785             sage: u.parent()                                       
     964            sage: u.parent()
    786965            Number Field in a with defining polynomial x^2 - 13
    787966        """
    788967        from sage.rings.all import QuadraticField, Integer
    789         # Take square-free part so sqrt(n) doesn't get simplified further by maxima
     968        # Take square-free part so sqrt(n) doesn't get simplified
     969        # further by maxima
    790970        # (The original version of this function would yield wrong answers if
    791971        # n is not squarefree.)
    792         n = Integer(n).squarefree_part() 
     972        n = Integer(n).squarefree_part()
    793973        if n < 1:
    794974            raise ValueError, "n (=%s) must be >= 1"%n
    795975        s = repr(self('qunit(%s)'%n)).lower()
     
    804984       
    805985        INPUT:
    806986       
    807        
    808         -  ``ptsx`` - [x1,...,xn], where the xi and yi are
     987        - ``ptsx`` - [x1,...,xn], where the xi and yi are
    809988           real,
    810989       
    811         -  ``ptsy`` - [y1,...,yn]
     990        - ``ptsy`` - [y1,...,yn]
    812991       
    813         -  ``options`` - a string representing maxima plot2d
     992        - ``options`` - a string representing maxima plot2d
    814993           options.
    815994       
    816        
    817995        The points are (x1,y1), (x2,y2), etc.
    818996       
    819997        This function requires maxima 5.9.2 or newer.
     
    8451023        where each ptsi is of the form [[x1,y1],...,[xn,yn]] x's must be
    8461024        integers and y's reals options is a string representing maxima
    8471025        plot2d options.
     1026
     1027        INPUT:
     1028       
     1029        - ``pts_lst`` - list of points; each point must be of the form [x,y]
     1030          where ``x`` is an integer and ``y`` is a real
     1031
     1032        - ``var`` - string; representing Maxima's plot2d options
    8481033       
    8491034        Requires maxima 5.9.2 at least.
    8501035
     
    8651050            sage: zeta_ptsx1 = [ (pari(1/2+i*I/10).zeta().real()).precision(1) for i in range (10,150)]
    8661051            sage: zeta_ptsy1 = [ (pari(1/2+i*I/10).zeta().imag()).precision(1) for i in range (10,150)]
    8671052            sage: maxima.plot_multilist([[zeta_ptsx1,zeta_ptsy1],[xx,y0],[x0,yy]])      # not tested
    868             sage: opts='[gnuplot_preamble, "set nokey"]'                 
     1053            sage: opts='[gnuplot_preamble, "set nokey"]'
    8691054            sage: maxima.plot_multilist([[zeta_ptsx1,zeta_ptsy1],[xx,y0],[x0,yy]],opts)    # not tested
    8701055        """
    8711056        n = len(pts_list)
     
    8801065            self('plot2d('+cmd+')')
    8811066        else:
    8821067            self('plot2d('+cmd+','+options+')')
    883    
     1068
    8841069
    8851070class MaximaAbstractElement(InterfaceElement):
     1071    r"""
     1072    Element of Maxima through an abstract interface.
     1073
     1074    EXAMPLES:
     1075
     1076    Elements of this class should not be created directly.
     1077    The targeted parent of a concrete inherited class should be used instead::
     1078
     1079        sage: from sage.interfaces.maxima_lib import maxima_lib
     1080        sage: xp = maxima(x)
     1081        sage: type(xp)
     1082        <class 'sage.interfaces.maxima.MaximaElement'>
     1083        sage: xl = maxima_lib(x)
     1084        sage: type(xl)
     1085        <class 'sage.interfaces.maxima_lib.MaximaLibElement'>
     1086    """
     1087
    8861088    def __str__(self):
    8871089        """
    888         Printing an object explicitly gives ASCII art:
     1090        Printing an object explicitly gives ASCII art.
     1091
     1092        INPUT: none
     1093
     1094        OUTPUT: string
    8891095       
    8901096        EXAMPLES::
    8911097       
     
    9011107
    9021108    def bool(self):
    9031109        """
     1110        Convert ``self`` into a boolean.
     1111
     1112        INPUT: none
     1113
     1114        OUTPUT: boolean
     1115
    9041116        EXAMPLES::
    9051117       
    9061118            sage: maxima(0).bool()
     
    9131125
    9141126    def __cmp__(self, other):
    9151127        """
     1128        Compare this Maxima object with ``other``.
     1129
     1130        INPUT:
     1131
     1132        - ``other`` - an object to compare to
     1133
     1134        OUTPUT: integer
     1135
    9161136        EXAMPLES::
    9171137       
    9181138            sage: a = maxima(1); b = maxima(2)
     
    9351155        """
    9361156
    9371157        # thanks to David Joyner for telling me about using "is".
    938         # but be careful, since for relations things like is(equal(a,b)) are what Maxima needs
     1158        # but be careful, since for relations things like is(equal(a,b))
     1159        # are what Maxima needs
    9391160        P = self.parent()
    9401161        try:
    9411162            if P.eval("is (%s < %s)"%(self.name(), other.name())) == P._true_symbol():
     
    9471168        except TypeError:
    9481169            pass
    9491170        return cmp(repr(self),repr(other))
    950                    # everything is supposed to be comparable in Python, so we define
    951                    # the comparison thus when no comparable in interfaced system.
     1171        # everything is supposed to be comparable in Python,
     1172        # so we define the comparison thus when no comparable
     1173        # in interfaced system.
    9521174
    9531175    def _sage_(self):
    9541176        """
    955         Attempt to make a native Sage object out of this maxima object.
     1177        Attempt to make a native Sage object out of this Maxima object.
    9561178        This is useful for automatic coercions in addition to other
    9571179        things.
     1180
     1181        INPUT: none
     1182
     1183        OUTPUT: Sage object
    9581184       
    9591185        EXAMPLES::
    9601186       
     
    10001226
    10011227    def _symbolic_(self, R):
    10021228        """
    1003         Return a symbolic expression equivalent to this maxima object.
     1229        Return a symbolic expression equivalent to this Maxima object.
     1230
     1231        INPUT:
     1232
     1233        - ``R`` - symbolic ring to convert into
     1234
     1235        OUTPUT: symbolic expression
    10041236
    10051237        EXAMPLES::
    10061238
     
    10101242            sage: u.parent()
    10111243            Symbolic Ring
    10121244
    1013         This is used when converting maxima objects to the Symbolic Ring::
     1245        This is used when converting Maxima objects to the Symbolic Ring::
    10141246
    10151247            sage: SR(t)
    10161248            sqrt(2)
     
    10191251
    10201252    def __complex__(self):
    10211253        """
     1254        Return a complex number equivalent to this Maxima object.
     1255
     1256        INPUT: none
     1257
     1258        OUTPUT: complex
     1259
    10221260        EXAMPLES::
    10231261       
    10241262            sage: complex(maxima('sqrt(-2)+1'))
     
    10281266
    10291267    def _complex_mpfr_field_(self, C):
    10301268        """
     1269        Return a mpfr complex number equivalent to this Maxima object.
     1270
     1271        INPUT:
     1272
     1273        - ``C`` - complex numbers field to convert into
     1274
     1275        OUTPUT: complex
     1276       
    10311277        EXAMPLES::
    10321278       
    10331279            sage: CC(maxima('1+%i'))
     
    10471293
    10481294    def _mpfr_(self, R):
    10491295        """
     1296        Return a mpfr real number equivalent to this Maxima object.
     1297
     1298        INPUT:
     1299
     1300        - ``R`` - real numbers field to convert into
     1301
     1302        OUTPUT: real
     1303
    10501304        EXAMPLES::
    10511305       
    10521306            sage: RealField(100)(maxima('sqrt(2)+1'))
     
    10561310
    10571311    def _complex_double_(self, C):
    10581312        """
     1313        Return a double precision complex number equivalent to this Maxima object.
     1314
     1315        INPUT:
     1316
     1317        - ``C`` - double precision complex numbers field to convert into
     1318
     1319        OUTPUT: complex
     1320
    10591321        EXAMPLES::
    10601322       
    10611323            sage: CDF(maxima('sqrt(2)+1'))
     
    10651327
    10661328    def _real_double_(self, R):
    10671329        """
     1330        Return a double precision real number equivalent to this Maxima object.
     1331
     1332        INPUT:
     1333
     1334        - ``R`` - double precision real numbers field to convert into
     1335
     1336        OUTPUT: real
     1337
    10681338        EXAMPLES::
    10691339       
    10701340            sage: RDF(maxima('sqrt(2)+1'))
     
    10741344
    10751345    def real(self):
    10761346        """
    1077         Return the real part of this maxima element.
     1347        Return the real part of this Maxima element.
    10781348       
     1349        INPUT: none
     1350
     1351        OUTPUT: Maxima real
     1352
    10791353        EXAMPLES::
    10801354       
    10811355            sage: maxima('2 + (2/3)*%i').real()
     
    10851359
    10861360    def imag(self):
    10871361        """
    1088         Return the imaginary part of this maxima element.
     1362        Return the imaginary part of this Maxima element.
     1363       
     1364        INPUT: none
     1365
     1366        OUTPUT: Maxima real
    10891367       
    10901368        EXAMPLES::
    10911369       
     
    10981376        """
    10991377        Return numerical approximation to self as a Maxima object.
    11001378       
     1379        INPUT: none
     1380
     1381        OUTPUT: Maxima object
     1382       
    11011383        EXAMPLES::
    11021384       
    11031385            sage: a = maxima('sqrt(2)').numer(); a
     
    11091391
    11101392    def str(self):
    11111393        """
    1112         Return string representation of this maxima object.
     1394        Return string representation of this Maxima object.
     1395
     1396        INPUT: none
     1397
     1398        OUTPUT: string
    11131399       
    11141400        EXAMPLES::
    11151401       
     
    11211407
    11221408    def __repr__(self):
    11231409        """
    1124         Return print representation of this object.
     1410        Return print representation of this Maxima object.
     1411
     1412        INPUT: none
     1413
     1414        OUTPUT: string
     1415
     1416        The result is cached.
    11251417       
    11261418        EXAMPLES::
    11271419       
     
    11431435       
    11441436        INPUT:
    11451437       
     1438        - ``var`` - variable (default: 'x')
    11461439       
    1147         -  ``var`` - variable (default: 'x')
    1148        
    1149         -  ``n`` - integer (default: 1)
    1150        
     1440        - ``n`` - integer (default: 1)
    11511441       
    11521442        OUTPUT: n-th derivative of self with respect to the variable var
    11531443       
    11541444        EXAMPLES::
    11551445       
    1156             sage: f = maxima('x^2')                         
    1157             sage: f.diff()                                   
     1446            sage: f = maxima('x^2')
     1447            sage: f.diff()
    11581448            2*x
    1159             sage: f.diff('x')                               
     1449            sage: f.diff('x')
    11601450            2*x
    1161             sage: f.diff('x', 2)                             
     1451            sage: f.diff('x', 2)
    11621452            2
    11631453            sage: maxima('sin(x^2)').diff('x',4)
    11641454            16*x^4*sin(x^2)-12*sin(x^2)-48*x^2*cos(x^2)
    11651455       
    11661456        ::
    11671457       
    1168             sage: f = maxima('x^2 + 17*y^2')                 
     1458            sage: f = maxima('x^2 + 17*y^2')
    11691459            sage: f.diff('x')
    11701460            34*y*'diff(y,x,1)+2*x
    1171             sage: f.diff('y')                               
     1461            sage: f.diff('y')
    11721462            34*y
    11731463        """
    11741464        return InterfaceElement.__getattr__(self, 'diff')(var, n)
     
    11841474       
    11851475        INPUT:
    11861476       
     1477        - ``var`` - variable to integrate with respect to
    11871478       
    1188         -  ``var`` - variable to integrate with respect to
     1479        - ``a`` - lower endpoint of integration
    11891480       
    1190         -  ``a`` - lower endpoint of integration
     1481        - ``b`` - upper endpoint of integration
    11911482       
    1192         -  ``b`` - upper endpoint of integration
    1193        
    1194         -  ``desired_relative_error`` - (default: '1e-8') the
     1483        - ``desired_relative_error`` - (default: '1e-8') the
    11951484           desired relative error
    11961485       
    1197         -  ``maximum_num_subintervals`` - (default: 200)
     1486        - ``maximum_num_subintervals`` - (default: 200)
    11981487           maxima number of subintervals
    11991488       
    1200        
    12011489        OUTPUT:
    12021490       
     1491        - approximation to the integral
    12031492       
    1204         -  approximation to the integral
    1205        
    1206         -  estimated absolute error of the
     1493        - estimated absolute error of the
    12071494           approximation
    12081495       
    1209         -  the number of integrand evaluations
     1496        - the number of integrand evaluations
    12101497       
    1211         -  an error code:
     1498        - an error code:
    12121499       
    1213             -  ``0`` - no problems were encountered
     1500            - ``0`` - no problems were encountered
    12141501
    1215             -  ``1`` - too many subintervals were done
     1502            - ``1`` - too many subintervals were done
    12161503
    1217             -  ``2`` - excessive roundoff error
     1504            - ``2`` - excessive roundoff error
    12181505
    1219             -  ``3`` - extremely bad integrand behavior
     1506            - ``3`` - extremely bad integrand behavior
    12201507
    1221             -  ``4`` - failed to converge
     1508            - ``4`` - failed to converge
    12221509
    1223             -  ``5`` - integral is probably divergent or slowly convergent
     1510            - ``5`` - integral is probably divergent or slowly convergent
    12241511
    1225             -  ``6`` - the input is invalid
    1226        
     1512            - ``6`` - the input is invalid
    12271513       
    12281514        EXAMPLES::
    12291515       
     
    12331519        Note that GP also does numerical integration, and can do so to very
    12341520        high precision very quickly::
    12351521       
    1236             sage: gp('intnum(x=0,1,exp(-sqrt(x)))')           
     1522            sage: gp('intnum(x=0,1,exp(-sqrt(x)))')
    12371523            0.5284822353142307136179049194             # 32-bit
    12381524            0.52848223531423071361790491935415653022   # 64-bit
    12391525            sage: _ = gp.set_precision(80)
     
    12511537       
    12521538        INPUT:
    12531539       
     1540        - ``var`` - variable
    12541541       
    1255         -  ``var`` - variable
     1542        - ``min`` - default: None
    12561543       
    1257         -  ``min`` - default: None
     1544        - ``max`` - default: None
    12581545       
    1259         -  ``max`` - default: None
     1546        OUTPUT:
    12601547       
     1548        - the definite integral if xmin is not None
    12611549       
    1262         Returns the definite integral if xmin is not None, otherwise
    1263         returns an indefinite integral.
     1550        - an indefinite integral otherwise
    12641551       
    12651552        EXAMPLES::
    12661553       
    1267             sage: maxima('x^2+1').integral()                   
     1554            sage: maxima('x^2+1').integral()
    12681555            x^3/3+x
    1269             sage: maxima('x^2+ 1 + y^2').integral('y')         
     1556            sage: maxima('x^2+ 1 + y^2').integral('y')
    12701557            y^3/3+x^2*y+y
    1271             sage: maxima('x / (x^2+1)').integral()             
     1558            sage: maxima('x / (x^2+1)').integral()
    12721559            log(x^2+1)/2
    1273             sage: maxima('1/(x^2+1)').integral()               
     1560            sage: maxima('1/(x^2+1)').integral()
    12741561            atan(x)
    1275             sage: maxima('1/(x^2+1)').integral('x', 0, infinity) 
     1562            sage: maxima('1/(x^2+1)').integral('x', 0, infinity)
    12761563            %pi/2
    1277             sage: maxima('x/(x^2+1)').integral('x', -1, 1)     
     1564            sage: maxima('x/(x^2+1)').integral('x', -1, 1)
    12781565            0
    12791566       
    12801567        ::
    12811568       
    1282             sage: f = maxima('exp(x^2)').integral('x',0,1); f   
     1569            sage: f = maxima('exp(x^2)').integral('x',0,1); f
    12831570            -sqrt(%pi)*%i*erf(%i)/2
    12841571            sage: f.numer()
    12851572            1.46265174590718...
     
    12961583
    12971584    def __float__(self):
    12981585        """
    1299         Return floating point version of this maxima element.
     1586        Return floating point version of this Maxima element.
     1587
     1588        INPUT: none
     1589
     1590        OUTPUT: real
    13001591       
    13011592        EXAMPLES::
    13021593       
     
    13151606    def __len__(self):
    13161607        """
    13171608        Return the length of a list.
     1609
     1610        INPUT: none
     1611
     1612        OUTPUT: integer
    13181613       
    13191614        EXAMPLES::
    13201615       
    1321             sage: v = maxima('create_list(x^i,i,0,5)')         
    1322             sage: len(v)                                       
     1616            sage: v = maxima('create_list(x^i,i,0,5)')
     1617            sage: len(v)
    13231618            6
    13241619        """
    1325         P = self._check_valid()       
     1620        P = self._check_valid()
    13261621        return int(P.eval('length(%s)'%self.name()))
    13271622
    13281623    def dot(self, other):
    13291624        """
    13301625        Implements the notation self . other.
     1626
     1627        INPUT:
     1628
     1629        - ``other`` - matrix; argument to dot.
     1630
     1631        OUTPUT: Maxima matrix
    13311632       
    13321633        EXAMPLES::
    13331634       
     
    13431644    def __getitem__(self, n):
    13441645        r"""
    13451646        Return the n-th element of this list.
     1647
     1648        INPUT:
     1649
     1650        - ``n`` - integer
     1651
     1652        OUTPUT: Maxima object
    13461653       
    13471654        .. note::
    13481655
     
    13511658       
    13521659        EXAMPLES::
    13531660       
    1354             sage: v = maxima('create_list(i*x^i,i,0,5)'); v   
     1661            sage: v = maxima('create_list(i*x^i,i,0,5)'); v
    13551662            [0,x,2*x^2,3*x^3,4*x^4,5*x^5]
    1356             sage: v[3]                                         
     1663            sage: v[3]
    13571664            3*x^3
    1358             sage: v[0]                                           
     1665            sage: v[0]
    13591666            0
    1360             sage: v[10]                                         
     1667            sage: v[10]
    13611668            Traceback (most recent call last):
    13621669            ...
    13631670            IndexError: n = (10) must be between 0 and 5
     
    13701677
    13711678    def __iter__(self):
    13721679        """
    1373         EXAMPLE::
     1680        Return an iterator for self.
     1681
     1682        INPUT: none
     1683
     1684        OUTPUT: iterator
     1685
     1686        EXAMPLES::
    13741687       
    13751688            sage: v = maxima('create_list(i*x^i,i,0,5)')
    13761689            sage: L = list(v)
     
    13831696    def subst(self, val):
    13841697        """
    13851698        Substitute a value or several values into this Maxima object.
     1699
     1700        INPUT:
     1701
     1702        - ``val`` - string representing substitution(s) to perform
     1703
     1704        OUTPUT: Maxima object
    13861705       
    13871706        EXAMPLES::
    13881707       
     
    13981717    def comma(self, args):
    13991718        """
    14001719        Form the expression that would be written 'self, args' in Maxima.
     1720
     1721        INPUT:
     1722
     1723        - ``args`` - string
     1724
     1725        OUTPUT: Maxima object
    14011726       
    14021727        EXAMPLES::
    14031728       
     
    14131738    def _latex_(self):
    14141739        """
    14151740        Return Latex representation of this Maxima object.
     1741
     1742        INPUT: none
     1743
     1744        OUTPUT: string
    14161745       
    14171746        This calls the tex command in Maxima, then does a little
    14181747        post-processing to fix bugs in the resulting Maxima output.
     
    14381767        P = self.parent()
    14391768        s = P._eval_line('tex(%s);'%self.name(), reformat=False)
    14401769        if not '$$' in s:
    1441             raise RuntimeError, "Error texing maxima object."
     1770            raise RuntimeError, "Error texing Maxima object."
    14421771        i = s.find('$$')
    14431772        j = s.rfind('$$')
    14441773        s = s[i+2:j]
    14451774        s = multiple_replace({'\r\n':' ',
    1446                               '\\%':'', 
     1775                              '\\%':'',
    14471776                              '\\arcsin ':'\\sin^{-1} ',
    14481777                              '\\arccos ':'\\cos^{-1} ',
    14491778                              '\\arctan ':'\\tan^{-1} '}, s)
     
    14621791    def trait_names(self, verbose=False):
    14631792        """
    14641793        Return all Maxima commands, which is useful for tab completion.
     1794
     1795        INPUT:
     1796       
     1797        - ``verbose`` - boolean
     1798
     1799        OUTPUT: list of strings
    14651800       
    14661801        EXAMPLES::
    14671802       
     
    14761811        If self is a Maxima matrix, return the corresponding Sage matrix
    14771812        over the Sage ring `R`.
    14781813       
     1814        INPUT:
     1815
     1816        - ``R`` - ring to coerce into
     1817
     1818        OUTPUT: matrix
     1819       
    14791820        This may or may not work depending in how complicated the entries
    14801821        of self are! It only works if the entries of self can be coerced as
    14811822        strings to produce meaningful elements of `R`.
    14821823       
    14831824        EXAMPLES::
    14841825       
    1485             sage: _ = maxima.eval("f[i,j] := i/j")             
    1486             sage: A = maxima('genmatrix(f,4,4)'); A             
     1826            sage: _ = maxima.eval("f[i,j] := i/j")
     1827            sage: A = maxima('genmatrix(f,4,4)'); A
    14871828            matrix([1,1/2,1/3,1/4],[2,1,2/3,1/2],[3,3/2,1,3/4],[4,2,4/3,1])
    1488             sage: A._matrix_(QQ)                               
     1829            sage: A._matrix_(QQ)
    14891830            [  1 1/2 1/3 1/4]
    14901831            [  2   1 2/3 1/2]
    14911832            [  3 3/2   1 3/4]
     
    15171858        """
    15181859        Return the partial fraction decomposition of self with respect to
    15191860        the variable var.
     1861
     1862        INPUT:
     1863
     1864        - ``var`` - string
     1865
     1866        OUTPUT: Maxima object
    15201867       
    15211868        EXAMPLES::
    15221869       
    1523             sage: f = maxima('1/((1+x)*(x-1))')           
    1524             sage: f.partial_fraction_decomposition('x')   
     1870            sage: f = maxima('1/((1+x)*(x-1))')
     1871            sage: f.partial_fraction_decomposition('x')
    15251872            1/(2*(x-1))-1/(2*(x+1))
    15261873            sage: print f.partial_fraction_decomposition('x')
    15271874                                 1           1
     
    15321879
    15331880    def _operation(self, operation, right):
    15341881        r"""
     1882        Return the result of "self operation right" in Maxima.
     1883
     1884        INPUT:
     1885
     1886        - ``operation`` - string; operator
     1887
     1888        - ``right`` - Maxima object; right operand
     1889
     1890        OUTPUT: Maxima object
     1891
    15351892        Note that right's parent should already be Maxima since this should
    15361893        be called after coercion has been performed.
    15371894       
     
    15681925
    15691926
    15701927class MaximaAbstractElementFunction(MaximaAbstractElement):
     1928    r"""
     1929    Create a Maxima function with the parent ``parent``,
     1930    name ``name``, definition ``defn``, arguments ``args``
     1931    and latex representation ``latex``.
     1932
     1933    INPUT:
     1934
     1935    - ``parent`` - an instance of a concrete Maxima interface
     1936
     1937    - ``name`` - string
     1938
     1939    - ``defn`` - string
     1940
     1941    - ``args`` - string; comma separated names of arguments
     1942
     1943    - ``latex`` - string
     1944
     1945    OUTPUT: Maxima function
     1946
     1947    EXAMPLES::
     1948       
     1949        sage: maxima.function('x,y','e^cos(x)')
     1950        e^cos(x)
     1951    """
     1952
    15711953    def __init__(self, parent, name, defn, args, latex):
    15721954        """
    1573         EXAMPLES::
    1574        
     1955        Create a Maxima function.
     1956        See ``MaximaAbstractElementFunction`` for full documentation.
     1957
     1958        TESTS::
     1959
     1960            sage: from sage.interfaces.maxima_abstract import MaximaAbstractElementFunction
     1961            sage: MaximaAbstractElementFunction == loads(dumps(MaximaAbstractElementFunction))
     1962            True
    15751963            sage: f = maxima.function('x,y','sin(x+y)')
    15761964            sage: f == loads(dumps(f))
    15771965            True
     
    15831971
    15841972    def __reduce__(self):
    15851973        """
     1974        Implement __reduce__ for ``MaximaAbstractElementFunction``.
     1975
     1976        INPUT: none
     1977
     1978        OUTPUT:
     1979
     1980        A couple consisting of:
     1981
     1982        - the function to call for unpickling
     1983       
     1984        - a tuple of arguments for the function
     1985
    15861986        EXAMPLES::
    15871987       
    15881988            sage: f = maxima.function('x,y','sin(x+y)')
     
    15901990            (<function reduce_load_MaximaAbstract_function at 0x...>,
    15911991             (Maxima, 'sin(x+y)', 'x,y', None))
    15921992        """
    1593         return reduce_load_MaximaAbstract_function, (self.parent(), self.__defn, self.__args, self.__latex)
     1993        return reduce_load_MaximaAbstract_function, (self.parent(),
     1994                            self.__defn, self.__args, self.__latex)
    15941995       
    1595     def __call__(self, *x):
     1996    def __call__(self, *args):
    15961997        """
     1998        Return the result of calling this Maxima function
     1999        with the given arguments.
     2000
     2001        INPUT:
     2002
     2003        - ``args`` - a variable number of arguments
     2004
     2005        OUTPUT: Maxima object
     2006
    15972007        EXAMPLES::
    15982008       
    15992009            sage: f = maxima.function('x,y','sin(x+y)')
     
    16032013            sin(2*x)
    16042014        """
    16052015        P = self._check_valid()
    1606         if len(x) == 1:
    1607             x = '(%s)'%x
    1608         return P('%s%s'%(self.name(), x))
     2016        if len(args) == 1:
     2017            args = '(%s)'%args
     2018        return P('%s%s'%(self.name(), args))
    16092019
    16102020    def __repr__(self):
    16112021        """
     2022        Return print representation of this Maxima function.
     2023
     2024        INPUT: none
     2025
     2026        OUTPUT: string
     2027
    16122028        EXAMPLES::
    16132029       
    16142030            sage: f = maxima.function('x,y','sin(x+y)')
     
    16192035
    16202036    def _latex_(self):
    16212037        """
     2038        Return latex representation of this Maxima function.
     2039
     2040        INPUT: none
     2041
     2042        OUTPUT: string
     2043
    16222044        EXAMPLES::
    16232045       
    16242046            sage: f = maxima.function('x,y','sin(x+y)')
     
    16332055    def arguments(self, split=True):
    16342056        r"""
    16352057        Returns the arguments of this Maxima function.
     2058
     2059        INPUT:
     2060
     2061        - ``split`` - boolean; if True return a tuple of strings,
     2062          otherwise return a string of comma-separated arguments
     2063
     2064        OUTPUT:
     2065
     2066        - a string if ``split`` is False
     2067
     2068        - a list of strings if ``split`` is True
    16362069       
    16372070        EXAMPLES::
    16382071       
     
    16532086    def definition(self):
    16542087        """
    16552088        Returns the definition of this Maxima function as a string.
     2089
     2090        INPUT: none
     2091
     2092        OUTPUT: string
    16562093       
    16572094        EXAMPLES::
    16582095       
     
    16652102    def integral(self, var):
    16662103        """
    16672104        Returns the integral of self with respect to the variable var.
     2105
     2106        INPUT:
     2107
     2108        - ``var`` - a variable
     2109
     2110        OUTPUT: Maxima function
    16682111       
    16692112        Note that integrate is an alias of integral.
    16702113       
     
    16792122        """
    16802123        var = str(var)
    16812124        P = self._check_valid()
    1682         f = P('integrate(%s(%s), %s)'%(self.name(), self.arguments(split=False), var))
     2125        f = P('integrate(%s(%s), %s)'%(self.name(),
     2126                        self.arguments(split=False), var))
    16832127
    16842128        args = self.arguments()
    16852129        if var not in args:
     
    16922136        r"""
    16932137        This is a utility function which factors out much of the
    16942138        commonality used in the arithmetic operations for
    1695         ``MaximaFunctions``.
     2139        ``MaximaAbstractElementFunction``.
    16962140       
    16972141        INPUT:
    16982142       
    1699        
    1700         -  ``operation`` - A string representing the operation
     2143        - ``operation`` - A string representing the operation
    17012144           being performed. For example, '\*', or '1/'.
    17022145       
    1703         -  ``f`` - The other operand. If f is
    1704            ``None``, than the operation is assumed to be unary
     2146        - ``f`` - The other operand. If f is
     2147           ``None``, then the operation is assumed to be unary
    17052148           rather than binary.
    17062149       
    1707        
    17082150        EXAMPLES::
    17092151       
    17102152            sage: f = maxima.function('x,y','sin(x+y)')
     
    17332175
    17342176    def _add_(self, f):
    17352177        """
    1736         MaximaFunction as left summand.
     2178        This Maxima function as left summand.
    17372179       
    17382180        EXAMPLES::
    17392181       
     
    17502192            sage: (f+maxima.cos(x))(2)
    17512193            sin(2)+cos(2)
    17522194            sage: (f+maxima.cos(y)) # This is a function with only ONE argument!
    1753             cos(y)+sin(x) 
     2195            cos(y)+sin(x)
    17542196            sage: (f+maxima.cos(y))(2)
    17552197            cos(y)+sin(2)
    17562198       
     
    17612203            sage: g+f
    17622204            sin(x)-cos(x)
    17632205            sage: (g+f)(2) # The sum IS a function
    1764             sin(2)-cos(2) 
     2206            sin(2)-cos(2)
    17652207            sage: 2+f
    17662208            sin(x)+2
    17672209        """
     
    17692211
    17702212    def _sub_(self, f):
    17712213        r"""
    1772         ``MaximaFunction`` as minuend.
     2214        This Maxima function as minuend.
    17732215       
    17742216        EXAMPLES::
    17752217       
     
    17792221            sage: f-g
    17802222            sin(x)+cos(x)
    17812223            sage: (f-g)(2)
    1782             sin(2)+cos(2) 
     2224            sin(2)+cos(2)
    17832225            sage: (f-maxima.cos(y)) # This function only has the argument x!
    17842226            sin(x)-cos(y)
    17852227            sage: _(2)
    1786             sin(2)-cos(y) 
     2228            sin(2)-cos(y)
    17872229       
    17882230        ::
    17892231       
     
    17942236       
    17952237    def _mul_(self, f):
    17962238        r"""
    1797         ``MaximaFunction`` as left factor.
     2239        This Maxima function as left factor.
    17982240       
    17992241        EXAMPLES::
    18002242       
     
    18202262
    18212263    def _div_(self, f):
    18222264        r"""
    1823         ``MaximaFunction`` as dividend.
     2265        This Maxima function as dividend.
    18242266       
    18252267        EXAMPLES::
    18262268       
     
    18462288
    18472289    def __neg__(self):
    18482290        r"""
    1849         Additive inverse of a ``MaximaFunction``.
     2291        Additive inverse of this Maxima function.
    18502292       
    18512293        EXAMPLES::
    18522294       
     
    18582300
    18592301    def __inv__(self):
    18602302        r"""
    1861         Multiplicative inverse of a ``MaximaFunction``.
     2303        Multiplicative inverse of this Maxima function.
    18622304       
    18632305        EXAMPLES::
    18642306       
     
    18702312
    18712313    def __pow__(self,f):
    18722314        r"""
    1873         ``MaximaFunction`` raised to some power.
     2315        This Maxima function raised to some power.
    18742316       
    18752317        EXAMPLES::
    18762318       
     
    18902332
    18912333
    18922334def reduce_load_MaximaAbstract_function(parent, defn, args, latex):
     2335    r"""
     2336    Unpickle a Maxima function.
     2337
     2338    EXAMPLES::
     2339
     2340        sage: from sage.interfaces.maxima_abstract import reduce_load_MaximaAbstract_function
     2341        sage: f = maxima.function('x,y','sin(x+y)')
     2342        sage: _,args = f.__reduce__()
     2343        sage: g = reduce_load_MaximaAbstract_function(*args)
     2344        sage: g == f
     2345        True
     2346    """
    18932347    return parent.function(args, defn, defn, latex)
    18942348   
    18952349def maxima_version():
    18962350    """
     2351    Return Maxima version.
     2352
     2353    Currently this calls a new copy of Maxima.
     2354
    18972355    EXAMPLES::
    18982356   
    18992357        sage: from sage.interfaces.maxima_abstract import maxima_version
  • sage/interfaces/maxima_lib.py

    diff -r 1bd1f40c456f -r 88910e6cc47b sage/interfaces/maxima_lib.py
    a b  
    11r"""
    2 Interface to Maxima
     2Library interface to Maxima
    33
    44Maxima is a free GPL'd general purpose computer algebra system
    55whose development started in 1968 at MIT. It contains symbolic
     
    2626- William Stein (2006-02-24): *greatly* improved robustness by adding
    2727  sequence numbers to IO bracketing in _eval_line
    2828
    29 If the string "error" (case insensitive) occurs in the output of
    30 anything from Maxima, a RuntimeError exception is raised.
     29- Robert Bradshaw, Nils Bruin, Jean-Pierre Flori (2010,2011): Binary library
     30  interface
     31
     32For this interface, Maxima is loaded into ECL which is itself loaded
     33as a C library in Sage. Translations between Sage and Maxima objects
     34(which are nothing but wrappers to ECL objects) is made as much as possible
     35directly, but falls back to the string based conversion used by the
     36classical Maxima Pexpect interface in case no new implementation has been made.
     37
     38This interface is the one used for calculus by Sage
     39and is accessible as maxima_calculus::
     40
     41    sage: maxima_calculus
     42    Maxima_lib
     43
     44Only one instance of this interface can be instantiated,
     45so the user should not try to instantiate another one,
     46which is anyway set to raise an error::
     47
     48    sage: from sage.interfaces.maxima_lib import MaximaLib
     49    sage: MaximaLib()
     50    Traceback (most recent call last):
     51    ...
     52    RuntimeError: Maxima interface in library mode can only be instantiated once
    3153"""
    3254
    3355#*****************************************************************************
     
    4971
    5072from sage.libs.ecl import *
    5173
    52 from maxima_abstract import MaximaAbstract, MaximaAbstractFunction, MaximaAbstractElement, MaximaAbstractFunctionElement, MaximaAbstractElementFunction
     74from maxima_abstract import (MaximaAbstract, MaximaAbstractFunction,
     75  MaximaAbstractElement, MaximaAbstractFunctionElement,
     76  MaximaAbstractElementFunction)
    5377
    54 ## We begin here by initializing maxima in library mode
     78## We begin here by initializing Maxima in library mode
     79## i.e. loading it into ECL
    5580ecl_eval("(setf *load-verbose* NIL)")
    5681ecl_eval("(require 'maxima)")
    5782ecl_eval("(in-package :maxima)")
     
    6085ecl_eval("(set-locale-subdir)")
    6186ecl_eval("(set-pathnames)")
    6287ecl_eval("(defun add-lineinfo (x) x)")
    63 #the following is a direct adaption of the definition of "retrieve" in the Maxima file
    64 #macsys.lisp. This routine is normally responsible for displaying a question and
    65 #returning the answer. We change it to throw an error in which the text of the question
    66 #is included. We do this by running exactly the same code as in the original definition
    67 #of "retrieve", but with *standard-output* redirected to a string.
     88ecl_eval('(defun principal nil (error "Divergent Integral"))')
     89ecl_eval("(setf $errormsg nil)")
     90
     91# the following is a direct adaption of the definition of "retrieve"
     92# in the Maxima file macsys.lisp. This routine is normally responsible
     93# for displaying a question and returning the answer. We change it to
     94# throw an error in which the text of the question is included. We do
     95# this by running exactly the same code as in the original definition
     96# of "retrieve", but with *standard-output* redirected to a string.
    6897ecl_eval(r"""
    6998(defun retrieve (msg flag &aux (print? nil))
    7099  (declare (special msg flag print?))
    71100  (or (eq flag 'noprint) (setq print? t))
    72   (error 
    73       (concatenate 'string "Maxima asks: " 
    74       (string-trim '(#\Newline) 
     101  (error
     102      (concatenate 'string "Maxima asks: "
     103      (string-trim '(#\Newline)
    75104      (with-output-to-string (*standard-output*)
    76105      (cond ((not print?)
    77106             (setq print? t)
     
    100129)
    101130""")
    102131
    103 ecl_eval('(defparameter *dev-null* (make-two-way-stream (make-concatenated-stream) (make-broadcast-stream)))')
    104 ecl_eval('(defun principal nil (error "Divergent Integral"))')
    105 ecl_eval("(setf $errormsg nil)")
    106 
    107 #ecl_eval(r"(defun tex-derivative (x l r) (tex (if $derivabbrev (tex-dabbrev x) (tex-d x '\partial)) l r lop rop ))")
    108 
    109 #ecl_eval('(defun ask-evod (x even-odd)(error "Maxima asks a question"))')
    110 #ecl_eval('(defun ask-integerp (x)(error "Maxima asks a question"))')
    111 #ecl_eval('(defun ask-declare (x property)(error "Maxima asks a question"))')
    112 #ecl_eval('(defun ask-prop (object property fun-or-number)(error "Maxima asks a question"))')
    113 #ecl_eval('(defun asksign01 (a)(error "Maxima asks a question"))')
    114 #ecl_eval('(defun asksign (x)(error "Maxima asks a question"))')
    115 #ecl_eval('(defun asksign1 ($askexp)(error "Maxima asks a question"))')
    116 #ecl_eval('(defun ask-greateq (x y)(error "Maxima asks a question"))')
    117 #ecl_eval('(defun askinver (a)(error "Maxima asks a question"))')
    118 #ecl_eval('(defun npask (exp)(error "Maxima asks a question"))')
    119 
     132## Redirection of ECL and Maxima stdout to /dev/null
     133ecl_eval(r"""(defparameter *dev-null* (make-two-way-stream
     134              (make-concatenated-stream) (make-broadcast-stream)))""")
    120135ecl_eval("(setf original-standard-output *standard-output*)")
    121136ecl_eval("(setf *standard-output* *dev-null*)")
    122137#ecl_eval("(setf *error-output* *dev-null*)")
    123138
     139## Default options set in Maxima
    124140# display2d -- no ascii art output
    125141# keepfloat -- don't automatically convert floats to rationals
    126 init_code = ['display2d : false', 'domain : complex', 'keepfloat : true', 'load(to_poly_solver)', 'load(simplify_sum)']
     142init_code = ['display2d : false', 'domain : complex', 'keepfloat : true',
     143            'load(to_poly_solver)', 'load(simplify_sum)']
    127144# Turn off the prompt labels, since computing them *very
    128145# dramatically* slows down the maxima interpret after a while.
    129146# See the function makelabel in suprv1.lisp.
    130147# Many thanks to andrej.vodopivec@gmail.com and also
    131148# Robert Dodier for figuring this out!
    132 # See trac # 6818. 
     149# See trac # 6818.
    133150init_code.append('nolabels : true')
    134151for l in init_code:
    135152    ecl_eval("#$%s$"%l)
     
    137154## should allow to do this through a method
    138155#ecl_eval("(setf *standard-output* original-standard-output)")
    139156
     157## This is the main function (ECL object) used for evaluation
    140158# This returns an EclObject
    141159maxima_eval=ecl_eval("""
    142160(defun maxima-eval( form )
     
    150168            ((eq result 'maxima-error)
    151169                (let ((the-jig (process-error-argl (cddr $error))))
    152170                    (mapc #'set (car the-jig) (cadr the-jig))
    153                     (error (concatenate 'string "Error executing code in Maxima: "
    154                        (with-output-to-string (stream)
    155                            (apply #'mformat stream (cadr $error) (caddr the-jig)))))
     171                    (error (concatenate 'string
     172                        "Error executing code in Maxima: "
     173                        (with-output-to-string (stream)
     174                           (apply #'mformat stream (cadr $error)
     175                             (caddr the-jig)))))
    156176                ))
    157             (t 
     177            (t
    158178                (let ((the-jig (process-error-argl (cddr $error))))
    159179                    (mapc #'set (car the-jig) (cadr the-jig))
    160                     (error (concatenate 'string "Maxima condition. result:" (princ-to-string result) "$error:"
    161                        (with-output-to-string (stream)
    162                            (apply #'mformat stream (cadr $error) (caddr the-jig)))))
     180                    (error (concatenate 'string "Maxima condition. result:"
     181                        (princ-to-string result) "$error:"
     182                        (with-output-to-string (stream)
     183                            (apply #'mformat stream (cadr $error)
     184                              (caddr the-jig)))))
    163185                ))
    164186        )
    165187    )
    166188)
    167189""")
    168190
     191## Number of instances of this interface
    169192maxima_lib_instances = 0
    170193
     194## Here we define several useful ECL/Maxima objects
    171195# The Maxima string function can change the structure of its input
    172196#maxprint=EclObject("$STRING")
    173 maxprint=EclObject("(defun mstring-for-sage (form) (coerce (mstring form) 'string))").eval()
     197maxprint=EclObject(r"""(defun mstring-for-sage (form)
     198                         (coerce (mstring form) 'string))""").eval()
    174199meval=EclObject("MEVAL")
    175200msetq=EclObject("MSETQ")
    176201mlist=EclObject("MLIST")
     
    189214max_to_poly_solve=EclObject("$TO_POLY_SOLVE")
    190215
    191216def stdout_to_string(s):
    192     return ecl_eval("(with-output-to-string (*standard-output*) (maxima-eval #$%s$))"%s).python()[1:-1]
     217    r"""
     218    Evaluate command ``s`` and catch Maxima stdout
     219    (not the result of the command!) into a string.
     220
     221    INPUT:
     222
     223    - ``s`` - string; command to evaluate
     224
     225    OUTPUT: string
     226
     227    This is currently used to implement display2d.
     228
     229    EXAMPLES::
     230   
     231        sage: from sage.interfaces.maxima_lib import stdout_to_string
     232        sage: stdout_to_string('1+1')
     233        ''
     234        sage: stdout_to_string('disp(1+1)')
     235        '2\n\n'
     236    """
     237    return ecl_eval(r"""(with-output-to-string (*standard-output*)
     238                          (maxima-eval #$%s$))"""%s).python()[1:-1]
    193239
    194240def max_to_string(s):
    195      return maxprint(s).python()[1:-1]
     241    r"""
     242    Return the Maxima string corresponding to this ECL object.
     243
     244    INPUT:
     245
     246    - ``s`` - ECL object
     247
     248    OUTPUT: string
     249
     250    EXAMPLES::
     251
     252        sage: from sage.interfaces.maxima_lib import maxima_lib, max_to_string
     253        sage: ecl = maxima_lib(cos(x)).ecl()
     254        sage: max_to_string(ecl)
     255        'cos(x)'
     256    """
     257    return maxprint(s).python()[1:-1]
    196258
    197259my_mread=ecl_eval("""
    198260(defun my-mread (cmd)
    199261  (caddr (mread (make-string-input-stream cmd))))
    200262""")
    201263
    202 def parse_max_string(l):
    203   return my_mread('"%s;"'%l)
     264def parse_max_string(s):
     265    r"""
     266    Evaluate string in Maxima without *any* further simplification.
     267
     268    INPUT:
     269
     270    - ``s`` - string
     271
     272    OUTPUT: ECL object
     273
     274    EXAMPLES::
     275
     276        sage: from sage.interfaces.maxima_lib import parse_max_string
     277        sage: parse_max_string('1+1')
     278        <ECL: ((MPLUS) 1 1)>
     279    """
     280    return my_mread('"%s;"'%s)
    204281
    205282class MaximaLib(MaximaAbstract):
    206283    """
    207284    Interface to Maxima as a Library.
     285
     286    INPUT: none
     287
     288    OUTPUT: Maxima interface as a Library
     289
     290    EXAMPLES::
     291
     292        sage: from sage.interfaces.maxima_lib import MaximaLib, maxima_lib
     293        sage: isinstance(maxima_lib,MaximaLib)
     294        True
     295
     296    Only one such interface can be instantiated::
     297
     298        sage: MaximaLib()
     299        Traceback (most recent call last):
     300        ...
     301        RuntimeError: Maxima interface in library mode can only
     302        be instantiated once
    208303    """
    209304    def __init__(self):
    210305        """
    211306        Create an instance of the Maxima interpreter.
     307        See ``MaximaLib`` for full documentation.
    212308
    213309        TESTS::
    214310
    215             sage: from sage.interfaces.maxima_lib import maxima_lib
     311            sage: from sage.interfaces.maxima_lib import MaximaLib, maxima_lib
     312            sage: MaximaLib == loads(dumps(MaximaLib))
     313            True
    216314            sage: maxima_lib == loads(dumps(maxima_lib))
    217315            True
    218316
    219317        We make sure labels are turned off (see trac 6816)::
    220        
     318
    221319            sage: 'nolabels : true' in maxima_lib._MaximaLib__init_code
    222320            True
    223321        """
     
    229327        global init_code
    230328        self.__init_code = init_code
    231329
    232         ## The name should definitely be changed to maxima_lib, however much more changes are then needed elsewhere
    233         ## With maxima, more things are fine, but for example _maxima_init_ gets called in calculus.calculus and the classic interface gets initialized (not started, it is already initialized by default, so that is not really a big deal)
    234330        MaximaAbstract.__init__(self,"maxima_lib")
    235331        self.__seq = 0
    236  
     332
    237333    def _coerce_from_special_method(self, x):
     334        r"""
     335        Coerce ``x`` into self trying to call a special underscore method.
     336
     337        INPUT:
     338
     339        - ``x`` - object to coerce into self
     340
     341        OUTPUT: Maxima element equivalent to ``x``
     342
     343        EXAMPLES::
     344
     345            sage: from sage.interfaces.maxima_lib import maxima_lib
     346            sage: xmax = maxima_lib._coerce_from_special_method(x)
     347            sage: type(xmax)
     348            <class 'sage.interfaces.maxima_lib.MaximaLibElement'>
     349        """
    238350        if isinstance(x, EclObject):
    239351            return MaximaLibElement(self,self._create(x))
    240352        else:
    241353            return MaximaAbstract._coerce_from_special_method(self,x)
     354
     355    def __reduce__(self):
     356        r"""
     357        Implement __reduce__ for ``MaximaLib``.
     358
     359        INPUT: none
     360
     361        OUTPUT:
     362
     363        A couple consisting of:
     364
     365        - the function to call for unpickling
    242366       
    243     def __reduce__(self):
    244         """
     367        - a tuple of arguments for the function
     368
    245369        EXAMPLES::
    246370       
    247371            sage: from sage.interfaces.maxima_lib import maxima_lib
     
    251375        return reduce_load_MaximaLib, tuple([])
    252376
    253377    # This outputs a string
    254     def eval(self, line, locals=None, reformat=True, **kwds):
     378    def _eval_line(self, line, locals=None, reformat=True, **kwds):
     379        r"""
     380        Evaluate the line in Maxima.
     381
     382        INPUT:
     383
     384        - ``line`` - string; text to evaluate
     385       
     386        - ``locals`` - None (ignored); this is used for compatibility with the
     387          Sage notebook's generic system interface.
     388       
     389        - ``reformat`` - boolean; whether to strip output or not
     390
     391        - ``**kwds`` - All other arguments are currently ignored.
     392
     393        OUTPUT: string representing Maxima output
     394
     395        EXAMPLES::
     396
     397            sage: from sage.interfaces.maxima_lib import maxima_lib
     398            sage: maxima_lib._eval_line('1+1')
     399            '2'
     400            sage: maxima_lib._eval_line('1+1;')
     401            '2'
     402            sage: maxima_lib._eval_line('1+1$')
     403            ''
     404            sage: maxima_lib._eval_line('randvar : cos(x)+sin(y)$')
     405            ''
     406            sage: maxima_lib._eval_line('randvar')
     407            'sin(y)+cos(x)'
     408        """
    255409        result = ''
    256410        while line:
    257411            ind_dollar=line.find("$")
     
    272426            return result
    273427        return ''.join([x.strip() for x in result.split()])
    274428
    275     _eval_line = eval
     429    eval = _eval_line
    276430
    277431    ###########################################
    278     # Direct access to underlying lisp interpreter. 
     432    # Direct access to underlying lisp interpreter.
    279433    ###########################################
    280434    def lisp(self, cmd):
    281435        """
    282436        Send a lisp command to maxima.
    283437       
     438        INPUT:
     439
     440        - ``cmd`` - string
     441
     442        OUTPUT: ECL object
     443
    284444        .. note::
    285445
    286446           The output of this command is very raw - not pretty.
     
    299459       
    300460        INPUT:
    301461       
    302        
    303462        -  ``var`` - string
    304463       
    305464        -  ``value`` - string
    306        
     465
     466        OUTPUT: none
    307467       
    308468        EXAMPLES::
    309469       
     
    321481        """
    322482        Clear the variable named var.
    323483
     484        INPUT:
     485
     486        - ``var`` - string
     487
     488        OUTPUT: none
     489
    324490        EXAMPLES::
    325491
    326492            sage: from sage.interfaces.maxima_lib import maxima_lib
     
    339505    def get(self, var):
    340506        """
    341507        Get the string value of the variable var.
     508
     509        INPUT:
     510
     511        - ``var`` - string
     512
     513        OUTPUT: string
    342514       
    343515        EXAMPLES::
    344516       
     
    349521        """
    350522        s = self.eval('%s;'%var)
    351523        return s
    352  
     524
    353525    def _create(self, value, name=None):
     526        r"""
     527        Create a variable with given value and name.
     528
     529        INPUT:
     530
     531        - ``value`` - string or ECL object
     532
     533        - ``name`` - string (default: None); name to use for the variable,
     534          an automatically generated name is used if this is none
     535
     536        OUTPUT:
     537
     538        - string; the name of the created variable
     539
     540        EXAMPLES:
     541
     542        Creation from strings::
     543
     544            sage: from sage.interfaces.maxima_lib import maxima_lib
     545            sage: maxima_lib._create('3','var3')
     546            'var3'
     547            sage: maxima_lib.get('var3')
     548            '3'
     549            sage: s = maxima_lib._create('3')
     550            sage: s # random output
     551            'sage9'
     552            sage: s[:4] == 'sage'
     553            True
     554
     555        And from ECL object::
     556
     557            sage: c = maxima_lib(x+cos(19)).ecl()
     558            sage: maxima_lib._create(c,'m')
     559            'm'
     560            sage: maxima_lib.get('m')
     561            'x+cos(19)'
     562        """
    354563        name = self._next_var_name() if name is None else name
    355564        if isinstance(value,EclObject):
    356565            maxima_eval([[msetq],cadadr("#$%s$#$"%name),value])
     
    359568        return name
    360569
    361570    def _function_class(self):
    362         """
     571        r"""
     572        Return the Python class of Maxima functions.
     573
     574        INPUT: none
     575       
     576        OUTPUT: type
     577
    363578        EXAMPLES::
    364579       
    365580            sage: from sage.interfaces.maxima_lib import maxima_lib
     
    369584        return MaximaLibFunction
    370585
    371586    def _object_class(self):
    372         """
     587        r"""
    373588        Return the Python class of Maxima elements.
     589
     590        INPUT: none
     591       
     592        OUTPUT: type
    374593       
    375594        EXAMPLES::
    376595       
     
    381600        return MaximaLibElement
    382601
    383602    def _function_element_class(self):
    384         """     
     603        r"""
     604        Return the Python class of Maxima functions of elements.
     605
     606        INPUT: none
     607       
     608        OUTPUT: type
     609
    385610        EXAMPLES::
    386611       
    387612            sage: from sage.interfaces.maxima_lib import maxima_lib
     
    391616        return MaximaLibFunctionElement
    392617
    393618    def _object_function_class(self):
    394         """
     619        r"""
     620        Return the Python class of Maxima user-defined functions.
     621
     622        INPUT: none
     623       
     624        OUTPUT: type
     625
    395626        EXAMPLES::
    396627       
    397628            sage: from sage.interfaces.maxima_lib import maxima_lib
     
    400631        """
    401632        return MaximaLibElementFunction
    402633
    403     ##some helper functions to wrap the calculus use of the maxima interface.
    404     ##these routines expect arguments living in the symbolic ring and return something
    405     ##that is hopefully coercible into the symbolic ring again.
     634    ## some helper functions to wrap the calculus use of the maxima interface.
     635    ## these routines expect arguments living in the symbolic ring
     636    ## and return something that is hopefully coercible into the symbolic
     637    ## ring again.
    406638
    407639    def sr_integral(self,*args):
    408640        """
     
    414646            sage: integrate(1/(x^3 *(a+b*x)^(1/3)),x)
    415647            Traceback (most recent call last):
    416648            ...
    417             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)
     649            ValueError: Computation failed since Maxima requested additional
     650            constraints; using the 'assume' command before integral evaluation
     651            *may* help (example of legal syntax is 'assume(a>0)', see
     652            `assume?` for more details)
    418653            Is  a  positive or negative?
    419654            sage: assume(a>0)
    420655            sage: integrate(1/(x^3 *(a+b*x)^(1/3)),x)
     
    424659            sage: integral(x^n,x)
    425660            Traceback (most recent call last):
    426661            ...
    427             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)
     662            ValueError: Computation failed since Maxima requested additional
     663            constraints; using the 'assume' command before integral evaluation
     664            *may* help (example of legal syntax is 'assume(n+1>0)',
     665            see `assume?` for more details)
    428666            Is  n+1  zero or nonzero?
    429667            sage: assume(n+1>0)
    430668            sage: integral(x^n,x)
     
    462700            sage: sum(a*q^k, k, 0, oo)
    463701            Traceback (most recent call last):
    464702            ...
    465             ValueError: Computation failed since Maxima requested additional constraints; using the 'assume' command before summation *may* help (example of legal syntax is 'assume(abs(q)-1>0)', see `assume?` for more details)
     703            ValueError: Computation failed since Maxima requested additional
     704            constraints; using the 'assume' command before summation *may* help
     705            (example of legal syntax is 'assume(abs(q)-1>0)', see `assume?`
     706            for more details)
    466707            Is  abs(q)-1  positive, negative, or zero?
    467708            sage: assume(q > 1)
    468709            sage: sum(a*q^k, k, 0, oo)
     
    482723        except RuntimeError, error:
    483724            s = str(error)
    484725            if "divergent" in s:
    485 # in pexpect interface, one looks for this - could not find an example where 'Pole encountered' occurred, though
     726# in pexpect interface, one looks for this;
     727# could not find an example where 'Pole encountered' occurred, though
    486728#            if "divergent" in s or 'Pole encountered' in s:
    487729                raise ValueError, "Sum is divergent."
    488730            elif "Is" in s: # Maxima asked for a condition
     
    506748            7776/3125
    507749            sage: limit(f,x = 1.2)
    508750            2.06961575467...
    509             sage: var('a')   
     751            sage: var('a')
    510752            a
    511753            sage: limit(x^a,x=0)
    512754            Traceback (most recent call last):
    513755            ...
    514             ValueError: Computation failed since Maxima requested additional constraints; using the 'assume' command before limit evaluation *may* help (see `assume?` for more details)
     756            ValueError: Computation failed since Maxima requested additional
     757            constraints; using the 'assume' command before limit evaluation
     758            *may* help (see `assume?` for more details)
    515759            Is  a  positive, negative, or zero?
    516760            sage: assume(a>0)
    517761            sage: limit(x^a,x=0)
    518762            Traceback (most recent call last):
    519763            ...
    520             ValueError: Computation failed since Maxima requested additional constraints; using the 'assume' command before limit evaluation *may* help (see `assume?` for more details)
    521             Is a an integer?
     764            ValueError: Computation failed since Maxima requested additional
     765            constraints; using the 'assume' command before limit evaluation
     766            *may* help (see `assume?` for more details)
     767            Is a an integer?
    522768            sage: assume(a,'integer')
    523769            sage: assume(a,'even')  # Yes, Maxima will ask this too
    524770            sage: limit(x^a,x=0)
     
    562808
    563809
    564810def is_MaximaLibElement(x):
    565     """
     811    r"""
    566812    Returns True if x is of type MaximaLibElement.
    567813   
    568814    EXAMPLES::
     
    577823    return isinstance(x, MaximaLibElement)
    578824
    579825class MaximaLibElement(MaximaAbstractElement):
     826    r"""
     827    Element of Maxima through library interface.
     828
     829    EXAMPLES:
     830
     831    Elements of this class should not be created directly.
     832    The targeted parent should be used instead::
     833
     834        sage: from sage.interfaces.maxima_lib import maxima_lib
     835        sage: maxima_lib(4)
     836        4
     837        sage: maxima_lib(log(x))
     838        log(x)
    580839    """
    581     """   
     840
    582841    def ecl(self):
     842        r"""
     843        Return the underlying ECL object of this MaximaLib object.
     844
     845        INPUT: none
     846
     847        OUTPUT: ECL object
     848
     849        EXAMPLES::
     850
     851            sage: from sage.interfaces.maxima_lib import maxima_lib
     852            sage: maxima_lib(x+cos(19)).ecl()
     853            <ECL: ((MPLUS SIMP) ((%COS SIMP) 19) $X)>
     854        """
    583855        try:
    584856            return self._ecl
    585857        except AttributeError:
    586858            self._ecl=maxima_eval("#$%s$"%self._name)
    587859            return self._ecl
    588            
     860
    589861    def to_poly_solve(self,vars,options=""):
     862        r"""
     863        Use Maxima's to_poly_solver package.
     864
     865        INPUT:
     866
     867        - ``vars`` - symbolic expressions
     868
     869        - ``options`` - string (default="")
     870
     871        OUTPUT: Maxima object
     872
     873        EXAMPLES::
     874
     875            sage: from sage.interfaces.maxima_lib import maxima_lib
     876            sage: sol = maxima_lib(sin(x) == 0).to_poly_solve(x)
     877            sage: sol.sage()
     878            [[x == pi + 2*pi*z6], [x == 2*pi*z8]]
     879        """
    590880        if options.find("use_grobner=true") != -1:
    591881            cmd=EclObject([[max_to_poly_solve], self.ecl(), sr_to_max(vars),
    592882                                             [[mequal],max_use_grobner,True]])
     
    595885        return self.parent()(maxima_eval(cmd))
    596886
    597887    def display2d(self, onscreen=True):
    598         """
     888        r"""
     889        Return the 2d representation of this Maxima object.
     890
     891        INPUT:
     892
     893        - ``onscreen`` - boolean (default: True); whether to print or return
     894
     895        OUTPUT:
     896
     897        The representation is printed if onscreen is set to True
     898        and returned as a string otherwise.
     899
    599900        EXAMPLES::
    600901       
    601902            sage: from sage.interfaces.maxima_lib import maxima_lib
    602             sage: F = maxima_lib('x^5 - y^5').factor() 
    603             sage: F.display2d ()             
     903            sage: F = maxima_lib('x^5 - y^5').factor()
     904            sage: F.display2d()
    604905                                   4      3    2  2    3      4
    605906                       - (y - x) (y  + x y  + x  y  + x  y + x )
    606907        """
     
    638939
    639940
    640941def reduce_load_MaximaLib():
    641     """
     942    r"""
     943    Unpickle the (unique) Maxima library interface.
     944
    642945    EXAMPLES::
    643946   
    644947        sage: from sage.interfaces.maxima_lib import reduce_load_MaximaLib
     
    647950    """
    648951    return maxima_lib
    649952
    650 #**********************************
    651 # ???
    652953
     954#############################################
     955# Smart translations between SR and Maxima
     956#############################################
     957
     958import sage.rings.real_double
    653959import sage.symbolic.expression
    654960import sage.functions.trig
    655961import sage.functions.log
     
    667973cadadr=EclObject("cadadr")
    668974meval=EclObject("meval")
    669975NIL=EclObject("NIL")
    670 ratdisrep=EclObject("ratdisrep")
    671976
     977## Dictionaries for standard operators
    672978sage_op_dict = {
    673979    sage.symbolic.expression.operator.abs : "MABS",
    674980    sage.symbolic.expression.operator.add : "MPLUS",
     
    7071013sage_op_dict = dict([(k,EclObject(sage_op_dict[k])) for k in sage_op_dict])
    7081014max_op_dict = dict([(sage_op_dict[k],k) for k in sage_op_dict])
    7091015
     1016
     1017## Here we correct the dictionaries for some simple operators
    7101018def add_vararg(*args):
     1019    r"""
     1020    Addition of a variable number of arguments.
     1021
     1022    INPUT:
     1023   
     1024    - ``args`` - arguments to add
     1025
     1026    OUTPUT: sum of arguments
     1027
     1028    EXAMPLES::
     1029
     1030        sage: from sage.interfaces.maxima_lib import add_vararg
     1031        sage: add_vararg(1,2,3,4,5,6,7)
     1032        28
     1033    """
    7111034    S=0
    7121035    for a in args:
    7131036        S=S+a
    7141037    return S
    7151038
    7161039def mul_vararg(*args):
     1040    r"""
     1041    Multiplication of a variable number of arguments.
     1042
     1043    INPUT:
     1044   
     1045    - ``args`` - arguments to multiply
     1046
     1047    OUTPUT: product of arguments
     1048
     1049    EXAMPLES::
     1050
     1051        sage: from sage.interfaces.maxima_lib import mul_vararg
     1052        sage: mul_vararg(9,8,7,6,5,4)
     1053        60480
     1054    """
    7171055    P=1
    7181056    for a in args:
    7191057        P=P*a
    7201058    return P
    7211059
    7221060def sage_rat(x,y):
     1061    r"""
     1062    Return quotient x/y.
     1063
     1064    INPUT:
     1065
     1066    - ``x`` - integer
     1067
     1068    - ``y`` - integer
     1069
     1070    OUTPUT: rational
     1071
     1072    EXAMPLES::
     1073
     1074        sage: from sage.interfaces.maxima_lib import sage_rat
     1075        sage: sage_rat(1,7)
     1076        1/7
     1077    """
    7231078    return x/y
    7241079
    7251080mplus=EclObject("MPLUS")
    7261081mtimes=EclObject("MTIMES")
    727 mdiff=EclObject("%DERIVATIVE")
    7281082rat=EclObject("RAT")
    729 max_i=EclObject("$%I")
    7301083max_op_dict[mplus]=add_vararg
    7311084max_op_dict[mtimes]=mul_vararg
    7321085max_op_dict[rat]=sage_rat
     1086
     1087
     1088## Here we build dictionaries for operators needing special conversions.
     1089ratdisrep=EclObject("ratdisrep")
     1090mrat=EclObject("MRAT")
    7331091mqapply=EclObject("MQAPPLY")
    7341092max_li=EclObject("$LI")
    7351093max_psi=EclObject("$PSI")
    7361094max_array=EclObject("ARRAY")
     1095mdiff=EclObject("%DERIVATIVE")
    7371096max_gamma_incomplete=sage_op_dict[sage.functions.other.gamma_inc]
    7381097
    7391098def mrat_to_sage(expr):
    7401099    r"""
    741     Convert a maxima MRAT expression to Sage SR
     1100    Convert a Maxima MRAT expression to Sage SR.
    7421101   
    743     Maxima has an optimised representation for multivariate rational expressions.
    744     The easiest way to translate those to SR is by first asking maxima to give
    745     the generic representation of the object. That is what RATDISREP does in
    746     maxima.
     1102    INPUT:
     1103
     1104    - ``expr`` - ECL object; a Maxima MRAT expression
     1105
     1106    OUTPUT: symbolic expression
     1107
     1108    Maxima has an optimised representation for multivariate
     1109    rational expressions. The easiest way to translate those
     1110    to SR is by first asking Maxima to give the generic representation
     1111    of the object. That is what RATDISREP does in Maxima.
     1112
     1113    EXAMPLES::
     1114
     1115        sage: from sage.interfaces.maxima_lib import maxima_lib, mrat_to_sage
     1116        sage: var('x y z')
     1117        (x, y, z)
     1118        sage: c = maxima_lib((x+y^2+z^9)/x^6+z^8/y).rat()
     1119        sage: c
     1120        (y*z^9+x^6*z^8+y^3+x*y)/(x^6*y)
     1121        sage: c.ecl()
     1122        <ECL: ((MRAT SIMP ($X $Y $Z)
     1123        ...>
     1124        sage: mrat_to_sage(c.ecl())
     1125        (x^6*z^8 + y*z^9 + y^3 + x*y)/(x^6*y)
    7471126    """
    7481127    return max_to_sr(meval(EclObject([[ratdisrep],expr])))
    7491128
    7501129def mqapply_to_sage(expr):
    7511130    r"""
    752     Special conversion rule for MQAPPLY expressions
     1131    Special conversion rule for MQAPPLY expressions.
     1132
     1133    INPUT:
     1134
     1135    - ``expr`` - ECL object; a Maxima MQAPPLY expression
     1136
     1137    OUTPUT: symbolic expression
     1138
     1139    MQAPPLY is used for function as li[x](y) and psi[x](y).
     1140
     1141    EXAMPLES::
     1142
     1143        sage: from sage.interfaces.maxima_lib import maxima_lib, mqapply_to_sage
     1144        sage: c = maxima_lib('li[2](3)')
     1145        sage: c.ecl()
     1146        <ECL: ((MQAPPLY SIMP) (($LI SIMP ARRAY) 2) 3)>
     1147        sage: mqapply_to_sage(c.ecl())
     1148        polylog(2, 3)
    7531149    """
    7541150    if caaadr(expr) == max_li:
    755         return sage.functions.log.polylog(max_to_sr(cadadr(expr)),max_to_sr(caddr(expr)))
     1151        return sage.functions.log.polylog(max_to_sr(cadadr(expr)),
     1152                                           max_to_sr(caddr(expr)))
    7561153    if caaadr(expr) == max_psi:
    757         return sage.functions.other.psi(max_to_sr(cadadr(expr)),max_to_sr(caddr(expr)))
     1154        return sage.functions.other.psi(max_to_sr(cadadr(expr)),
     1155                                         max_to_sr(caddr(expr)))
    7581156    else:
    7591157        op=max_to_sr(cadr(expr))
    7601158        max_args=cddr(expr)
    7611159        args=[max_to_sr(a) for a in max_args]
    7621160        return op(*args)
    7631161
     1162def mdiff_to_sage(expr):
     1163    r"""
     1164    Special conversion rule for %DERIVATIVE expressions.
     1165
     1166    INPUT:
     1167
     1168    - ``expr`` - ECL object; a Maxima %DERIVATIVE expression
     1169
     1170    OUTPUT: symbolic expression
     1171
     1172    EXAMPLES::
     1173
     1174        sage: from sage.interfaces.maxima_lib import maxima_lib, mdiff_to_sage
     1175        sage: f = maxima_lib('f(x)').diff('x',4)
     1176        sage: f.ecl()
     1177        <ECL: ((%DERIVATIVE SIMP) (($F SIMP) $X) $X 4)>
     1178        sage: mdiff_to_sage(f.ecl())
     1179        D[0, 0, 0, 0](f)(x)
     1180    """
     1181    return max_to_sr(expr.cadr()).diff(*[max_to_sr(e) for e in expr.cddr()])
     1182
    7641183def dummy_integrate(expr):
    7651184    r"""
    766     we would like to simply tie maxima's integrate to sage.calculus.calculus.dummy_integrate, but we're being imported there so to avoid circularity we define it here.
     1185    We would like to simply tie Maxima's integrate to
     1186    sage.calculus.calculus.dummy_integrate, but we're being
     1187    imported there so to avoid circularity we define it here.
     1188
     1189    INPUT:
     1190
     1191    - ``expr`` - ECL object; a Maxima %INTEGRATE expression
     1192
     1193    OUTPUT: symbolic expression
     1194
     1195    EXAMPLES::
     1196        sage: from sage.interfaces.maxima_lib import maxima_lib, dummy_integrate
     1197        sage: f = maxima_lib('f(x)').integrate('x')
     1198        sage: f.ecl()
     1199        <ECL: ((%INTEGRATE SIMP) (($F SIMP) $X) $X)>
     1200        sage: dummy_integrate(f.ecl())
     1201        integrate(f(x), x)
     1202
     1203    ::
     1204        sage: f = maxima_lib('f(x)').integrate('x',0,10)
     1205        sage: f.ecl()
     1206        <ECL: ((%INTEGRATE SIMP) (($F SIMP) $X) $X 0 10)>
     1207        sage: dummy_integrate(f.ecl())
     1208        integrate(f(x), x, 0, 10)
    7671209    """
    7681210    args=[max_to_sr(a) for a in cdr(expr)]
    7691211    if len(args) == 4 :
    770         return sage.symbolic.integration.integral.definite_integral(*args, hold=True)
     1212        return sage.symbolic.integration.integral.definite_integral(*args,
     1213                                                                hold=True)
    7711214    else:
    772         return sage.symbolic.integration.integral.indefinite_integral(*args, hold=True)
     1215        return sage.symbolic.integration.integral.indefinite_integral(*args,
     1216                                                                  hold=True)
    7731217
    774 def mdiff_to_sage(expr):
    775     return max_to_sr(expr.cadr()).diff(*[max_to_sr(e) for e in expr.cddr()])
    776 
     1218## The dictionaries
    7771219special_max_to_sage={
    778     EclObject("MRAT") : mrat_to_sage,
     1220    mrat : mrat_to_sage,
    7791221    mqapply : mqapply_to_sage,
    780     EclObject("%INTEGRATE") : dummy_integrate,
    781     mdiff : mdiff_to_sage
     1222    mdiff : mdiff_to_sage,
     1223    EclObject("%INTEGRATE") : dummy_integrate
    7821224}
    7831225
    7841226special_sage_to_max={
     
    7881230    sage.functions.other.Ei : lambda X : [[max_gamma_incomplete], 0, X]
    7891231}
    7901232
     1233
     1234## Dictionaries for symbols
    7911235sage_sym_dict={}
    7921236max_sym_dict={}
    7931237
     1238
     1239## Generic conversion functions
     1240
     1241max_i=EclObject("$%I")
    7941242def pyobject_to_max(obj):
     1243    r"""
     1244    Convert a (simple) Python object into a Maxima object.
     1245
     1246    INPUT:
     1247
     1248    - ``expr`` - Python object
     1249
     1250    OUTPUT: ECL object
     1251
     1252    .. note::
     1253    This uses functions defined in sage.libs.ecl.
     1254
     1255    EXAMPLES::
     1256        sage: from sage.interfaces.maxima_lib import pyobject_to_max
     1257        sage: pyobject_to_max(4)
     1258        <ECL: 4>
     1259        sage: pyobject_to_max('z')
     1260        <ECL: Z>
     1261        sage: var('x')
     1262        x
     1263        sage: pyobject_to_max(x)
     1264        Traceback (most recent call last):
     1265        ...
     1266        TypeError: Unimplemented type for python_to_ecl
     1267    """
    7951268    if isinstance(obj,sage.rings.rational.Rational):
    7961269        return EclObject(obj) if (obj.denom().is_one()) else EclObject([[rat], obj.numer(),obj.denom()])
    7971270    elif isinstance(obj,sage.rings.number_field.number_field_element_quadratic.NumberFieldElement_quadratic) and obj.parent().defining_polynomial().list() == [1,0,1]:
     
    8021275# This goes from SR to EclObject
    8031276def sr_to_max(expr):
    8041277    r"""
     1278    Convert a symbolic expression into a Maxima object.
     1279
     1280    INPUT:
     1281
     1282    - ``expr`` - symbolic expression
     1283
     1284    OUTPUT: ECL object
     1285
     1286    EXAMPLES::
     1287        sage: from sage.interfaces.maxima_lib import sr_to_max
     1288        sage: var('x')
     1289        x
     1290        sage: sr_to_max(x)
     1291        <ECL: $X>
     1292        sage: sr_to_max(cos(x))
     1293        <ECL: ((%COS) $X)>
     1294        sage: f = function('f',x)
     1295        sage: sr_to_max(f.diff())
     1296        <ECL: ((%DERIVATIVE) (($F) $X) $X 1)>
    8051297    """
    8061298    global sage_op_dict, max_op_dict
    8071299    global sage_sym_dict, max_sym_dict
     
    8111303    if op:
    8121304        # Stolen from sage.symbolic.expression_conversion
    8131305        # Should be defined in a function and then put in special_sage_to_max
    814         # For that, we should change the API of the functions there (we need to have access to op, not only to expr.operands()
     1306        # For that, we should change the API of the functions there
     1307        # (we need to have access to op, not only to expr.operands()
    8151308        if isinstance(op, FDerivativeOperator):
    8161309            from sage.symbolic.ring import is_SymbolicVariable
    8171310            args = expr.operands()
     
    8221315            params = op.parameter_set()
    8231316            deriv_max = []
    8241317            [deriv_max.extend([sr_to_max(args[i]), EclObject(params.count(i))]) for i in set(params)]
    825             l = [mdiff,f]
     1318            l = [[mdiff],f]
    8261319            l.extend(deriv_max)
    8271320            return EclObject(l)
    8281321        elif (op in special_sage_to_max):
     
    8481341            return pyobject_to_max(expr.pyobject())
    8491342        except TypeError:
    8501343            return maxima(expr).ecl()
    851    
     1344
    8521345# This goes from EclObject to SR
    853 import sage.rings.real_double
     1346def max_to_sr(expr):
     1347    r"""
     1348    Convert a Maxima object into a symbolic expression.
    8541349
    855 def max_to_sr(expr):
     1350    INPUT:
     1351
     1352    - ``expr`` - ECL object
     1353
     1354    OUTPUT: symbolic expression
     1355
     1356    EXAMPLES::
     1357
     1358        sage: from sage.interfaces.maxima_lib import maxima_lib, max_to_sr
     1359        sage: f = maxima_lib('f(x)')
     1360        sage: f.ecl()
     1361        <ECL: (($F SIMP) $X)>
     1362        sage: max_to_sr(f.ecl())
     1363        f(x)
     1364
     1365    TESTS::
     1366
     1367        sage: from sage.interfaces.maxima_lib import sr_to_max, max_to_sr
     1368        sage: f = function('f',x).diff()
     1369        sage: bool(max_to_sr(sr_to_max(f)) == f)
     1370        True
     1371    """
    8561372    if expr.consp():
    8571373        op_max=caar(expr)
    8581374        if op_max in special_max_to_sage:
    8591375            return special_max_to_sage[op_max](expr)
    8601376        if not(op_max in max_op_dict):
    861             # This could be unsafe if the conversion to SR chenges the structure of expr
     1377            # This could be unsafe if the conversion to SR
     1378            # changes the structure of expr
    8621379            sage_expr=SR(maxima(expr))
    8631380            max_op_dict[op_max]=sage_expr.operator()
    8641381            sage_op_dict[sage_expr.operator()]=op_max
     
    8771394        if isinstance(e,float):
    8781395            return sage.rings.real_double.RealDoubleElement(e)
    8791396        return e
    880