Esempio n. 1
0
    def cython_ann(line, cell):
        from Cython.Compiler.Main import compile as cy_compile
        from Cython.Compiler.CmdLine import parse_command_line
        from IPython.core import display
        import re

        with open("demo.pyx","wb") as f:
            f.write(cell.strip().encode("utf8"))
        options, sources = parse_command_line(["-a", "demo.pyx"])
        cy_compile(sources, options)
        with open("demo.html") as f:
            html = f.read().decode("utf8")

        html = u"\n".join([line for line in html.split("\n") if not line.startswith("<p>")])
        html = html.replace(u"display: none;", u"")
        html= re.sub(u"/\*.+?\*/.", u"", html, flags=re.DOTALL | re.MULTILINE)
        javascript = u"""
        <script>
        $("pre.code").css("background-color", "#ffffff").hide()
            .css("border-left", "2px solid #cccccc")
            .css("margin-left", "10px");
        $("pre.line").attr("onclick", "").click(function(){$(this).next().slideToggle();return 0;})
            .css("border-bottom", "1px solid #cccccc");
        $("span.error_goto").hide();
        </script>
        """
        display.display(display.HTML(html))
        display.display(display.HTML(javascript))
Esempio n. 2
0
def simple_cythonize(src, destdir=None, cwd=None, **cy_kwargs):
    """ Generates a C file from a Cython source file.

    Parameters
    ==========

    src: str
        Path to Cython source.
    destdir: str (optional)
        Path to output directory (default: '.').
    cwd: path string (optional)
        Root of relative paths (default: '.').
    **cy_kwargs:
        Second argument passed to cy_compile. Generates a .cpp file if ``cplus=True`` in ``cy_kwargs``,
        else a .c file.
    """
    from Cython.Compiler.Main import (
        default_options, CompilationOptions
    )
    from Cython.Compiler.Main import compile as cy_compile

    assert src.lower().endswith('.pyx') or src.lower().endswith('.py')
    cwd = cwd or '.'
    destdir = destdir or '.'

    ext = '.cpp' if cy_kwargs.get('cplus', False) else '.c'
    c_name = os.path.splitext(os.path.basename(src))[0] + ext

    dstfile = os.path.join(destdir, c_name)

    if cwd:
        ori_dir = os.getcwd()
    else:
        ori_dir = '.'
    os.chdir(cwd)
    try:
        cy_options = CompilationOptions(default_options)
        cy_options.__dict__.update(cy_kwargs)
        # Set language_level if not set by cy_kwargs
        # as not setting it is deprecated
        if 'language_level' not in cy_kwargs:
            cy_options.__dict__['language_level'] = 3
        cy_result = cy_compile([src], cy_options)
        if cy_result.num_errors > 0:
            raise ValueError("Cython compilation failed.")
        if os.path.realpath(os.path.dirname(src)) != os.path.realpath(destdir):
            if os.path.exists(dstfile):
                os.unlink(dstfile)
            shutil.move(os.path.join(os.path.dirname(src), c_name), destdir)
    finally:
        os.chdir(ori_dir)
    return dstfile
Esempio n. 3
0
def simple_cythonize(src, destdir=None, cwd=None, **cy_kwargs):
    """ Generates a C file from a Cython source file.

    Parameters
    ==========

    src: str
        Path to Cython source.
    destdir: str (optional)
        Path to output directory (default: '.').
    cwd: path string (optional)
        Root of relative paths (default: '.').
    **cy_kwargs:
        Second argument passed to cy_compile. Generates a .cpp file if ``cplus=True`` in ``cy_kwargs``,
        else a .c file.
    """
    from Cython.Compiler.Main import (
        default_options, CompilationOptions
    )
    from Cython.Compiler.Main import compile as cy_compile

    assert src.lower().endswith('.pyx') or src.lower().endswith('.py')
    cwd = cwd or '.'
    destdir = destdir or '.'

    ext = '.cpp' if cy_kwargs.get('cplus', False) else '.c'
    c_name = os.path.splitext(os.path.basename(src))[0] + ext

    dstfile = os.path.join(destdir, c_name)

    if cwd:
        ori_dir = os.getcwd()
    else:
        ori_dir = '.'
    os.chdir(cwd)
    try:
        cy_options = CompilationOptions(default_options)
        cy_options.__dict__.update(cy_kwargs)
        cy_result = cy_compile([src], cy_options)
        if cy_result.num_errors > 0:
            raise ValueError("Cython compilation failed.")
        if os.path.abspath(os.path.dirname(src)) != os.path.abspath(destdir):
            if os.path.exists(dstfile):
                os.unlink(dstfile)
            shutil.move(os.path.join(os.path.dirname(src), c_name), destdir)
    finally:
        os.chdir(ori_dir)
    return dstfile
