Ticket #7377: trac_7377-doctests.patch

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

(Really) basic tests and doc for every functions in sage.interfaces.maxima*

  • sage/interfaces/expect.py

    # HG changeset patch
    # User Jean-Pierre Flori <flori@enst.fr>
    # Date 1299854441 -3600
    # Node ID 474b56e1b430940d79fd0c60964f2a6e892cf859
    # Parent  60b96545371000ca24cd8a7310fc83caeea6fa31
    Doctests.
    
    diff -r 60b965453710 -r 474b56e1b430 sage/interfaces/expect.py
    a b  
    11"""
    2 Common Interface Functionality
     2Common Interface Functionality through Pexpect
    33
    44See the examples in the other sections for how to use specific
    55interfaces. The interface classes all derive from the generic
     
    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/interface.py

    diff -r 60b965453710 -r 474b56e1b430 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 60b965453710 -r 474b56e1b430 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 interface
     30
     31This is the interface used by the maxima object::
     32
     33    sage: type(maxima)
     34    <class 'sage.interfaces.maxima.Maxima'>
     35
    2936If the string "error" (case insensitive) occurs in the output of
    3037anything from Maxima, a RuntimeError exception is raised.
    3138
     
    468475class Maxima(MaximaAbstract, Expect):
    469476    """
    470477    Interface to the Maxima interpreter.
     478
     479    EXAMPLES::
     480
     481        sage: m = Maxima()
     482        sage: m == maxima
     483        False
    471484    """
    472485    def __init__(self, script_subdirectory=None, logfile=None, server=None,
    473486                 init_code = None):
     
    567580
    568581    def __reduce__(self):
    569582        """
     583        Implementation of __reduce__ for ``Maxima``.
     584
    570585        EXAMPLES::
    571586       
    572587            sage: maxima.__reduce__()
     
    575590        return reduce_load_Maxima, tuple([])
    576591
    577592    def _sendline(self, str):
     593        """
     594        Send a string followed by a newline character.
     595
     596        EXAMPLES::
     597
     598            sage: maxima._sendline('t : 9;')
     599            sage: maxima.get('t')
     600            '9'
     601        """
    578602        self._sendstr(str)
    579603        os.write(self._expect.child_fd, os.linesep)
    580604
     
    671695    def _eval_line(self, line, allow_use_file=False,
    672696                   wait_for_prompt=True, reformat=True, error_check=True):
    673697        """
     698        Return result of line evaluation.
     699
    674700        EXAMPLES:
    675701       
    676702        We check that errors are correctly checked::
     
    794820            self.quit()
    795821
    796822    def _batch(self, s, batchload=True):
     823        """
     824        Call Maxima's batch or batchload command with a file containing the given string as argument.
     825
     826        EXAMPLES::
     827
     828            sage: maxima._batch('10003;')
     829            '...batchload...'
     830            sage: maxima._batch('10003;',batchload=False)
     831            '...batch...10003...'
     832        """
    797833        filename = '%s-%s'%(self._local_tmpfile(),randrange(2147483647))
    798834        F = open(filename, 'w')
    799835        F.write(s)
     
    815851        self._sendline(cmd)
    816852        self._expect_expr(s)
    817853        out = self._before()
    818         self._error_check(str, out)
     854        self._error_check(cmd, out)
    819855        os.unlink(filename)
    820856        return out
    821857
    822858    def _quit_string(self):
    823859        """
     860        Return string representation of quit command.
     861       
    824862        EXAMPLES::
    825863       
    826864            sage: maxima._quit_string()
     
    830868
    831869    def _crash_msg(self):
    832870        """
     871        Return string representation of crash message.
     872
    833873        EXAMPLES::
    834874       
    835875            sage: maxima._crash_msg()
     
    837877        """
    838878        print "Maxima crashed -- automatically restarting."
    839879
    840     def _error_check(self, str, out):
     880    def _error_check(self, cmd, out):
     881        """
     882        Check string for errors.
     883
     884        EXAMPLES::
     885       
     886            sage: maxima._error_check("1+1;","Principal Value")
     887            Traceback (most recent call last):
     888            ...
     889            TypeError: Error executing code in Maxima
     890            CODE:
     891                1+1;
     892            Maxima ERROR:
     893                Principal Value
     894        """
    841895        r = self._error_re
    842896        m = r.search(out)
    843897        if not m is None:
    844             self._error_msg(str, out)
     898            self._error_msg(cmd, out)
    845899           
    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);',''))
     900    def _error_msg(self, cmd, out):
     901        """
     902        Raise error with formated description.
     903
     904        EXAMPLES::
     905
     906            sage: maxima._error_msg("1+1;","Principal Value")
     907            Traceback (most recent call last):
     908            ...
     909            TypeError: Error executing code in Maxima
     910            CODE:
     911                1+1;
     912            Maxima ERROR:
     913                Principal Value
     914        """
     915        raise TypeError, "Error executing code in Maxima\nCODE:\n    %s\nMaxima ERROR:\n    %s"%(cmd, out.replace('-- an error.  To debug this try debugmode(true);',''))
    848916
    849917    ###########################################
    850918    # Direct access to underlying lisp interpreter.
    851919    ###########################################
    852920    def lisp(self, cmd):
    853921        """
    854         Send a lisp command to maxima.
     922        Send a lisp command to Maxima.
    855923       
    856924        .. note::
    857925
     
    878946       
    879947        INPUT:
    880948       
    881        
    882949        -  ``var`` - string
    883950       
    884951        -  ``value`` - string
     
    9351002
    9361003    def _function_class(self):
    9371004        """
     1005        Return the Python class of Maxima functions.
     1006
    9381007        EXAMPLES::
    9391008       
    9401009            sage: maxima._function_class()
     
    9541023        return MaximaElement
    9551024
    9561025    def _function_element_class(self):
    957         """     
     1026        """
     1027        Return the Python class of Maxima functions of elements.
     1028
    9581029        EXAMPLES::
    9591030       
    9601031            sage: maxima._function_element_class()
     
    9641035
    9651036    def _object_function_class(self):
    9661037        """
     1038        Return the Python class of Maxima user-defined functions.
     1039
    9671040        EXAMPLES::
    9681041       
    9691042            sage: maxima._object_function_class()
     
    9711044        """
    9721045        return MaximaElementFunction
    9731046
    974     ##some old helper functions to wrap the calculus use of the maxima interface.
     1047    ##some old helper functions to wrap the calculus use of the Maxima interface.
    9751048    ##these routines expect arguments living in the symbolic ring and return something
    9761049    ##that is hopefully coercible into the symbolic ring again.
    9771050##
     
    10061079    """
    10071080    return isinstance(x, MaximaElement)
    10081081
    1009 # Thanks to the MRO for multiple inheritance used by the Sage's Python , this should work as expected
     1082# Thanks to the MRO for multiple inheritance used by the Sage's Python, this should work as expected
    10101083class MaximaElement(MaximaAbstractElement, ExpectElement):
     1084    """
     1085    Maxima elements.
     1086
     1087    EXAMPLES:
     1088
     1089    Elements of this class should not be created directly.
     1090    The targeted parent should be used instead::
     1091
     1092        sage: maxima(3)
     1093        3
     1094        sage: maxima(cos(x)+e^234)
     1095        cos(x)+%e^234
     1096    """
    10111097    def __init__(self, parent, value, is_name=False, name=None):
     1098        """
     1099        Create a Maxima element.
     1100        See ``MaximaElement`` for full documentation.
     1101
     1102        EXAMPLES::
     1103
     1104           sage: maxima(zeta(7))
     1105           zeta(7)
     1106        """
    10121107        ExpectElement.__init__(self, parent, value, is_name=False, name=None)
    10131108
    10141109    def display2d(self, onscreen=True):
    10151110        """
     1111        Return the 2d string representation of this Maxima object.
     1112
    10161113        EXAMPLES::
    10171114       
    10181115            sage: F = maxima('x^5 - y^5').factor() 
    1019             sage: F.display2d ()             
     1116            sage: F.display2d()             
    10201117                                   4      3    2  2    3      4
    10211118                       - (y - x) (y  + x y  + x  y  + x  y + x )
    10221119        """
     
    10551152
    10561153# Thanks to the MRO for multiple inheritance used by the Sage's Python , this should work as expected
    10571154class MaximaElementFunction(MaximaElement, MaximaAbstractElementFunction):
     1155    """
     1156    Maxima user-defined functions.
     1157
     1158    EXAMPLES:
     1159
     1160    Elements of this class should not be created directly.
     1161    The method ``function`` of the targeted parent should be used instead::
     1162
     1163        sage: maxima.function('x,y','h(x)*y')
     1164        h(x)*y
     1165    """
     1166
    10581167    def __init__(self, parent, name, defn, args, latex):
     1168        """
     1169        Create a Maxima function.
     1170        See ``MaximaElementFunction`` for full documentation.
     1171
     1172        EXAMPLES::
     1173       
     1174            sage: maxima.function('x,y','cos(x)+y')
     1175            cos(x)+y
     1176        """
    10591177        MaximaElement.__init__(self, parent, name, is_name=True)
    10601178        MaximaAbstractElementFunction.__init__(self, parent, name, defn, args, latex)
    10611179
     
    10671185
    10681186def reduce_load_Maxima():
    10691187    """
     1188    Unpickle a Maxima Pexpect interface.
     1189
    10701190    EXAMPLES::
    10711191   
    10721192        sage: from sage.interfaces.maxima import reduce_load_Maxima
     
    10751195    """
    10761196    return maxima
    10771197
     1198# This is defined for compatibility with the old Maxima interface.
    10781199def reduce_load_Maxima_function(parent, defn, args, latex):
     1200    """
     1201    Unpickle a Maxima function.
     1202
     1203    EXAMPLES::
     1204
     1205        sage: from sage.interfaces.maxima import reduce_load_Maxima_function
     1206        sage: f = maxima.function('x,y','sin(x+y)')
     1207        sage: _,args = f.__reduce__()
     1208        sage: g = reduce_load_Maxima_function(*args)
     1209        sage: g == f
     1210        True
     1211    """
    10791212    return parent.function(args, defn, defn, latex)
    10801213
    10811214def __doctest_cleanup():
     1215    """
     1216    Kill all Pexpect interfaces.
     1217
     1218    EXAMPLES::
     1219   
     1220        sage: from sage.interfaces.maxima import __doctest_cleanup
     1221        sage: maxima(1)
     1222        1
     1223        sage: maxima.is_running()
     1224        True
     1225        sage: __doctest_cleanup()
     1226        sage: maxima.is_running()
     1227        False
     1228    """
    10821229    import sage.interfaces.quit
    10831230    sage.interfaces.quit.expect_quitall()
  • sage/interfaces/maxima_abstract.py

    diff -r 60b965453710 -r 474b56e1b430 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 interface
     30
     31This is an abstract class implementing the functions shared between the Pexpect and library interfaces to Maxima.
    3132"""
    3233
    3334#*****************************************************************************
     
    6566# documentation from the system -- this could also be useful.
    6667
    6768class MaximaAbstract(Interface):
     69    r"""
     70    Abstract interface to Maxima.
     71
     72    INPUT:
     73
     74    - ``name`` - string
     75
     76    OUTPUT:
     77       
     78    - the interface
     79
     80    EXAMPLES:
     81       
     82    This class should not be instantiated directly,
     83    but through its subclasses Maxima (Pexpect interface)
     84    or MaximaLib (library interface)::
     85
     86        sage: m = Maxima()
     87        sage: from sage.interfaces.maxima_abstract import MaximaAbstract
     88        sage: isinstance(m,MaximaAbstract)
     89        True
    6890    """
    69     Interface to the Maxima interpreter.
    70     """
     91
    7192    def __init__(self, name):
    72         """
     93        r"""
    7394        Create an instance of an abstract interface to Maxima.
     95        See ``MaximaAbstract`` for full documentation.
     96
     97        EXAMPLES::
     98
     99            sage: from sage.interfaces.maxima_abstract import MaximaAbstract
     100            sage: isinstance(maxima,MaximaAbstract)
     101            True
    74102        """
    75103        Interface.__init__(self,name)
    76104
     
    78106    # System -- change directory, etc
    79107    ###########################################
    80108    def chdir(self, dir):
    81         """
     109        r"""
    82110        Change Maxima's current working directory.
    83111       
     112        INPUT:
     113
     114        - ``dir`` - string
     115
     116        OUTPUT: none
     117
    84118        EXAMPLES::
    85119       
    86120            sage: maxima.chdir('/')
     
    91125    # Interactive help
    92126    ###########################################
    93127    def _command_runner(self, command, s, redirect=True):
    94         """
     128        r"""
    95129        Run ``command`` in a new Maxima session and return its
    96130        output as an ``AsciiArtString``.
     131
     132        INPUT:
    97133       
    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?
     134        - ``command`` - string; function to call
     135
     136        - ``s`` - string; argument to the function
     137
     138        - ``redirect`` - boolean (default: True); if redirect is set to False, then the output of the command is not
     139          returned as a string. Instead, it behaves like os.system. This is
     140          used for interactive things like Maxima's demos. See maxima.demo?
     141
     142        OUTPUT:
     143
     144        Output of ``command(s)`` as an ``AsciiArtString`` if ``redirect`` is set to False;
     145        None otherwise.
    101146       
    102147        EXAMPLES::
    103148       
     
    125170            subprocess.Popen(cmd, shell=True)
    126171
    127172    def help(self, s):
    128         """
     173        r"""
     174        Return Maxima's help for ``s``.
     175
     176        INPUT:
     177
     178        - ``s`` - string
     179
     180        OUTPUT:
     181
     182        Maxima's help for ``s``
     183
    129184        EXAMPLES::
    130185       
    131186            sage: maxima.help('gcd')
    132187            -- Function: gcd (<p_1>, <p_2>, <x_1>, ...)
    133188            ...
    134189        """
     190        # Should this be implemented without launching a new Maxima session
     191        # i.e. using eval_line ?
    135192        return self._command_runner("describe", s)
    136193
    137194    def example(self, s):
    138         """
     195        r"""
     196        Return Maxima's examples for ``s``.
     197
     198        INPUT:
     199
     200        - ``s`` - string
     201
     202        OUTPUT:
     203
     204        Maxima's examples for ``s``
     205
    139206        EXAMPLES::
    140207       
    141208            sage: maxima.example('arrays')
     
    152219                                                  24
    153220                                                 done
    154221        """
     222        # Should this be implemented without launching a new Maxima session
     223        # i.e. using eval_line ?
    155224        return self._command_runner("example", s)
    156225
    157226    describe = help
    158227
    159228    def demo(self, s):
    160         """
     229        r"""
     230        Run Maxima's demo for ``s``.
     231
     232        INPUT:
     233
     234        - ``s`` - string
     235
     236        OUTPUT: none
     237
    161238        EXAMPLES::
    162239       
    163240            sage: maxima.demo('array') # not tested
     
    166243        At the _ prompt, type ';' followed by enter to get next demo
    167244        subscrmap : true _
    168245        """
     246        # Should this be implemented without launching a new Maxima session
     247        # i.e. using eval_line ?
    169248        return self._command_runner("demo", s, redirect=False)
    170249
    171250    def completions(self, s, verbose=True):
    172         """
     251        r"""
    173252        Return all commands that complete the command starting with the
    174         string s. This is like typing s[tab] in the Maxima interpreter.
     253        string ``s``. This is like typing s[tab] in the Maxima interpreter.
     254
     255        INPUT:
     256
     257        - ``s`` - string
     258
     259        - ``verbose`` - boolean (default: True)
     260
     261        OUTPUT: array of strings
    175262       
    176263        EXAMPLES::
    177264       
     
    191278    def _commands(self, verbose=True):
    192279        """
    193280        Return list of all commands defined in Maxima.
     281
     282        INPUT:
     283
     284        - ``verbose`` - boolean (default: True)
     285
     286        OUTPUT: array of strings
    194287       
    195288        EXAMPLES::
    196289       
     290            # The output is kind of random
    197291            sage: sorted(maxima._commands(verbose=False))
    198             ['Alpha',
    199              'Beta',
     292            [...
     293             'display',
    200294             ...
    201              'zunderflow']
     295             'gcd',
     296             ...
     297             'verbose',
     298             ...]
    202299        """
    203300        try:
    204301            return self.__commands
     
    210307        return self.__commands
    211308
    212309    def trait_names(self, verbose=True, use_disk_cache=True):
    213         """
     310        r"""
    214311        Return all Maxima commands, which is useful for tab completion.
     312
     313        INPUT:
     314
     315        - ``verbose`` - boolean (default: True)
     316
     317        - ``use_disk_cache`` - boolean (default: True); if set to True, try to read cached result from disk
     318
     319        OUTPUT: array of strings
    215320       
    216321        EXAMPLES::
    217322       
     
    247352        Start the interactive Maxima console. This is a completely separate
    248353        maxima session from this interface. To interact with this session,
    249354        you should instead use ``maxima.interact()``.
     355
     356        INPUT: none
    250357       
     358        OUTPUT: none
     359
    251360        EXAMPLES::
    252361       
    253362            sage: maxima.console()             # not tested (since we can't)
     
    273382    def cputime(self, t=None):
    274383        r"""
    275384        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}.
     385
     386        INPUT:
     387
     388        - ``t`` - float (default: None); If \var{t} is not None, then it returns the difference between
     389          the current CPU time and \var{t}.
     390
     391        OUTPUT: float
    278392       
    279393        EXAMPLES:
    280394            sage: t = maxima.cputime()
     
    288402            return float(self.eval('elapsed_run_time()'))
    289403
    290404    def version(self):
    291         """
     405        r"""
    292406        Return the version of Maxima that Sage includes.
     407
     408        INPUT: none
     409       
     410        OUTPUT: none
    293411       
    294412        EXAMPLES::
    295413       
     
    303421    ###
    304422
    305423    def _assign_symbol(self):
     424        r"""
     425        Return the assign symbol in Maxima.
     426
     427        INPUT: none
     428       
     429        OUTPUT: string
     430
     431        EXAMPLES::
     432
     433            sage: maxima._assign_symbol()
     434            ':'
     435            sage: maxima.eval('t : 8')
     436            '8'
     437            sage: maxima.eval('t')
     438            '8'
     439        """
    306440        return ":"
    307441
    308442    def _true_symbol(self):
    309443        """
    310444        Return the true symbol in Maxima.
     445
     446        INPUT: none
     447       
     448        OUTPUT: string
    311449       
    312450        EXAMPLES::
    313451       
     
    321459    def _false_symbol(self):
    322460        """
    323461        Return the false symbol in Maxima.
     462
     463        INPUT: none
     464       
     465        OUTPUT: string
    324466       
    325467        EXAMPLES::
    326468       
     
    335477        """
    336478        Returns the equality symbol in Maxima.
    337479
     480        INPUT: none
     481       
     482        OUTPUT: string
     483
    338484        EXAMPLES::
    339485
    340486             sage: maxima._equality_symbol()
    341487             '='
     488             sage: var('x y')
     489             (x, y)
     490             sage: maxima(x == y)
     491             x=y
    342492        """
    343493        return '='
    344494
    345495    def _inequality_symbol(self):
    346496        """
    347         Returns the equality symbol in Maxima.
     497        Returns the inequality symbol in Maxima.
     498
     499        INPUT: none
     500       
     501        OUTPUT: string
    348502
    349503        EXAMPLES::
    350504
     
    357511
    358512    def _function_class(self):
    359513        """
     514        Return the Python class of Maxima functions.
     515
     516        INPUT: none
     517       
     518        OUTPUT: type
     519
    360520        EXAMPLES::
    361521       
    362522            sage: maxima._function_class()
     
    367527    def _object_class(self):
    368528        """
    369529        Return the Python class of Maxima elements.
     530
     531        INPUT: none
     532       
     533        OUTPUT: type
    370534       
    371535        EXAMPLES::
    372536       
     
    376540        return MaximaAbstractElement
    377541
    378542    def _function_element_class(self):
    379         """     
     543        """
     544        Return the Python class of Maxima functions of elements.
     545
     546        INPUT: none
     547       
     548        OUTPUT: type
     549
    380550        EXAMPLES::
    381551       
    382552            sage: maxima._function_element_class()
     
    386556
    387557    def _object_function_class(self):
    388558        """
     559        Return the Python class of Maxima user-defined functions.
     560
     561        INPUT: none
     562       
     563        OUTPUT: type
     564
    389565        EXAMPLES::
    390566       
    391567            sage: maxima._object_function_class()
     
    393569        """
    394570        return MaximaAbstractElementFunction
    395571
    396     ####
    397     #
    398     ####
     572    ####################
     573    # Maxima functions #
     574    ####################
    399575
    400576    def function(self, args, defn, rep=None, latex=None):
    401577        """
     
    403579       
    404580        INPUT:
    405581       
    406        
    407582        -  ``args`` - a string with variable names separated by
    408583           commas
    409584       
     
    413588        -  ``rep`` - an optional string; if given, this is how
    414589           the function will print.
    415590       
     591        OUTPUT: Maxima function
    416592       
    417593        EXAMPLES::
    418594       
     
    433609            sage: g(1,2,3)
    434610            3*(cos(2)+sin(1))
    435611       
    436         The function definition can be a maxima object::
     612        The function definition can be a Maxima object::
    437613       
    438614            sage: an_expr = maxima('sin(x)*gamma(x)')
    439615            sage: t = maxima.function('x', an_expr)
     
    461637            rep = defn
    462638        f = self._object_function_class()(self, name, rep, args, latex)
    463639        return f
    464 
    465     #####
    466     # Maxima functions
    467     #####
    468640   
    469641##     def display2d(self, flag=True):
    470642##         """
     
    496668       
    497669        INPUT:
    498670       
    499        
    500671        -  ``f`` - a string representing a function (such as
    501672           f="sin(x)") [var, xmin, xmax]
    502673       
    503674        -  ``options`` - an optional string representing plot2d
    504675           options in gnuplot format
    505676       
    506        
    507677        EXAMPLES::
    508678       
    509679            sage: maxima.plot2d('sin(x)','[x,-5,5]')   # not tested
     
    516686
    517687    def plot2d_parametric(self, r, var, trange, nticks=50, options=None):
    518688        r"""
    519         Plots r = [x(t), y(t)] for t = tmin...tmax using gnuplot with
    520         options
     689        Plot r = [x(t), y(t)] for t = tmin...tmax using gnuplot with
     690        options.
    521691       
    522692        INPUT:
    523        
    524        
     693
    525694        -  ``r`` - a string representing a function (such as
    526695           r="[x(t),y(t)]")
    527696       
     
    535704        -  ``options`` - an optional string representing plot2d
    536705           options in gnuplot format
    537706       
    538        
    539707        EXAMPLES::
    540708       
    541709            sage: maxima.plot2d_parametric(["sin(t)","cos(t)"], "t",[-3.1,3.1])   # not tested
     
    570738       
    571739        INPUT:
    572740       
    573        
    574741        -  ``f`` - a string representing a function (such as
    575742           f="sin(x)") [var, min, max]
    576743       
    577        
     744        - ``args`` should be of the form '[x, xmin, xmax]', '[y, ymin, ymax]', '[grid, nx, ny]', options
     745
    578746        EXAMPLES::
    579747       
    580748            sage: maxima.plot3d('1 + x^3 - y^2', '[x,-2,2]', '[y,-2,2]', '[grid,12,12]')    # not tested
     
    594762       
    595763        INPUT:
    596764       
    597        
    598765        -  ``x, y, z`` - a string representing a function (such
    599766           as ``x="u2+v2"``, ...) vars is a list or two strings
    600767           representing variables (such as vars = ["u","v"])
     
    607774        -  ``options`` - optional string representing plot2d
    608775           options in gnuplot format
    609776       
    610        
    611777        OUTPUT: displays a plot on screen or saves to a file
    612778       
    613779        EXAMPLES::
     
    649815       
    650816        INPUT:
    651817       
    652        
    653818        -  ``de`` - a string representing the ODE
    654819       
    655820        -  ``vars`` - a list of strings representing the two
     
    658823        -  ``ics`` - a triple of numbers [a,b1,b2] representing
    659824           y(a)=b1, y'(a)=b2
    660825       
    661        
    662826        EXAMPLES::
    663827       
    664828            sage: maxima.de_solve('diff(y,x,2) + 3*x = y', ['x','y'], [1,1,1])
     
    692856       
    693857        INPUT:
    694858       
    695        
    696859        -  ``de`` - a string representing the ODE (e.g., de =
    697860           "diff(f(x),x,2)=diff(f(x),x)+sin(x)")
    698861       
     
    703866           conditions, with symbols allowed which are represented by strings
    704867           (eg, f(0)=1, f'(0)=2 is ics = [0,1,2])
    705868       
    706        
    707869        EXAMPLES::
    708870       
    709871            sage: maxima.clear('x'); maxima.clear('f')
     
    742904        """
    743905        Wraps maxima's linsolve.
    744906       
    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
     907        INPUT:
     908
     909        - ``eqns`` - a list of m strings; each representing a linear
     910        question in m = n variables
     911        - ``vars`` - a list of n strings; each
    747912        representing a variable
    748913       
    749914        EXAMPLES::
     
    772937        Finds a unit of the ring of integers of the quadratic number field
    773938        `\QQ(\sqrt{n})`, `n>1`, using the qunit maxima
    774939        command.
     940
     941        INPUT:
     942
     943        - ``n`` - an integer
    775944       
    776945        EXAMPLES::
    777946       
     
    804973       
    805974        INPUT:
    806975       
    807        
    808976        -  ``ptsx`` - [x1,...,xn], where the xi and yi are
    809977           real,
    810978       
     
    813981        -  ``options`` - a string representing maxima plot2d
    814982           options.
    815983       
    816        
    817984        The points are (x1,y1), (x2,y2), etc.
    818985       
    819986        This function requires maxima 5.9.2 or newer.
     
    8451012        where each ptsi is of the form [[x1,y1],...,[xn,yn]] x's must be
    8461013        integers and y's reals options is a string representing maxima
    8471014        plot2d options.
     1015
     1016        INPUT:
     1017       
     1018        - ``pts_lst`` - list of points; each point must be of the form [x,y]
     1019          where ``x`` is an integer and ``y`` is a real
     1020        - ``var`` - string; representing Maxima's plot2d options
    8481021       
    8491022        Requires maxima 5.9.2 at least.
    8501023
     
    8851058class MaximaAbstractElement(InterfaceElement):
    8861059    def __str__(self):
    8871060        """
    888         Printing an object explicitly gives ASCII art:
     1061        Printing an object explicitly gives ASCII art.
     1062
     1063        INPUT: none
     1064
     1065        OUTPUT: string
    8891066       
    8901067        EXAMPLES::
    8911068       
     
    9011078
    9021079    def bool(self):
    9031080        """
     1081        Convert ``self`` into a boolean.
     1082
     1083        INPUT: none
     1084
     1085        OUTPUT: boolean
     1086
    9041087        EXAMPLES::
    9051088       
    9061089            sage: maxima(0).bool()
     
    9131096
    9141097    def __cmp__(self, other):
    9151098        """
     1099        Compare this Maxima object with ``other``.
     1100
     1101        INPUT:
     1102
     1103        - ``other`` - an object to compare to
     1104
     1105        OUTPUT: integer
     1106
    9161107        EXAMPLES::
    9171108       
    9181109            sage: a = maxima(1); b = maxima(2)
     
    9521143
    9531144    def _sage_(self):
    9541145        """
    955         Attempt to make a native Sage object out of this maxima object.
     1146        Attempt to make a native Sage object out of this Maxima object.
    9561147        This is useful for automatic coercions in addition to other
    9571148        things.
     1149
     1150        INPUT: none
     1151
     1152        OUTPUT: Sage object
    9581153       
    9591154        EXAMPLES::
    9601155       
     
    10001195
    10011196    def _symbolic_(self, R):
    10021197        """
    1003         Return a symbolic expression equivalent to this maxima object.
     1198        Return a symbolic expression equivalent to this Maxima object.
     1199
     1200        INPUT:
     1201
     1202        - ``R`` - symbolic ring to convert into
     1203
     1204        OUTPUT: symbolic expression
    10041205
    10051206        EXAMPLES::
    10061207
     
    10101211            sage: u.parent()
    10111212            Symbolic Ring
    10121213
    1013         This is used when converting maxima objects to the Symbolic Ring::
     1214        This is used when converting Maxima objects to the Symbolic Ring::
    10141215
    10151216            sage: SR(t)
    10161217            sqrt(2)
     
    10191220
    10201221    def __complex__(self):
    10211222        """
     1223        Return a complex number equivalent to this Maxima object.
     1224
     1225        INPUT: none
     1226
     1227        OUTPUT: complex
     1228
    10221229        EXAMPLES::
    10231230       
    10241231            sage: complex(maxima('sqrt(-2)+1'))
     
    10281235
    10291236    def _complex_mpfr_field_(self, C):
    10301237        """
     1238        Return a mpfr complex number equivalent to this Maxima object.
     1239
     1240        INPUT:
     1241
     1242        - ``C`` - complex numbers field to convert into
     1243
     1244        OUTPUT: complex
     1245       
    10311246        EXAMPLES::
    10321247       
    10331248            sage: CC(maxima('1+%i'))
     
    10471262
    10481263    def _mpfr_(self, R):
    10491264        """
     1265        Return a mpfr real number equivalent to this Maxima object.
     1266
     1267        INPUT:
     1268
     1269        - ``R`` - real numbers field to convert into
     1270
     1271        OUTPUT: real
     1272
    10501273        EXAMPLES::
    10511274       
    10521275            sage: RealField(100)(maxima('sqrt(2)+1'))
     
    10561279
    10571280    def _complex_double_(self, C):
    10581281        """
     1282        Return a double precision complex number equivalent to this Maxima object.
     1283
     1284        INPUT:
     1285
     1286        - ``C`` - double precision complex numbers field to convert into
     1287
     1288        OUTPUT: complex
     1289
    10591290        EXAMPLES::
    10601291       
    10611292            sage: CDF(maxima('sqrt(2)+1'))
     
    10651296
    10661297    def _real_double_(self, R):
    10671298        """
     1299        Return a double precision real number equivalent to this Maxima object.
     1300
     1301        INPUT:
     1302
     1303        - ``R`` - double precision real numbers field to convert into
     1304
     1305        OUTPUT: real
     1306
    10681307        EXAMPLES::
    10691308       
    10701309            sage: RDF(maxima('sqrt(2)+1'))
     
    10741313
    10751314    def real(self):
    10761315        """
    1077         Return the real part of this maxima element.
     1316        Return the real part of this Maxima element.
    10781317       
     1318        INPUT: none
     1319
     1320        OUTPUT: Maxima real
     1321
    10791322        EXAMPLES::
    10801323       
    10811324            sage: maxima('2 + (2/3)*%i').real()
     
    10851328
    10861329    def imag(self):
    10871330        """
    1088         Return the imaginary part of this maxima element.
     1331        Return the imaginary part of this Maxima element.
     1332       
     1333        INPUT: none
     1334
     1335        OUTPUT: Maxima real
    10891336       
    10901337        EXAMPLES::
    10911338       
     
    10981345        """
    10991346        Return numerical approximation to self as a Maxima object.
    11001347       
     1348        INPUT: none
     1349
     1350        OUTPUT: Maxima object
     1351       
    11011352        EXAMPLES::
    11021353       
    11031354            sage: a = maxima('sqrt(2)').numer(); a
     
    11091360
    11101361    def str(self):
    11111362        """
    1112         Return string representation of this maxima object.
     1363        Return string representation of this Maxima object.
     1364
     1365        INPUT: none
     1366
     1367        OUTPUT: string
    11131368       
    11141369        EXAMPLES::
    11151370       
     
    11211376
    11221377    def __repr__(self):
    11231378        """
    1124         Return print representation of this object.
     1379        Return print representation of this Maxima object.
     1380
     1381        INPUT: none
     1382
     1383        OUTPUT: string
     1384
     1385        The result is cached.
    11251386       
    11261387        EXAMPLES::
    11271388       
     
    11431404       
    11441405        INPUT:
    11451406       
    1146        
    11471407        -  ``var`` - variable (default: 'x')
    11481408       
    11491409        -  ``n`` - integer (default: 1)
    11501410       
    1151        
    11521411        OUTPUT: n-th derivative of self with respect to the variable var
    11531412       
    11541413        EXAMPLES::
     
    11841443       
    11851444        INPUT:
    11861445       
    1187        
    11881446        -  ``var`` - variable to integrate with respect to
    11891447       
    11901448        -  ``a`` - lower endpoint of integration
     
    11961454       
    11971455        -  ``maximum_num_subintervals`` - (default: 200)
    11981456           maxima number of subintervals
    1199        
    1200        
     1457           
    12011458        OUTPUT:
    12021459       
    1203        
    12041460        -  approximation to the integral
    12051461       
    12061462        -  estimated absolute error of the
     
    12241480
    12251481            -  ``6`` - the input is invalid
    12261482       
    1227        
    12281483        EXAMPLES::
    12291484       
    12301485            sage: maxima('exp(-sqrt(x))').nintegral('x',0,1)
     
    12511506       
    12521507        INPUT:
    12531508       
    1254        
    12551509        -  ``var`` - variable
    12561510       
    12571511        -  ``min`` - default: None
    12581512       
    12591513        -  ``max`` - default: None
    12601514       
     1515        OUTPUT:
    12611516       
    1262         Returns the definite integral if xmin is not None, otherwise
    1263         returns an indefinite integral.
     1517        - the definite integral if xmin is not None
     1518       
     1519        - an indefinite integral otherwise
    12641520       
    12651521        EXAMPLES::
    12661522       
     
    12961552
    12971553    def __float__(self):
    12981554        """
    1299         Return floating point version of this maxima element.
     1555        Return floating point version of this Maxima element.
     1556
     1557        INPUT: none
     1558
     1559        OUTPUT: real
    13001560       
    13011561        EXAMPLES::
    13021562       
     
    13151575    def __len__(self):
    13161576        """
    13171577        Return the length of a list.
     1578
     1579        INPUT: none
     1580
     1581        OUTPUT: integer
    13181582       
    13191583        EXAMPLES::
    13201584       
     
    13281592    def dot(self, other):
    13291593        """
    13301594        Implements the notation self . other.
     1595
     1596        INPUT:
     1597
     1598        - ``other`` - matrix; argument to dot.
     1599
     1600        OUTPUT: Maxima matrix
    13311601       
    13321602        EXAMPLES::
    13331603       
     
    13431613    def __getitem__(self, n):
    13441614        r"""
    13451615        Return the n-th element of this list.
     1616
     1617        INPUT:
     1618
     1619        - ``n`` - integer
     1620
     1621        OUTPUT: Maxima object
    13461622       
    13471623        .. note::
    13481624
     
    13701646
    13711647    def __iter__(self):
    13721648        """
    1373         EXAMPLE::
     1649        Return an iterator for self.
     1650
     1651        INPUT: none
     1652
     1653        OUTPUT: iterator
     1654
     1655        EXAMPLES::
    13741656       
    13751657            sage: v = maxima('create_list(i*x^i,i,0,5)')
    13761658            sage: L = list(v)
     
    13831665    def subst(self, val):
    13841666        """
    13851667        Substitute a value or several values into this Maxima object.
     1668
     1669        INPUT:
     1670
     1671        - ``val`` - string representing substitution(s) to perform
     1672
     1673        OUTPUT: Maxima object
    13861674       
    13871675        EXAMPLES::
    13881676       
     
    13981686    def comma(self, args):
    13991687        """
    14001688        Form the expression that would be written 'self, args' in Maxima.
     1689
     1690        INPUT:
     1691
     1692        - ``args`` - string
     1693
     1694        OUTPUT: Maxima object
    14011695       
    14021696        EXAMPLES::
    14031697       
     
    14131707    def _latex_(self):
    14141708        """
    14151709        Return Latex representation of this Maxima object.
     1710
     1711        INPUT: none
     1712
     1713        OUTPUT: string
    14161714       
    14171715        This calls the tex command in Maxima, then does a little
    14181716        post-processing to fix bugs in the resulting Maxima output.
     
    14381736        P = self.parent()
    14391737        s = P._eval_line('tex(%s);'%self.name(), reformat=False)
    14401738        if not '$$' in s:
    1441             raise RuntimeError, "Error texing maxima object."
     1739            raise RuntimeError, "Error texing Maxima object."
    14421740        i = s.find('$$')
    14431741        j = s.rfind('$$')
    14441742        s = s[i+2:j]
     
    14621760    def trait_names(self, verbose=False):
    14631761        """
    14641762        Return all Maxima commands, which is useful for tab completion.
     1763
     1764        INPUT:
     1765       
     1766        - ``verbose`` - boolean
     1767
     1768        OUTPUT: list of strings
    14651769       
    14661770        EXAMPLES::
    14671771       
     
    14761780        If self is a Maxima matrix, return the corresponding Sage matrix
    14771781        over the Sage ring `R`.
    14781782       
     1783        INPUT:
     1784
     1785        - ``R`` - ring to coerce into
     1786
     1787        OUTPUT: matrix
     1788       
    14791789        This may or may not work depending in how complicated the entries
    14801790        of self are! It only works if the entries of self can be coerced as
    14811791        strings to produce meaningful elements of `R`.
     
    15171827        """
    15181828        Return the partial fraction decomposition of self with respect to
    15191829        the variable var.
     1830
     1831        INPUT:
     1832
     1833        - ``var`` - string
     1834
     1835        OUTPUT: Maxima object
    15201836       
    15211837        EXAMPLES::
    15221838       
     
    15321848
    15331849    def _operation(self, operation, right):
    15341850        r"""
     1851        Return the result of "self operation right" in Maxima.
     1852
     1853        INPUT:
     1854
     1855        - ``operation`` - string; operator
     1856
     1857        - ``right`` - Maxima object; right operand
     1858
     1859        OUTPUT: Maxima object
     1860
    15351861        Note that right's parent should already be Maxima since this should
    15361862        be called after coercion has been performed.
    15371863       
     
    15681894
    15691895
    15701896class MaximaAbstractElementFunction(MaximaAbstractElement):
     1897    r"""
     1898    Create a Maxima function with the parent ``parent``,
     1899    name ``name``, definition ``defn``, arguments ``args``
     1900    and latex representation ``latex``.
     1901
     1902    INPUT:
     1903
     1904    - ``parent`` - an instance of a concrete Maxima interface
     1905
     1906    - ``name`` - string
     1907
     1908    - ``defn`` - string
     1909
     1910    - ``args`` - string; comma separated names of arguments
     1911
     1912    - ``latex`` - string
     1913
     1914    OUTPUT: Maxima function
     1915
     1916    EXAMPLES::
     1917       
     1918        sage: f = maxima.function('x,y','sin(x+y)')
     1919        sage: f == loads(dumps(f))
     1920        True
     1921    """
     1922
    15711923    def __init__(self, parent, name, defn, args, latex):
    15721924        """
     1925        Create a Maxima function.
     1926        See ``MaximaAbstractElementFunction`` for full documentation.
     1927
    15731928        EXAMPLES::
    15741929       
    15751930            sage: f = maxima.function('x,y','sin(x+y)')
     
    15831938
    15841939    def __reduce__(self):
    15851940        """
     1941        Implement __reduce__ for ``MaximaAbstractElementFunction``.
     1942
     1943        INPUT: none
     1944
     1945        OUTPUT:
     1946
     1947        A couple consisting of:
     1948
     1949        - the function to call for unpickling
     1950       
     1951        - a tuple of arguments for the function
     1952
    15861953        EXAMPLES::
    15871954       
    15881955            sage: f = maxima.function('x,y','sin(x+y)')
     
    15941961       
    15951962    def __call__(self, *x):
    15961963        """
     1964        Return the result of calling this Maxima function with arguments ``*x``.
     1965
     1966        INPUT:
     1967
     1968        - ``x`` - a variable number of arguments
     1969
     1970        OUTPUT: Maxima object
     1971
    15971972        EXAMPLES::
    15981973       
    15991974            sage: f = maxima.function('x,y','sin(x+y)')
     
    16091984
    16101985    def __repr__(self):
    16111986        """
     1987        Return print representation of this Maxima function.
     1988
     1989        INPUT: none
     1990
     1991        OUTPUT: string
     1992
    16121993        EXAMPLES::
    16131994       
    16141995            sage: f = maxima.function('x,y','sin(x+y)')
     
    16192000
    16202001    def _latex_(self):
    16212002        """
     2003        Return latex representation of this Maxima function.
     2004
     2005        INPUT: none
     2006
     2007        OUTPUT: string
     2008
    16222009        EXAMPLES::
    16232010       
    16242011            sage: f = maxima.function('x,y','sin(x+y)')
     
    16332020    def arguments(self, split=True):
    16342021        r"""
    16352022        Returns the arguments of this Maxima function.
     2023
     2024        INPUT:
     2025
     2026        - ``split`` - boolean; if True return a tuple of strings,
     2027          otherwise return a string of comma-separated arguments
     2028
     2029        OUTPUT:
     2030
     2031        - a string if ``split`` is False
     2032
     2033        - a list of strings if ``split`` is True
    16362034       
    16372035        EXAMPLES::
    16382036       
     
    16532051    def definition(self):
    16542052        """
    16552053        Returns the definition of this Maxima function as a string.
     2054
     2055        INPUT: none
     2056
     2057        OUTPUT: string
    16562058       
    16572059        EXAMPLES::
    16582060       
     
    16652067    def integral(self, var):
    16662068        """
    16672069        Returns the integral of self with respect to the variable var.
     2070
     2071        INPUT:
     2072
     2073        - ``var`` - a variable
     2074
     2075        OUTPUT: Maxima function
    16682076       
    16692077        Note that integrate is an alias of integral.
    16702078       
     
    16922100        r"""
    16932101        This is a utility function which factors out much of the
    16942102        commonality used in the arithmetic operations for
    1695         ``MaximaFunctions``.
     2103        ``MaximaAbstractElementFunction``.
    16962104       
    16972105        INPUT:
    16982106       
    1699        
    17002107        -  ``operation`` - A string representing the operation
    17012108           being performed. For example, '\*', or '1/'.
    17022109       
    17032110        -  ``f`` - The other operand. If f is
    1704            ``None``, than the operation is assumed to be unary
     2111           ``None``, then the operation is assumed to be unary
    17052112           rather than binary.
    17062113       
    1707        
    17082114        EXAMPLES::
    17092115       
    17102116            sage: f = maxima.function('x,y','sin(x+y)')
     
    17332139
    17342140    def _add_(self, f):
    17352141        """
    1736         MaximaFunction as left summand.
     2142        This Maxima function as left summand.
    17372143       
    17382144        EXAMPLES::
    17392145       
     
    17692175
    17702176    def _sub_(self, f):
    17712177        r"""
    1772         ``MaximaFunction`` as minuend.
     2178        This Maxima function as minuend.
    17732179       
    17742180        EXAMPLES::
    17752181       
     
    17942200       
    17952201    def _mul_(self, f):
    17962202        r"""
    1797         ``MaximaFunction`` as left factor.
     2203        This Maxima function as left factor.
    17982204       
    17992205        EXAMPLES::
    18002206       
     
    18202226
    18212227    def _div_(self, f):
    18222228        r"""
    1823         ``MaximaFunction`` as dividend.
     2229        This Maxima function as dividend.
    18242230       
    18252231        EXAMPLES::
    18262232       
     
    18462252
    18472253    def __neg__(self):
    18482254        r"""
    1849         Additive inverse of a ``MaximaFunction``.
     2255        Additive inverse of this Maxima function.
    18502256       
    18512257        EXAMPLES::
    18522258       
     
    18582264
    18592265    def __inv__(self):
    18602266        r"""
    1861         Multiplicative inverse of a ``MaximaFunction``.
     2267        Multiplicative inverse of this Maxima function.
    18622268       
    18632269        EXAMPLES::
    18642270       
     
    18702276
    18712277    def __pow__(self,f):
    18722278        r"""
    1873         ``MaximaFunction`` raised to some power.
     2279        This Maxima function raised to some power.
    18742280       
    18752281        EXAMPLES::
    18762282       
     
    18902296
    18912297
    18922298def reduce_load_MaximaAbstract_function(parent, defn, args, latex):
     2299    r"""
     2300    Unpickle a Maxima function.
     2301
     2302    EXAMPLES::
     2303
     2304        sage: from sage.interfaces.maxima_abstract import reduce_load_MaximaAbstract_function
     2305        sage: f = maxima.function('x,y','sin(x+y)')
     2306        sage: _,args = f.__reduce__()
     2307        sage: g = reduce_load_MaximaAbstract_function(*args)
     2308        sage: g == f
     2309        True
     2310    """
    18932311    return parent.function(args, defn, defn, latex)
    18942312   
    18952313def maxima_version():
    18962314    """
     2315    Return Maxima version.
     2316
     2317    Currently this calls a new copy of Maxima.
     2318
    18972319    EXAMPLES::
    18982320   
    18992321        sage: from sage.interfaces.maxima_abstract import maxima_version
  • sage/interfaces/maxima_lib.py

    diff -r 60b965453710 -r 474b56e1b430 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 interface
     30
     31For this interface, Maxima is loaded into ECL which is itself loaded as a C library in Sage.
     32Translations between Sage and Maxima objects (which are nothing but wrappers to ECL objects)
     33is made as much as possible directly, but falls back to the string based conversion
     34used by the classical Maxima Pexpect interface in case no new implementation has been made.
     35
     36This interface is the one used for calculus by Sage and is accessible as maxima_calculus::
     37
     38    sage: maxima_calculus
     39    Maxima_lib
     40
     41Only one instance of this interface can be instantiated,
     42so the user should not try to instantiate another one,
     43which is anyway set to raise an error::
     44
     45    sage: from sage.interfaces.maxima_lib import MaximaLib
     46    sage: MaximaLib()
     47    Traceback (most recent call last):
     48    ...
     49    RuntimeError: Maxima interface in library mode can only be instantiated once
    3150"""
    3251
    3352#*****************************************************************************
     
    5170
    5271from maxima_abstract import MaximaAbstract, MaximaAbstractFunction, MaximaAbstractElement, MaximaAbstractFunctionElement, MaximaAbstractElementFunction
    5372
    54 ## We begin here by initializing maxima in library mode
     73## We begin here by initializing Maxima in library mode
     74## i.e. loading it into ECL
    5575ecl_eval("(setf *load-verbose* NIL)")
    5676ecl_eval("(require 'maxima)")
    5777ecl_eval("(in-package :maxima)")
     
    6080ecl_eval("(set-locale-subdir)")
    6181ecl_eval("(set-pathnames)")
    6282ecl_eval("(defun add-lineinfo (x) x)")
     83
    6384#the following is a direct adaption of the definition of "retrieve" in the Maxima file
    6485#macsys.lisp. This routine is normally responsible for displaying a question and
    6586#returning the answer. We change it to throw an error in which the text of the question
     
    100121)
    101122""")
    102123
     124## Redirection of ECL and Maxima stdout to /dev/null
    103125ecl_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 
    120126ecl_eval("(setf original-standard-output *standard-output*)")
    121127ecl_eval("(setf *standard-output* *dev-null*)")
    122128#ecl_eval("(setf *error-output* *dev-null*)")
    123129
     130## Default options set in Maxima
    124131# display2d -- no ascii art output
    125132# keepfloat -- don't automatically convert floats to rationals
    126133init_code = ['display2d : false', 'domain : complex', 'keepfloat : true', 'load(to_poly_solver)', 'load(simplify_sum)']
     
    137144## should allow to do this through a method
    138145#ecl_eval("(setf *standard-output* original-standard-output)")
    139146
     147## This is the main function (ECL object) used for evalutation
    140148# This returns an EclObject
    141149maxima_eval=ecl_eval("""
    142150(defun maxima-eval( form )
     
    166174)
    167175""")
    168176
     177## Number of instances of this interface
    169178maxima_lib_instances = 0
    170179
     180## Here we define several useful ECL/Maxima objects
    171181# The Maxima string function can change the structure of its input
    172182#maxprint=EclObject("$STRING")
    173183maxprint=EclObject("(defun mstring-for-sage (form) (coerce (mstring form) 'string))").eval()
     
    189199max_to_poly_solve=EclObject("$TO_POLY_SOLVE")
    190200
    191201def stdout_to_string(s):
     202    r"""
     203    Evaluate command ``s`` and catch Maxima stdout (not the result of the command!) into a string.
     204
     205    INPUT:
     206
     207    - ``s`` - string; command to evaluate
     208
     209    OUTPUT: string
     210
     211    This is currently used to implement display2d.
     212
     213    EXAMPLES::
     214   
     215        sage: from sage.interfaces.maxima_lib import stdout_to_string
     216        sage: stdout_to_string('1+1')
     217        ''
     218        sage: stdout_to_string('disp(1+1)')
     219        '2\n\n'
     220    """
    192221    return ecl_eval("(with-output-to-string (*standard-output*) (maxima-eval #$%s$))"%s).python()[1:-1]
    193222
    194223def max_to_string(s):
    195      return maxprint(s).python()[1:-1]
     224    r"""
     225    Return the Maxima string corresponding to this ECL object.
     226
     227    INPUT:
     228
     229    - ``s`` - ECL object
     230
     231    OUTPUT: string
     232
     233    EXAMPLES::
     234
     235        sage: from sage.interfaces.maxima_lib import maxima_lib, max_to_string
     236        sage: ecl = maxima_lib(cos(x)).ecl()
     237        sage: max_to_string(ecl)
     238        'cos(x)'
     239    """
     240    return maxprint(s).python()[1:-1]
    196241
    197242my_mread=ecl_eval("""
    198243(defun my-mread (cmd)
    199244  (caddr (mread (make-string-input-stream cmd))))
    200245""")
    201246
    202 def parse_max_string(l):
    203   return my_mread('"%s;"'%l)
     247def parse_max_string(s):
     248    r"""
     249    Evaluate string in Maxima without *any* further simplification.
     250
     251    INPUT:
     252
     253    - ``s`` - string
     254
     255    OUTPUT: ECL object
     256
     257    EXAMPLES::
     258
     259        sage: from sage.interfaces.maxima_lib import parse_max_string
     260        sage: parse_max_string('1+1')
     261        <ECL: ((MPLUS) 1 1)>
     262    """
     263    return my_mread('"%s;"'%s)
    204264
    205265class MaximaLib(MaximaAbstract):
    206266    """
    207267    Interface to Maxima as a Library.
     268
     269    INPUT: none
     270
     271    OUTPUT: Maxima interface as a Library
     272
     273    EXAMPLES::
     274
     275        sage: from sage.interfaces.maxima_lib import MaximaLib, maxima_lib
     276        sage: isinstance(maxima_lib,MaximaLib)
     277        True
     278
     279    Only one such interface can be instantiated::
     280
     281        sage: MaximaLib()
     282        Traceback (most recent call last):
     283        ...
     284        RuntimeError: Maxima interface in library mode can only be instantiated once
    208285    """
    209286    def __init__(self):
    210287        """
    211288        Create an instance of the Maxima interpreter.
     289        See ``MaximaLib`` for full documentation.
    212290
    213291        TESTS::
    214292
     
    229307        global init_code
    230308        self.__init_code = init_code
    231309
    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)
    234310        MaximaAbstract.__init__(self,"maxima_lib")
    235311        self.__seq = 0
    236312 
    237313    def _coerce_from_special_method(self, x):
     314        r"""
     315        Coerce ``x`` into self trying to call a special underscore method.
     316
     317        INPUT:
     318
     319        - ``x`` - object to coerce into self
     320
     321        OUTPUT: Maxima element equivalent to ``x``
     322
     323        EXAMPLES::
     324
     325            sage: from sage.interfaces.maxima_lib import maxima_lib
     326            sage: xmax = maxima_lib._coerce_from_special_method(x)
     327            sage: type(xmax)
     328            <class 'sage.interfaces.maxima_lib.MaximaLibElement'>
     329        """
    238330        if isinstance(x, EclObject):
    239331            return MaximaLibElement(self,self._create(x))
    240332        else:
    241333            return MaximaAbstract._coerce_from_special_method(self,x)
    242334       
    243335    def __reduce__(self):
    244         """
     336        r"""
     337        Implement __reduce__ for ``MaximaLib``.
     338
     339        INPUT: none
     340
     341        OUTPUT:
     342
     343        A couple consisting of:
     344
     345        - the function to call for unpickling
     346       
     347        - a tuple of arguments for the function
     348
    245349        EXAMPLES::
    246350       
    247351            sage: from sage.interfaces.maxima_lib import maxima_lib
     
    251355        return reduce_load_MaximaLib, tuple([])
    252356
    253357    # This outputs a string
    254     def eval(self, line, locals=None, reformat=True, **kwds):
     358    def _eval_line(self, line, locals=None, reformat=True, **kwds):
     359        r"""
     360        Evaluate the line in Maxima.
     361
     362        INPUT:
     363
     364        - ``line`` - string; text to evaluate
     365       
     366        - ``locals`` - None (ignored); this is used for compatibility with the
     367          Sage notebook's generic system interface.
     368         
     369        - ``reformat`` - boolean; whether to strip output or not
     370
     371        - ``**kwds`` - All other arguments are currently ignored.
     372
     373        OUTPUT: string representing Maxima output
     374
     375        EXAMPLES::
     376
     377            sage: from sage.interfaces.maxima_lib import maxima_lib
     378            sage: maxima_lib._eval_line('1+1')
     379            '2'
     380            sage: maxima_lib._eval_line('1+1;')
     381            '2'
     382            sage: maxima_lib._eval_line('1+1$')
     383            ''
     384            sage: maxima_lib._eval_line('randvar : cos(x)+sin(y)$')
     385            ''
     386            sage: maxima_lib._eval_line('randvar')
     387            'sin(y)+cos(x)'
     388        """
    255389        result = ''
    256390        while line:
    257391            ind_dollar=line.find("$")
     
    272406            return result
    273407        return ''.join([x.strip() for x in result.split()])
    274408
    275     _eval_line = eval
     409    eval = _eval_line
    276410
    277411    ###########################################
    278412    # Direct access to underlying lisp interpreter.
     
    281415        """
    282416        Send a lisp command to maxima.
    283417       
     418        INPUT:
     419
     420        - ``cmd`` - string
     421
     422        OUTPUT: ECL object
     423
    284424        .. note::
    285425
    286426           The output of this command is very raw - not pretty.
     
    299439       
    300440        INPUT:
    301441       
    302        
    303442        -  ``var`` - string
    304443       
    305444        -  ``value`` - string
    306        
     445
     446        OUTPUT: none
    307447       
    308448        EXAMPLES::
    309449       
     
    321461        """
    322462        Clear the variable named var.
    323463
     464        INPUT:
     465
     466        - ``var`` - string
     467
     468        OUTPUT: none
     469
    324470        EXAMPLES::
    325471
    326472            sage: from sage.interfaces.maxima_lib import maxima_lib
     
    339485    def get(self, var):
    340486        """
    341487        Get the string value of the variable var.
     488
     489        INPUT:
     490
     491        - ``var`` - string
     492
     493        OUTPUT: string
    342494       
    343495        EXAMPLES::
    344496       
     
    351503        return s
    352504 
    353505    def _create(self, value, name=None):
     506        r"""
     507        Create a variable with given value and name.
     508
     509        INPUT:
     510
     511        - ``value`` - string or ECL object
     512
     513        - ``name`` - string (default: None); name to use for the variable,
     514          an automatically generated name is used if this is none
     515
     516        OUTPUT:
     517
     518        - string; the name of the created variable
     519
     520        EXAMPLES:
     521
     522        Creation from strings::
     523
     524            sage: from sage.interfaces.maxima_lib import maxima_lib
     525            sage: maxima_lib._create('3','var3')
     526            'var3'
     527            sage: maxima_lib.get('var3')
     528            '3'
     529            sage: s = maxima_lib._create('3')
     530            sage: s # random output
     531            'sage9'
     532            sage: s[:4] == 'sage'
     533            True
     534
     535        And from ECL object::
     536
     537            sage: c = maxima_lib(x+cos(19)).ecl()
     538            sage: maxima_lib._create(c,'m')
     539            'm'
     540            sage: maxima_lib.get('m')
     541            'x+cos(19)'
     542        """
    354543        name = self._next_var_name() if name is None else name
    355544        if isinstance(value,EclObject):
    356545            maxima_eval([[msetq],cadadr("#$%s$#$"%name),value])
     
    359548        return name
    360549
    361550    def _function_class(self):
    362         """
     551        r"""
     552        Return the Python class of Maxima functions.
     553
     554        INPUT: none
     555       
     556        OUTPUT: type
     557
    363558        EXAMPLES::
    364559       
    365560            sage: from sage.interfaces.maxima_lib import maxima_lib
     
    369564        return MaximaLibFunction
    370565
    371566    def _object_class(self):
    372         """
     567        r"""
    373568        Return the Python class of Maxima elements.
     569
     570        INPUT: none
     571       
     572        OUTPUT: type
    374573       
    375574        EXAMPLES::
    376575       
     
    381580        return MaximaLibElement
    382581
    383582    def _function_element_class(self):
    384         """     
     583        r"""
     584        Return the Python class of Maxima functions of elements.
     585
     586        INPUT: none
     587       
     588        OUTPUT: type
     589
    385590        EXAMPLES::
    386591       
    387592            sage: from sage.interfaces.maxima_lib import maxima_lib
     
    391596        return MaximaLibFunctionElement
    392597
    393598    def _object_function_class(self):
    394         """
     599        r"""
     600        Return the Python class of Maxima user-defined functions.
     601
     602        INPUT: none
     603       
     604        OUTPUT: type
     605
    395606        EXAMPLES::
    396607       
    397608            sage: from sage.interfaces.maxima_lib import maxima_lib
     
    562773
    563774
    564775def is_MaximaLibElement(x):
    565     """
     776    r"""
    566777    Returns True if x is of type MaximaLibElement.
    567778   
    568779    EXAMPLES::
     
    576787    """
    577788    return isinstance(x, MaximaLibElement)
    578789
    579 class MaximaLibElement(MaximaAbstractElement):
    580     """
    581     """   
     790class MaximaLibElement(MaximaAbstractElement):   
    582791    def ecl(self):
     792        r"""
     793        Return the underlying ECL object of this MaximaLib object.
     794
     795        INPUT: none
     796
     797        OUTPUT: ECL object
     798
     799        EXAMPLES::
     800
     801            sage: from sage.interfaces.maxima_lib import maxima_lib
     802            sage: maxima_lib(x+cos(19)).ecl()
     803            <ECL: ((MPLUS SIMP) ((%COS SIMP) 19) $X)>
     804        """
    583805        try:
    584806            return self._ecl
    585807        except AttributeError:
     
    587809            return self._ecl
    588810           
    589811    def to_poly_solve(self,vars,options=""):
     812        r"""
     813        Use Maxima's to_poly_solver package.
     814
     815        INPUT:
     816
     817        - ``vars`` - symbolic expressions
     818
     819        - ``options`` - string (default="")
     820
     821        OUTPUT: Maxima object
     822
     823        EXAMPLES::
     824
     825            sage: from sage.interfaces.maxima_lib import maxima_lib
     826            sage: sol = maxima_lib(sin(x) == 0).to_poly_solve(x)
     827            sage: sol.sage()
     828            [[x == pi + 2*pi*z6], [x == 2*pi*z8]]
     829        """
    590830        if options.find("use_grobner=true") != -1:
    591831            cmd=EclObject([[max_to_poly_solve], self.ecl(), sr_to_max(vars),
    592832                                             [[mequal],max_use_grobner,True]])
     
    595835        return self.parent()(maxima_eval(cmd))
    596836
    597837    def display2d(self, onscreen=True):
    598         """
     838        r"""
     839        Return the 2d representation of this Maxima object.
     840
     841        INPUT:
     842
     843        - ``onscreen`` - boolean (default: True); whether to print or return
     844
     845        OUTPUT:
     846
     847        The representation is printed if onscreen is set to True
     848        and returned as a string otherwise.
     849
    599850        EXAMPLES::
    600851       
    601852            sage: from sage.interfaces.maxima_lib import maxima_lib
    602853            sage: F = maxima_lib('x^5 - y^5').factor() 
    603             sage: F.display2d ()             
     854            sage: F.display2d()             
    604855                                   4      3    2  2    3      4
    605856                       - (y - x) (y  + x y  + x  y  + x  y + x )
    606857        """
     
    638889
    639890
    640891def reduce_load_MaximaLib():
    641     """
     892    r"""
     893    Unpickle the Maxima library interface.
     894
    642895    EXAMPLES::
    643896   
    644897        sage: from sage.interfaces.maxima_lib import reduce_load_MaximaLib
     
    647900    """
    648901    return maxima_lib
    649902
    650 #**********************************
    651 # ???
    652903
     904#############################################
     905# Smart translations between SR and Maxima
     906#############################################
     907
     908import sage.rings.real_double
    653909import sage.symbolic.expression
    654910import sage.functions.trig
    655911import sage.functions.log
     
    667923cadadr=EclObject("cadadr")
    668924meval=EclObject("meval")
    669925NIL=EclObject("NIL")
    670 ratdisrep=EclObject("ratdisrep")
    671926
     927## Dictionaries for standard operators
    672928sage_op_dict = {
    673929    sage.symbolic.expression.operator.abs : "MABS",
    674930    sage.symbolic.expression.operator.add : "MPLUS",
     
    707963sage_op_dict = dict([(k,EclObject(sage_op_dict[k])) for k in sage_op_dict])
    708964max_op_dict = dict([(sage_op_dict[k],k) for k in sage_op_dict])
    709965
     966
     967## Here we correct the dictionaries for some simple operators
    710968def add_vararg(*args):
     969    r"""
     970    Addition of a variable number of arguments.
     971
     972    INPUT:
     973   
     974    - ``args`` - arguments to add
     975
     976    OUTPUT: sum of arguments
     977
     978    EXAMPLES::
     979
     980        sage: from sage.interfaces.maxima_lib import add_vararg
     981        sage: add_vararg(1,2,3,4,5,6,7)
     982        28
     983    """
    711984    S=0
    712985    for a in args:
    713986        S=S+a
    714987    return S
    715988
    716989def mul_vararg(*args):
     990    r"""
     991    Multiplication of a variable number of arguments.
     992
     993    INPUT:
     994   
     995    - ``args`` - arguments to multiply
     996
     997    OUTPUT: product of arguments
     998
     999    EXAMPLES::
     1000
     1001        sage: from sage.interfaces.maxima_lib import mul_vararg
     1002        sage: mul_vararg(9,8,7,6,5,4)
     1003        60480
     1004    """
    7171005    P=1
    7181006    for a in args:
    7191007        P=P*a
    7201008    return P
    7211009
    7221010def sage_rat(x,y):
     1011    r"""
     1012    Return quotient x/y.
     1013
     1014    INPUT:
     1015
     1016    - ``x`` - integer
     1017
     1018    - ``y`` - integer
     1019
     1020    OUTPUT: rational
     1021
     1022    EXAMPLES::
     1023
     1024        sage: from sage.interfaces.maxima_lib import sage_rat
     1025        sage: sage_rat(1,7)
     1026        1/7
     1027    """
    7231028    return x/y
    7241029
    7251030mplus=EclObject("MPLUS")
    7261031mtimes=EclObject("MTIMES")
    727 mdiff=EclObject("%DERIVATIVE")
    7281032rat=EclObject("RAT")
    729 max_i=EclObject("$%I")
    7301033max_op_dict[mplus]=add_vararg
    7311034max_op_dict[mtimes]=mul_vararg
    7321035max_op_dict[rat]=sage_rat
     1036
     1037
     1038## Here we build dictionaries for operators needing special conversions.
     1039ratdisrep=EclObject("ratdisrep")
     1040mrat=EclObject("MRAT")
    7331041mqapply=EclObject("MQAPPLY")
    7341042max_li=EclObject("$LI")
    7351043max_psi=EclObject("$PSI")
    7361044max_array=EclObject("ARRAY")
     1045mdiff=EclObject("%DERIVATIVE")
    7371046max_gamma_incomplete=sage_op_dict[sage.functions.other.gamma_inc]
    7381047
    7391048def mrat_to_sage(expr):
    7401049    r"""
    741     Convert a maxima MRAT expression to Sage SR
     1050    Convert a Maxima MRAT expression to Sage SR.
    7421051   
     1052    INPUT:
     1053
     1054    - ``expr`` - ECL object; a Maxima MRAT expression
     1055
     1056    OUTPUT: symbolic expression
     1057
    7431058    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
     1059    The easiest way to translate those to SR is by first asking Maxima to give
    7451060    the generic representation of the object. That is what RATDISREP does in
    746     maxima.
     1061    Maxima.
     1062
     1063    EXAMPLES::
     1064
     1065        sage: from sage.interfaces.maxima_lib import maxima_lib, mrat_to_sage
     1066        sage: var('x y z')
     1067        (x, y, z)
     1068        sage: c = maxima_lib((x+y^2+z^9)/x^6+z^8/y).rat()
     1069        sage: c
     1070        (y*z^9+x^6*z^8+y^3+x*y)/(x^6*y)
     1071        sage: c.ecl()
     1072        <ECL: ((MRAT SIMP ($X $Y $Z)
     1073        ...>
     1074        sage: mrat_to_sage(c.ecl())
     1075        (x^6*z^8 + y*z^9 + y^3 + x*y)/(x^6*y)
    7471076    """
    7481077    return max_to_sr(meval(EclObject([[ratdisrep],expr])))
    7491078
    7501079def mqapply_to_sage(expr):
    7511080    r"""
    752     Special conversion rule for MQAPPLY expressions
     1081    Special conversion rule for MQAPPLY expressions.
     1082
     1083    INPUT:
     1084
     1085    - ``expr`` - ECL object; a Maxima MQAPPLY expression
     1086
     1087    OUTPUT: symbolic expression
     1088
     1089    MQAPPLY is used for function as li[x](y) and psi[x](y).
     1090
     1091    EXAMPLES::
     1092
     1093        sage: from sage.interfaces.maxima_lib import maxima_lib, mqapply_to_sage
     1094        sage: c = maxima_lib('li[2](3)')
     1095        sage: c.ecl()
     1096        <ECL: ((MQAPPLY SIMP) (($LI SIMP ARRAY) 2) 3)>
     1097        sage: mqapply_to_sage(c.ecl())
     1098        polylog(2, 3)
    7531099    """
    7541100    if caaadr(expr) == max_li:
    7551101        return sage.functions.log.polylog(max_to_sr(cadadr(expr)),max_to_sr(caddr(expr)))
     
    7611107        args=[max_to_sr(a) for a in max_args]
    7621108        return op(*args)
    7631109
     1110def mdiff_to_sage(expr):
     1111    r"""
     1112    Special conversion rule for %DERIVATIVE expressions.
     1113
     1114    INPUT:
     1115
     1116    - ``expr`` - ECL object; a Maxima %DERIVATIVE expression
     1117
     1118    OUTPUT: symbolic expression
     1119
     1120    EXAMPLES::
     1121
     1122        sage: from sage.interfaces.maxima_lib import maxima_lib, mdiff_to_sage
     1123        sage: f = maxima_lib('f(x)').diff('x',4)
     1124        sage: f.ecl()
     1125        <ECL: ((%DERIVATIVE SIMP) (($F SIMP) $X) $X 4)>
     1126        sage: mdiff_to_sage(f.ecl())
     1127        D[0, 0, 0, 0](f)(x)
     1128    """
     1129    return max_to_sr(expr.cadr()).diff(*[max_to_sr(e) for e in expr.cddr()])
     1130
    7641131def dummy_integrate(expr):
    7651132    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.
     1133    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.
     1134
     1135    INPUT:
     1136
     1137    - ``expr`` - ECL object; a Maxima %INTEGRATE expression
     1138
     1139    OUTPUT: symbolic expression
     1140
     1141    EXAMPLES::
     1142        sage: from sage.interfaces.maxima_lib import maxima_lib, dummy_integrate
     1143        sage: f = maxima_lib('f(x)').integrate('x')
     1144        sage: f.ecl()
     1145        <ECL: ((%INTEGRATE SIMP) (($F SIMP) $X) $X)>
     1146        sage: dummy_integrate(f.ecl())
     1147        integrate(f(x), x)
     1148
     1149    ::
     1150        sage: f = maxima_lib('f(x)').integrate('x',0,10)
     1151        sage: f.ecl()
     1152        <ECL: ((%INTEGRATE SIMP) (($F SIMP) $X) $X 0 10)>
     1153        sage: dummy_integrate(f.ecl())
     1154        integrate(f(x), x, 0, 10)
    7671155    """
    7681156    args=[max_to_sr(a) for a in cdr(expr)]
    7691157    if len(args) == 4 :
     
    7711159    else:
    7721160        return sage.symbolic.integration.integral.indefinite_integral(*args, hold=True)
    7731161
    774 def mdiff_to_sage(expr):
    775     return max_to_sr(expr.cadr()).diff(*[max_to_sr(e) for e in expr.cddr()])
    776 
     1162## The dictionaries
    7771163special_max_to_sage={
    778     EclObject("MRAT") : mrat_to_sage,
     1164    mrat : mrat_to_sage,
    7791165    mqapply : mqapply_to_sage,
    780     EclObject("%INTEGRATE") : dummy_integrate,
    781     mdiff : mdiff_to_sage
     1166    mdiff : mdiff_to_sage,
     1167    EclObject("%INTEGRATE") : dummy_integrate
    7821168}
    7831169
    7841170special_sage_to_max={
     
    7881174    sage.functions.other.Ei : lambda X : [[max_gamma_incomplete], 0, X]
    7891175}
    7901176
     1177
     1178## Dictionaries for symbols
    7911179sage_sym_dict={}
    7921180max_sym_dict={}
    7931181
     1182
     1183## Generic conversion functions
     1184
     1185max_i=EclObject("$%I")
    7941186def pyobject_to_max(obj):
     1187    r"""
     1188    Convert a (simple) Python object into a Maxima object.
     1189
     1190    INPUT:
     1191
     1192    - ``expr`` - Python object
     1193
     1194    OUTPUT: ECL object
     1195
     1196    .. note::
     1197    This uses functions defined in sage.libs.ecl.
     1198
     1199    EXAMPLES::
     1200        sage: from sage.interfaces.maxima_lib import pyobject_to_max
     1201        sage: pyobject_to_max(4)
     1202        <ECL: 4>
     1203        sage: pyobject_to_max('z')
     1204        <ECL: Z>
     1205        sage: var('x')
     1206        x
     1207        sage: pyobject_to_max(x)
     1208        Traceback (most recent call last):
     1209        ...
     1210        TypeError: Unimplemented type for python_to_ecl
     1211    """
    7951212    if isinstance(obj,sage.rings.rational.Rational):
    7961213        return EclObject(obj) if (obj.denom().is_one()) else EclObject([[rat], obj.numer(),obj.denom()])
    7971214    elif isinstance(obj,sage.rings.number_field.number_field_element_quadratic.NumberFieldElement_quadratic) and obj.parent().defining_polynomial().list() == [1,0,1]:
     
    8021219# This goes from SR to EclObject
    8031220def sr_to_max(expr):
    8041221    r"""
     1222    Convert a symbolic expression into a Maxima object.
     1223
     1224    INPUT:
     1225
     1226    - ``expr`` - symbolic expression
     1227
     1228    OUTPUT: ECL object
     1229
     1230    EXAMPLES::
     1231        sage: from sage.interfaces.maxima_lib import sr_to_max
     1232        sage: var('x')
     1233        x
     1234        sage: sr_to_max(x)
     1235        <ECL: $X>
     1236        sage: sr_to_max(cos(x))
     1237        <ECL: ((%COS) $X)>
     1238        sage: f = function('f',x)
     1239        sage: sr_to_max(f.diff())
     1240        <ECL: ((%DERIVATIVE) (($F) $X) $X 1)>
    8051241    """
    8061242    global sage_op_dict, max_op_dict
    8071243    global sage_sym_dict, max_sym_dict
     
    8221258            params = op.parameter_set()
    8231259            deriv_max = []
    8241260            [deriv_max.extend([sr_to_max(args[i]), EclObject(params.count(i))]) for i in set(params)]
    825             l = [mdiff,f]
     1261            l = [[mdiff],f]
    8261262            l.extend(deriv_max)
    8271263            return EclObject(l)
    8281264        elif (op in special_sage_to_max):
     
    8501286            return maxima(expr).ecl()
    8511287   
    8521288# This goes from EclObject to SR
    853 import sage.rings.real_double
     1289def max_to_sr(expr):
     1290    r"""
     1291    Convert a Maxima object into a symbolic expression.
    8541292
    855 def max_to_sr(expr):
     1293    INPUT:
     1294
     1295    - ``expr`` - ECL object
     1296
     1297    OUTPUT: symbolic expression
     1298
     1299    EXAMPLES::
     1300
     1301        sage: from sage.interfaces.maxima_lib import maxima_lib, max_to_sr
     1302        sage: f = maxima_lib('f(x)')
     1303        sage: f.ecl()
     1304        <ECL: (($F SIMP) $X)>
     1305        sage: max_to_sr(f.ecl())
     1306        f(x)
     1307
     1308    TESTS::
     1309
     1310        sage: from sage.interfaces.maxima_lib import sr_to_max, max_to_sr
     1311        sage: f = function('f',x).diff()
     1312        sage: bool(max_to_sr(sr_to_max(f)) == f)
     1313        True
     1314    """
    8561315    if expr.consp():
    8571316        op_max=caar(expr)
    8581317        if op_max in special_max_to_sage:
    8591318            return special_max_to_sage[op_max](expr)
    8601319        if not(op_max in max_op_dict):
    861             # This could be unsafe if the conversion to SR chenges the structure of expr
     1320            # This could be unsafe if the conversion to SR changes the structure of expr
    8621321            sage_expr=SR(maxima(expr))
    8631322            max_op_dict[op_max]=sage_expr.operator()
    8641323            sage_op_dict[sage_expr.operator()]=op_max