Beispiel #1
0
def get_distutils_extension(modname, pyxfilename, language_level=None):
#    try:
#        import hashlib
#    except ImportError:
#        import md5 as hashlib
#    extra = "_" + hashlib.md5(open(pyxfilename).read()).hexdigest()  
#    modname = modname + extra
    extension_mod,setup_args = handle_special_build(modname, pyxfilename)
    if not extension_mod:
        from distutils.extension import Extension
        extension_mod = Extension(name = modname, sources=[pyxfilename])
        if language_level is not None:
            extension_mod.cython_directives = {'language_level': language_level}
    return extension_mod,setup_args
Beispiel #2
0
def get_distutils_extension(modname, pyxfilename, language_level=None):
#    try:
#        import hashlib
#    except ImportError:
#        import md5 as hashlib
#    extra = "_" + hashlib.md5(open(pyxfilename).read()).hexdigest()  
#    modname = modname + extra
    extension_mod,setup_args = handle_special_build(modname, pyxfilename)
    if not extension_mod:
        if not isinstance(pyxfilename, str):
            # distutils is stupid in Py2 and requires exactly 'str'
            # => encode accidentally coerced unicode strings back to str
            pyxfilename = pyxfilename.encode(sys.getfilesystemencoding())
        from distutils.extension import Extension
        extension_mod = Extension(name = modname, sources=[pyxfilename])
        if language_level is not None:
            extension_mod.cython_directives = {'language_level': language_level}
    return extension_mod,setup_args
# Recover the CLASS version
with open(os.path.join(include_folder, 'common.h'), 'r') as v_file:
    for line in v_file:
        if line.find("_VERSION_") != -1:
            # get rid of the " and the v
            VERSION = line.split()[-1][2:-1]
            break

# Define cython extension and fix Python version
classy_ext = Extension("classy", [os.path.join(classy_folder, "classy.pyx")],
                           include_dirs=[nm.get_include(), include_folder],
                           libraries=liblist,
                           library_dirs=[root_folder, GCCPATH],
                           extra_link_args=['-lgomp'])
#import six
#classy_ext.cython_directives = {'language_level': "3" if six.PY3 else "2"}

classy_ext.cython_directives = {'language_level': "2"}


setup(
    name='classy',
    version=VERSION,
    description='Python interface to the Cosmological Boltzmann code CLASS',
    url='http://www.class-code.net',
    cmdclass={'build_ext': build_ext},
    ext_modules=[classy_ext],
    #data_files=[('bbn', ['../bbn/sBBN.dat'])]
)
Beispiel #4
0
    if "/" in ext_name:
        ext_name = ext_name.replace("/", ".")

    sources = [pyxfile]
    extmod = Extension(ext_name,
                       sources=sources,
                       libraries=['cpptraj'],
                       language='c++',
                       library_dirs=[libdir, ],
                       include_dirs=[cpptraj_include, pytraj_home],
                       extra_compile_args=extra_compile_args,
                       extra_link_args=extra_link_args)

    extmod.cython_directives = {
        'embedsignature': True,
        'boundscheck': False,
        'wraparound': False,
    }
    ext_modules.append(extmod)