Esempio n. 4
0
def simple_cythonize(src, destdir=None, cwd=None, **cy_kwargs):
    """ Generates a C file from a Cython source file.

    Parameters
    ==========

    src: str
        Path to Cython source.
    destdir: str (optional)
        Path to output directory (default: '.').
    cwd: path string (optional)
        Root of relative paths (default: '.').
    **cy_kwargs:
        Second argument passed to cy_compile. Generates a .cpp file if ``cplus=True`` in ``cy_kwargs``,
        else a .c file.
    """
    from Cython.Compiler.Main import default_options, CompilationOptions
    from Cython.Compiler.Main import compile as cy_compile

    assert src.lower().endswith(".pyx") or src.lower().endswith(".py")
    cwd = cwd or "."
    destdir = destdir or "."

    ext = ".cpp" if cy_kwargs.get("cplus", False) else ".c"
    c_name = os.path.splitext(os.path.basename(src))[0] + ext

    dstfile = os.path.join(destdir, c_name)

    if cwd:
        ori_dir = os.getcwd()
    else:
        ori_dir = "."
    os.chdir(cwd)
    try:
        cy_options = CompilationOptions(default_options)
        cy_options.__dict__.update(cy_kwargs)
        cy_result = cy_compile([src], cy_options)
        if cy_result.num_errors > 0:
            raise ValueError("Cython compilation failed.")
        if os.path.abspath(os.path.dirname(src)) != os.path.abspath(destdir):
            if os.path.exists(dstfile):
                os.unlink(dstfile)
            shutil.move(os.path.join(os.path.dirname(src), c_name), destdir)
    finally:
        os.chdir(ori_dir)
    return dstfile
Esempio n. 5
0
def simple_cythonize(src, destdir=None, cwd=None, logger=None,
                     full_module_name=None, only_update=False,
                     **cy_kwargs):
    """
    Generates a C file from a Cython source file.

    Parameters
    ----------
    src: path string
        path to Cython source
    destdir: path string (optional)
        Path to output directory (default: '.')
    cwd: path string (optional)
        Root of relative paths (default: '.')
    logger: logging.Logger
        info level used.
    full_module_name: string
        passed to cy_compile (default: None)
    only_update: bool
        Only cythonize if source is newer. default: False
    **cy_kwargs:
        second argument passed to cy_compile.
        Generates a .cpp file if cplus=True in cy_kwargs, else a .c file.
    """
    from Cython.Compiler.Main import (
        default_options, CompilationOptions
    )
    from Cython.Compiler.Main import compile as cy_compile

    assert src.lower().endswith('.pyx') or src.lower().endswith('.py')
    cwd = cwd or '.'
    destdir = destdir or '.'

    ext = '.cpp' if cy_kwargs.get('cplus', False) else '.c'
    c_name = os.path.splitext(os.path.basename(src))[0] + ext

    dstfile = os.path.join(destdir, c_name)

    if only_update:
        if not missing_or_other_newer(dstfile, src, cwd=cwd):
            msg = '{0} newer than {1}, did not re-cythonize.'.format(
                dstfile, src)
            if logger:
                logger.info(msg)
            else:
                print(msg)
            return dstfile

    if cwd:
        ori_dir = os.getcwd()
    else:
        ori_dir = '.'
    os.chdir(cwd)
    try:
        cy_options = CompilationOptions(default_options)
        cy_options.__dict__.update(cy_kwargs)
        if logger:
            logger.info("Cythonizing {0} to {1}".format(
                src, dstfile))
        cy_result = cy_compile([src], cy_options, full_module_name=full_module_name)
        if cy_result.num_errors > 0:
            raise ValueError("Cython compilation failed.")
        if os.path.abspath(os.path.dirname(
                src)) != os.path.abspath(destdir):
            if os.path.exists(dstfile):
                os.unlink(dstfile)
            shutil.move(os.path.join(os.path.dirname(src), c_name),
                        destdir)
    finally:
        os.chdir(ori_dir)
    return dstfile
Esempio n. 6
0
# It can be run in the build process of pyopenms when manual changes to the pyx
# files need to be made (not recommended!).
#
# == taken from autowrap/Main.py run(), lower part
from __future__ import print_function

infile = "pyopenms/pyopenms.pyx"

import cPickle
persisted_data_path = "include_dir.bin"
autowrap_include_dirs = cPickle.load(open(persisted_data_path, "rb"))
# autowrap_include_dirs = ['/usr/local/lib/python2.7/dist-packages/autowrap/data_files/boost', '/usr/local/lib/python2.7/dist-packages/autowrap/data_files', '/path/to/pyOpenMS/pxds', 'from Map cimport Map as _Map']

from Cython.Compiler.Main import compile as cy_compile, CompilationOptions
from Cython.Compiler.Options import directive_defaults
directive_defaults["boundscheck"] = False
directive_defaults["wraparound"] = False

options = dict(
    include_path=autowrap_include_dirs,
    compiler_directives=directive_defaults,
    #output_dir=".",
    #gdb_debug=True,
    cplus=True)

print("Compiling with Cython the file", infile)
print("Using include_path", autowrap_include_dirs)
options = CompilationOptions(**options)
cy_compile(infile, options=options)
print("Success!")