Ticket #11954: trac_11954-cython-doc.patch

File trac_11954-cython-doc.patch, 12.7 KB (added by John Palmieri, 11 years ago)
  • doc/en/reference/misc.rst

    # HG changeset patch
    # User J. H. Palmieri <palmieri@math.washington.edu>
    # Date 1319576040 25200
    # Node ID a75b310d0ee836287cd93a634a27002855994131
    # Parent  92cdbddc62099547cf5a7b62538c9d78c70c2ba0
    #11954: improve the documentation in the file sage/misc/cython.py,
    and include it in the reference manual
    
    diff --git a/doc/en/reference/misc.rst b/doc/en/reference/misc.rst
    a b Miscellaneous 
    4747   sage/misc/classcall_metaclass
    4848   sage/misc/sage_unittest
    4949   sage/misc/randstate
    50    
     50   sage/misc/cython
  • sage/misc/cython.py

    diff --git a/sage/misc/cython.py b/sage/misc/cython.py
    a b  
    22Cython -- C-Extensions for Python
    33
    44AUTHORS:
    5     -- William Stein (2006-01-18): initial version
    6     -- William Stein (2007-07-28): update from sagex to cython
    7     -- Martin Albrecht & William Stein (2011-08): cfile & cargs
     5
     6- William Stein (2006-01-18): initial version
     7- William Stein (2007-07-28): update from sagex to cython
     8- Martin Albrecht & William Stein (2011-08): cfile & cargs
    89"""
    910
    1011#*****************************************************************************
    from misc import SPYX_TMP, SAGE_ROOT, SA 
    2122from sage.misc.misc import UNAME
    2223
    2324def cblas():
     25    """
     26    Return the name of the cblas library on this system.  If the
     27    environment variable :envvar:`$SAGE_CBLAS` is set, just return its
     28    value.  If not, return 'cblas' if :file:`/usr/lib/libcblas.so`
     29    or :file:`/usr/lib/libcblas.dylib` exists, return 'blas' if
     30    :file:`/usr/lib/libblas.dll.a` exists, and return 'gslcblas'
     31    otherwise.
     32
     33    EXAMPLES::
     34
     35        sage: sage.misc.cython.cblas() # random -- depends on OS, etc.
     36        'cblas'
     37    """
    2438    if os.environ.has_key('SAGE_CBLAS'):
    2539        return os.environ['SAGE_CBLAS']
    2640    elif os.path.exists('/usr/lib/libcblas.dylib') or \
    def cblas(): 
    3953# We should be using the Accelerate FrameWork on OS X, but that requires
    4054# some magic due to distutils having ridden on the short bus :)
    4155def atlas():
     56    """
     57    Returns the name of the ATLAS library to use.  On Darwin or
     58    Cygwin, this is 'blas', and otherwise it is 'atlas'.
     59
     60    EXAMPLES::
     61
     62        sage: sage.misc.cython.atlas() # random -- depends on OS
     63        'atlas'
     64    """
    4265    if UNAME == "Darwin" or "CYGWIN" in UNAME:
    4366        return 'blas'
    4467    else:
    standard_libs = ['mpfr', 'gmp', 'gmpxx', 
    5982offset = 0
    6083
    6184def parse_keywords(kwd, s):
    62     """
     85    r"""
    6386    Given a keyword kwd and a string s, return a list of all arguments
    6487    on the same line as that keyword in s, as well as a new copy of
    6588    s in which each occurrence of kwd is in a comment. If a comment
    6689    already occurs on the line containing kwd, no words after the #
    6790    are added to the list.
    6891
    69     EXAMPLES:
     92    EXAMPLES::
     93   
    7094        sage: sage.misc.cython.parse_keywords('clib', " clib foo bar baz\n #cinclude bar\n")
    7195        (['foo', 'bar', 'baz'], ' #clib foo bar baz\n #cinclude bar\n')
    7296
    def parse_keywords(kwd, s): 
    106130    return v, s
    107131
    108132def environ_parse(s):
     133    r"""
     134    Given a string s, find each substring of the form '\$ABC'.  If the
     135    environment variable :envvar:`ABC` is set, replace '\$ABC' with its
     136    value and move on to the next such substring.  If it is not set,
     137    stop parsing there.
     138
     139    EXAMPLES::
     140
     141        sage: from sage.misc.cython import environ_parse
     142        sage: environ_parse('$SAGE_ROOT') == SAGE_ROOT
     143        True
     144        sage: environ_parse('$THIS_IS_NOT_DEFINED_ANYWHERE')
     145        '$THIS_IS_NOT_DEFINED_ANYWHERE'
     146        sage: os.environ['DEFINE_THIS'] = 'hello'
     147        sage: environ_parse('$DEFINE_THIS/$THIS_IS_NOT_DEFINED_ANYWHERE/$DEFINE_THIS')
     148        'hello/$THIS_IS_NOT_DEFINED_ANYWHERE/$DEFINE_THIS'
     149    """
    109150    i = s.find('$')
    110151    if i == -1:
    111152        return s
    def environ_parse(s): 
    122163    return environ_parse(s)
    123164
    124165def pyx_preparse(s):
    125     """
     166    r"""
    126167    Preparse a pyx file
    127       * include cdefs.pxi, interrupt.pxi, stdsage.pxi
    128       * parse clang pragma (c or c++)
    129       * parse clib pragma (additional libraries to link in)
    130       * parse cinclude (additional include directories)
    131       * parse cfile (additional files to be included)
    132       * parse cargs (additional parameters passed to the compiler)
     168
     169    * include cdefs.pxi, interrupt.pxi, stdsage.pxi
     170    * parse clang pragma (c or c++)
     171    * parse clib pragma (additional libraries to link in)
     172    * parse cinclude (additional include directories)
     173    * parse cfile (additional files to be included)
     174    * parse cargs (additional parameters passed to the compiler)
    133175
    134176    The pragmas:
    135177
    def pyx_preparse(s): 
    149191
    150192    - ``cargs`` - additional parameters passed to the compiler
    151193
    152     OUTPUT:
    153        preamble, libs, includes, language, files, args
     194    OUTPUT: preamble, libs, includes, language, files, args
    154195
    155     EXAMPLE:
     196    EXAMPLES::
     197
    156198        sage: from sage.misc.cython import pyx_preparse
    157199        sage: pyx_preparse("")
    158200        ('\ninclude "interrupt.pxi"  # ctrl-c interrupt block support\ninclude "stdsage.pxi"  # ctrl-c interrupt block support\n\ninclude "cdefs.pxi"\n',
    def cython(filename, verbose=False, comp 
    258300           use_cache=False, create_local_c_file=False, annotate=True, sage_namespace=True,
    259301           create_local_so_file=False):
    260302    """
    261     TODO: document this function!
     303    Compile a Cython file.  This converts a Cython file to a C (or C++
     304    file), and then compiles that.  The .c file and the .so file are
     305    created in a temporary directory.
     306
     307    INPUTS:
     308
     309    - ``filename`` - the name of the file to be compiled.  Should end
     310      with 'pyx'.
     311
     312    - ``verbose`` (bool, default False) - if True, print debugging
     313      information.
     314
     315    - ``compile_message`` (bool, default False) - if True, print
     316      'Compiling <filename>...'
     317
     318    - ``use_cache`` (bool, default False) - if True, check the
     319      temporary build directory to see if there is already a
     320      corresponding .so file.  If so, and if the .so file is newer
     321      than the Cython file, don't recompile, just reuse the .so file.
     322
     323    - ``create_local_c_file`` (bool, default False) - if True, save a
     324      copy of the .c file in the current directory.
     325
     326    - ``annotate`` (bool, default True) - if True, create an html file
     327      which annotates the conversion from .pyx to .c.  By default this
     328      is only created in the temporary directory, but if
     329      ``create_local_c_file`` is also True, then save a copy of the
     330      .html file in the current directory.
     331
     332    - ``sage_namespace`` (bool, default True) - if True, import
     333      ``sage.all``.
     334
     335    - ``create_local_so_file`` (bool, default False) - if True, save a
     336      copy of the compiled .so file in the current directory.
     337
     338    TODO: doctests
    262339    """
    263340    if not filename.endswith('pyx'):
    264341        print "File (=%s) should have extension .pyx"%filename
    setup(ext_modules = ext_modules, 
    461538
    462539
    463540def subtract_from_line_numbers(s, n):
     541    r"""
     542    Given a string ``s`` and an integer ``n``, for any line of ``s``
     543    which has the form 'text:NUM:text' subtract ``n`` from NUM and
     544    return 'text:(NUM-n):text'.  Return other lines of ``s`` without
     545    change.
     546
     547    EXAMPLES::
     548
     549        sage: from sage.misc.cython import subtract_from_line_numbers
     550        sage: subtract_from_line_numbers('hello:1234:hello', 3)
     551        'hello:1231:hello\n'
     552        sage: subtract_from_line_numbers('text:123\nhello:1234:', 3)
     553        'text:123\nhello:1231:\n'
     554    """
    464555    ans = []
    465556    for X in s.split('\n'):
    466557        i = X.find(':')
    def cython_lambda(vars, expr, 
    486577    WARNING: This implementation is not well tested.
    487578
    488579    INPUT:
    489         vars -- list of pairs (variable name, c-data type), where
    490                 the variable names and data types are strings.
    491             OR -- a string such as
    492                         'double x, int y, int z'
    493         expr -- an expression involving the vars and constants;
    494                 You can access objects defined in the current
    495                 module scope globals() using sagobject_name.
    496                 See the examples below.
     580
     581    - ``vars`` - list of pairs (variable name, c-data type), where
     582      the variable names and data types are strings, OR a string such
     583      as 'double x, int y, int z'
     584
     585    - ``expr`` - an expression involving the vars and constants; you
     586      can access objects defined in the current module scope globals()
     587      using sagobject_name.  See the examples below.
    497588
    498589    EXAMPLES:
     590   
    499591    We create a Lambda function in pure Python (using the r to make sure the 3.2
    500     is viewed as a Python float):
     592    is viewed as a Python float)::
     593
    501594        sage: f = lambda x,y: x*x + y*y + x + y + 17r*x + 3.2r
    502595
    503     We make the same Lambda function, but in a compiled form.
     596    We make the same Lambda function, but in a compiled form. ::
     597
    504598        sage: g = cython_lambda('double x, double y', 'x*x + y*y + x + y + 17*x + 3.2')  # optional -- gcc
    505599        sage: g(2,3)                                                                     # optional -- gcc
    506600        55.200000000000003
    507601        sage: g(0,0)                                                                     # optional -- gcc
    508602        3.2000000000000002
    509603
    510     We access a global function and variable.
     604    We access a global function and variable. ::
     605
    511606        sage: a = 25
    512607        sage: f = cython_lambda('double x', 'sage.math.sin(x) + sage.a')                 # optional -- gcc
    513608        sage: f(10)                                                                      # optional -- gcc
    def cython_create_local_so(filename): 
    550645    Compile filename and make it available as a loadable shared object file.
    551646   
    552647    INPUT:
    553         filename -- string: a Cython (formerly SageX) (.spyx) file
     648
     649    - ``filename`` - string: a Cython (formerly SageX) (.spyx) file
    554650   
    555     OUTPUT:
    556         None
     651    OUTPUT: None
    557652   
    558     EFFECT:
    559         A compiled, python "importable" loadable shared object file is created.
     653    EFFECT: A compiled, python "importable" loadable shared object file is created.
    560654
    561     NOTE:
     655    .. note::
     656
    562657        Shared object files are {NOT} reloadable. The intent is for
    563658        imports in other scripts. A possible development cycle might
    564659        go thus:
    565660 
    566             - Attach a .spyx file
    567             - Interactively test and edit it to your satisfaction
    568             - Use cython_create_local_so to create the shared object file
    569             - Import the .so file in other scripts
     661        - Attach a .spyx file
     662        - Interactively test and edit it to your satisfaction
     663        - Use cython_create_local_so to create the shared object file
     664        - Import the .so file in other scripts
    570665
    571     EXAMPLE:
     666    EXAMPLES::
     667
    572668        sage: curdir = os.path.abspath(os.curdir)
    573669        sage: dir = tmp_dir(); os.chdir(dir)
    574670        sage: f = file('hello.spyx', 'w')
    def cython_create_local_so(filename): 
    584680        sage: os.chdir(curdir)
    585681
    586682    AUTHORS:
    587         -- David Fu (2008-04-09): initial version
     683
     684    - David Fu (2008-04-09): initial version
    588685    """
    589686    cython(filename, compile_message=True, use_cache=False, create_local_so_file=True)
    590687
    def sanitize(f): 
    595692
    596693    This means that the characters are all alphanumeric or _'s and
    597694    doesn't begin with a numeral.
     695
     696    EXAMPLES::
     697
     698        sage: from sage.misc.cython import sanitize
     699        sage: sanitize('abc')
     700        'abc'
     701        sage: sanitize('abc/def')
     702        'abc_def'
     703        sage: sanitize('123/def-hij/file.py')
     704        '_123_def_hij_file_py'
    598705    """
    599706    s = ''
    600707    if f[0].isdigit():
    def sanitize(f): 
    608715
    609716
    610717def compile_and_load(code):
    611     """
     718    r"""
    612719    INPUT:
    613720
    614         - ``code`` -- string containing code that could be in a .pyx
    615           file that is attached or put in a %cython block in the
    616           notebook.
     721    - ``code`` -- string containing code that could be in a .pyx file
     722      that is attached or put in a %cython block in the notebook.
    617723
    618     OUTPUT:
    619    
    620         - a module, which results from compiling the given code and
    621           importing it
     724    OUTPUT: a module, which results from compiling the given code and
     725    importing it
    622726
    623727    EXAMPLES::
    624728
    def import_test(name): 
    668772    Cython programs.
    669773
    670774    INPUT:
    671         - ``name`` -- string; name of a key to the TESTS dictionary above
    672775
    673     OUTPUT:
    674         - a module, which results from compiling the given code and importing it
     776    - ``name`` -- string; name of a key to the TESTS dictionary above
     777
     778    OUTPUT: a module, which results from compiling the given code and importing it
    675779
    676780    EXAMPLES::
    677    
     781
    678782        sage: module = sage.misc.cython.import_test("trac11680b")
    679783        sage: module.f(2,3,4)
    680784        9