setup_args = {}
packages = [
    'pytraj',
    'pytraj.utils',
    'pytraj.actions',
    'pytraj.analyses',
    'pytraj.datasets',
    'pytraj.externals',
    'pytraj.trajs',
    'pytraj.datafiles',
    'pytraj.datafiles.Ala3',
Beispiel #5
0
def c_to_dll(filename, ext = None, force_rebuild = 0,
               build_in_temp=False, cbuild_dir=None, setup_args={},
               reload_support=False, inplace=False):
    """Compile a C file to a DLL and return the name of the generated .so 
       or .dll ."""
    assert os.path.exists(filename), "Could not find %s" % os.path.abspath(filename)

    path, name = os.path.split(os.path.abspath(filename))

    if not ext:
        modname, extension = os.path.splitext(name)
        assert extension in (".c", ".py"), extension
        if not HAS_CYTHON:
            filename = filename[:-len(extension)] + '.c'
        ext = Extension(name=modname, sources=[filename])

    if not cbuild_dir:
        cbuild_dir = os.path.join(path, "_cbld")

    package_base_dir = path
    for package_name in ext.name.split('.')[-2::-1]:
        package_base_dir, pname = os.path.split(package_base_dir)
        if pname != package_name:
            # something is wrong - package path doesn't match file path
            package_base_dir = None
            break

    script_args=setup_args.get("script_args",[])
    if DEBUG or "--verbose" in script_args:
        quiet = "--verbose"
    else:
        quiet = "--quiet"
    args = [quiet, "build_ext"]
    if force_rebuild:
        args.append("--force")
    if inplace and package_base_dir:
        args.extend(['--build-lib', package_base_dir])
        if ext.name == '__init__' or ext.name.endswith('.__init__'):
            # package => provide __path__ early
            if not hasattr(ext, 'cython_directives'):
                ext.cython_directives = {'set_initial_path' : 'SOURCEFILE'}
            elif 'set_initial_path' not in ext.cython_directives:
                ext.cython_directives['set_initial_path'] = 'SOURCEFILE'

    if HAS_CYTHON and build_in_temp:
        args.append("--pyrex-c-in-temp")
    sargs = setup_args.copy()
    sargs.update({
        "script_name": None,
        "script_args": args + script_args,
    })
    # late import, in case setuptools replaced it
    from distutils.dist import Distribution
    dist = Distribution(sargs)
    if not dist.ext_modules:
        dist.ext_modules = []
    dist.ext_modules.append(ext)
    if HAS_CYTHON:
        dist.cmdclass = {'build_ext': build_ext}
    build = dist.get_command_obj('build')
    build.build_base = cbuild_dir

    cfgfiles = dist.find_config_files()
    dist.parse_config_files(cfgfiles)

    try:
        ok = dist.parse_command_line()
    except DistutilsArgError:
        raise

    if DEBUG:
        print("options (after parsing command line):")
        dist.dump_option_dicts()
    assert ok


    try:
        obj_build_ext = dist.get_command_obj("build_ext")
        dist.run_commands()
        so_path = obj_build_ext.get_outputs()[0]
        if obj_build_ext.inplace:
            # Python distutils get_outputs()[ returns a wrong so_path 
            # when --inplace ; see http://bugs.python.org/issue5977
            # workaround:
            so_path = os.path.join(os.path.dirname(filename),
                                   os.path.basename(so_path))
        if reload_support:
            org_path = so_path
            timestamp = os.path.getmtime(org_path)
            global _reloads
            last_timestamp, last_path, count = _reloads.get(org_path, (None,None,0) )
            if last_timestamp == timestamp:
                so_path = last_path
            else:
                basename = os.path.basename(org_path)
                while count < 100:
                    count += 1
                    r_path = os.path.join(obj_build_ext.build_lib,
                                          basename + '.reload%s'%count)
                    try:
                        import shutil # late import / reload_support is: debugging
                        try:
                            # Try to unlink first --- if the .so file
                            # is mmapped by another process,
                            # overwriting its contents corrupts the
                            # loaded image (on Linux) and crashes the
                            # other process. On Windows, unlinking an
                            # open file just fails.
                            if os.path.isfile(r_path):
                                os.unlink(r_path)
                        except OSError:
                            continue
                        shutil.copy2(org_path, r_path)
                        so_path = r_path
                    except IOError:
                        continue
                    break
                else:
                    # used up all 100 slots 
                    raise ImportError("reload count for %s reached maximum"%org_path)
                _reloads[org_path]=(timestamp, so_path, count)
        return so_path
    except KeyboardInterrupt:
        sys.exit(1)
    except (IOError, os.error):
        exc = sys.exc_info()[1]
        error = grok_environment_error(exc)

        if DEBUG:
            sys.stderr.write(error + "\n")
        raise
Beispiel #6
0
def pyx_to_dll(filename,
               ext=None,
               force_rebuild=0,
               build_in_temp=False,
               pyxbuild_dir=None,
               setup_args={},
               reload_support=False,
               inplace=False):
    """Compile a PYX file to a DLL and return the name of the generated .so 
       or .dll ."""
    assert os.path.exists(
        filename), "Could not find %s" % os.path.abspath(filename)

    path, name = os.path.split(os.path.abspath(filename))

    if not ext:
        modname, extension = os.path.splitext(name)
        assert extension in (".pyx", ".py"), extension
        if not HAS_CYTHON:
            filename = filename[:-len(extension)] + '.c'
        ext = Extension(name=modname, sources=[filename])

    if not pyxbuild_dir:
        pyxbuild_dir = os.path.join(path, "_pyxbld")

    package_base_dir = path
    for package_name in ext.name.split('.')[-2::-1]:
        package_base_dir, pname = os.path.split(package_base_dir)
        if pname != package_name:
            # something is wrong - package path doesn't match file path
            package_base_dir = None
            break

    script_args = setup_args.get("script_args", [])
    if DEBUG or "--verbose" in script_args:
        quiet = "--verbose"
    else:
        quiet = "--quiet"
    args = [quiet, "build_ext"]
    if force_rebuild:
        args.append("--force")
    if inplace and package_base_dir:
        args.extend(['--build-lib', package_base_dir])
        if ext.name == '__init__' or ext.name.endswith('.__init__'):
            # package => provide __path__ early
            if not hasattr(ext, 'cython_directives'):
                ext.cython_directives = {'set_initial_path': 'SOURCEFILE'}
            elif 'set_initial_path' not in ext.cython_directives:
                ext.cython_directives['set_initial_path'] = 'SOURCEFILE'

    if HAS_CYTHON and build_in_temp:
        args.append("--pyrex-c-in-temp")
    sargs = setup_args.copy()
    sargs.update({"script_name": None, "script_args": args + script_args})
    dist = Distribution(sargs)
    if not dist.ext_modules:
        dist.ext_modules = []
    dist.ext_modules.append(ext)
    if HAS_CYTHON:
        dist.cmdclass = {'build_ext': build_ext}
    build = dist.get_command_obj('build')
    build.build_base = pyxbuild_dir

    cfgfiles = dist.find_config_files()
    dist.parse_config_files(cfgfiles)

    try:
        ok = dist.parse_command_line()
    except DistutilsArgError:
        raise

    if DEBUG:
        print("options (after parsing command line):")
        dist.dump_option_dicts()
    assert ok

    try:
        obj_build_ext = dist.get_command_obj("build_ext")
        dist.run_commands()
        so_path = obj_build_ext.get_outputs()[0]
        if obj_build_ext.inplace:
            # Python distutils get_outputs()[ returns a wrong so_path
            # when --inplace ; see http://bugs.python.org/issue5977
            # workaround:
            so_path = os.path.join(os.path.dirname(filename),
                                   os.path.basename(so_path))
        if reload_support:
            org_path = so_path
            timestamp = os.path.getmtime(org_path)
            global _reloads
            last_timestamp, last_path, count = _reloads.get(
                org_path, (None, None, 0))
            if last_timestamp == timestamp:
                so_path = last_path
            else:
                basename = os.path.basename(org_path)
                while count < 100:
                    count += 1
                    r_path = os.path.join(obj_build_ext.build_lib,
                                          basename + '.reload%s' % count)
                    try:
                        import shutil  # late import / reload_support is: debugging
                        try:
                            # Try to unlink first --- if the .so file
                            # is mmapped by another process,
                            # overwriting its contents corrupts the
                            # loaded image (on Linux) and crashes the
                            # other process. On Windows, unlinking an
                            # open file just fails.
                            if os.path.isfile(r_path):
                                os.unlink(r_path)
                        except OSError:
                            continue
                        shutil.copy2(org_path, r_path)
                        so_path = r_path
                    except IOError:
                        continue
                    break
                else:
                    # used up all 100 slots
                    raise ImportError("reload count for %s reached maximum" %
                                      org_path)
                _reloads[org_path] = (timestamp, so_path, count)
        return so_path
    except KeyboardInterrupt:
        sys.exit(1)
    except (IOError, os.error):
        exc = sys.exc_info()[1]
        error = grok_environment_error(exc)

        if DEBUG:
            sys.stderr.write(error + "\n")
        raise
Beispiel #7
0
            # get rid of the " and the v
            VERSION = line.split()[-1][2:-1]
            break

classy_ext = Extension("classy", [os.path.join(classy_folder, "classy.pyx")],
                       include_dirs=[
                           nm.get_include(), include_folder,
                           "/Users/rmurgia/Desktop/OpenBLAS/include"
                       ],
                       libraries=liblist,
                       library_dirs=[root_folder, GCCPATH],
                       extra_link_args=[
                           '/Users/rmurgia/Desktop/OpenBLAS/lib/libopenblas.a',
                           '-lgomp', '-lgsl', '-lgslcblas',
                           '-Wl,-rpath,/usr/local/opt/gcc/lib/gcc/9/'
                       ])

import six
classy_ext.cython_directives = {'language_level': "3" if six.PY3 else "2"}

setup(
    name='classy',
    version=VERSION,
    description='Python interface to the Cosmological Boltzmann code CLASS',
    url='http://www.class-code.net',
    cmdclass={'build_ext': build_ext},
    ext_modules=[classy_ext],
    #ext_modules=[classy_ext],
    #data_files=[('bbn', ['../bbn/sBBN.dat'])]
)
Beispiel #8
0

pymilne_src = ["pyMilne.pyx"]
pymilne_inc = ["./",numpy.get_include()]

extension_kwargs = {
    'sources': pymilne_src,
    'include_dirs': pymilne_inc,
}


extension_kwargs = pkgconfig('eigen3', extension_kwargs)
extension_kwargs = pkgconfig('fftw3', extension_kwargs)

extension = Extension("pyMilne",
                      language="c++",
                      extra_compile_args=comp_flags,
                      extra_link_args=link_opts,
                      **extension_kwargs)

extension.cython_directives = {'language_level': "3"}

setup(
    name = 'pyMilne',
    version = '1.0',
    author = 'J. de la Cruz Rodriguez (ISP-SU 2020)',
    ext_modules=[extension],
    cmdclass = {'build_ext': build_ext}
)

Beispiel #9
0
    sources = [pyxfile]
    extmod = Extension(ext_name,
                       sources=sources,
                       libraries=['cpptraj'],
                       language='c++',
                       library_dirs=[
                           libdir,
                       ],
                       include_dirs=[cpptraj_include, pytraj_home],
                       extra_compile_args=extra_compile_args,
                       extra_link_args=extra_link_args)

    extmod.cython_directives = {
        'embedsignature': True,
        'boundscheck': False,
        'wraparound': False,
    }
    ext_modules.append(extmod)

setup_args = {}
packages = [
    'pytraj',
    'pytraj.utils',
    'pytraj.actions',
    'pytraj.analyses',
    'pytraj.datasets',
    'pytraj.externals',
    'pytraj.trajs',
    'pytraj.datafiles',
    'pytraj.datafiles.Ala3',
Beispiel #10
0
#==================================================================================================

# run with:
# python setup.py build_ext --inplace

# before running Python program you will need to export the C++ shared library path:
# export LD_LIBRARY_PATH=/path/to/URT/lib:$LD_LIBRARY_PATH

from distutils.core import setup
from distutils.extension import Extension
from Cython.Distutils import build_ext
from Cython.Build import cythonize
from numpy import get_include

# linking to C++ libURT.so library
ext = Extension('CyURT',
               sources = ['CyURT.pyx'],
               include_dirs = [get_include()],
               libraries = ['URT'],
               extra_compile_args = ['-std=c++11','-Wall','-march=native','-DUSE_BLAZE','-DBLAZE_BLAS_INCLUDE_FILE <mkl_cblas.h>'],
               extra_link_args = ['-L../lib'],
               language='c++')

# NB: in extra_compile_args replace the header <mkl_cblas.h> by the one associated with the BLAS/LAPACK replacement library, for example OpenBLAS will use the header <cblas.h>

ext.cython_directives = {'boundscheck': False,'wraparound': False}
# turn off bounds-checking for entire function
# turn off negative index wrapping for entire function

setup(cmdclass = {'build_ext' : build_ext}, ext_modules = [ext])
Beispiel #11
0
                sources=[
                    os.path.join(libvsc_dir, 'python', "core.pyx"),
                    os.path.join(libvsc_dir, 'python', 'VisitorProxy.cpp'),
                    os.path.join(libvsc_dir, 'python', 'py_get_vsc.cpp'),
                    os.path.join(libvsc_dir, 'python',
                                 'ModelFieldDataClosure.cpp'),
                    os.path.join(libvsc_dir, 'python',
                                 'ModelStructCreateHookClosure.cpp'),
                    os.path.join(libvsc_dir, 'python', 'VscTasks.cpp'),
                ],
                language="c++",
                include_dirs=[
                    os.path.join(libvsc_dir, 'src'),
                    os.path.join(libvsc_dir, 'src', 'include')
                ])
ext.cython_directives = {'language_level': '3'}

setup(name="libvsc",
      packages=['libvsc'],
      package_dir={'': 'python'},
      author="Matthew Ballance",
      author_email="*****@*****.**",
      description=("Provides the core TbLink-RPC library"),
      license="Apache 2.0",
      keywords=["SystemVerilog", "Verilog", "RTL", "Python"],
      url="https://github.com/fvutils/libvsc",
      entry_points={
          'console_scripts': ['tblink-rpc = tblink_rpc.__main__:main']
      },
      install_requires=[],
      setup_requires=['setuptools_scm', 'cython'],
Beispiel #12
0
with open(os.path.join(include_folder, 'common.h'), 'r') as v_file:
    for line in v_file:
        if line.find("_VERSION_") != -1:
            # get rid of the " and the v
            VERSION = line.split()[-1][2:-1]
            break

# Define cython extension and fix Python version
classy_ext = Extension("classy", [os.path.join(classy_folder, "classy.pyx")],
                       include_dirs=[
                           nm.get_include(), include_folder, heat_folder,
                           recfast_folder, hyrec_folder
                       ],
                       libraries=liblist,
                       library_dirs=[root_folder, GCCPATH],
                       extra_link_args=['-lgomp'])
import sys
classy_ext.cython_directives = {
    'language_level': "3" if sys.version_info.major >= 3 else "2"
}

setup(
    name='classy',
    version=VERSION,
    description='Python interface to the Cosmological Boltzmann code CLASS',
    url='http://www.class-code.net',
    cmdclass={'build_ext': build_ext},
    ext_modules=[classy_ext],
    #data_files=[('bbn', ['../bbn/sBBN.dat'])]
)