Esempio n. 1
0
    def _find_hdf5_compiler_settings(self, olds, mpi):
        """Returns (include_dirs, lib_dirs, define_macros)"""
        # Specified lib/include dirs explicitly
        if self.hdf5_includedir or self.hdf5_libdir:
            inc_dirs = [self.hdf5_includedir] if self.hdf5_includedir else []
            lib_dirs = [self.hdf5_libdir] if self.hdf5_libdir else []
            return (inc_dirs, lib_dirs, [])

        # Specified a prefix dir (e.g. '/usr/local')
        if self.hdf5:
            inc_dirs = [op.join(self.hdf5, 'include')]
            lib_dirs = [op.join(self.hdf5, 'lib')]
            if sys.platform.startswith('win'):
                lib_dirs.append(op.join(self.hdf5, 'bin'))
            return (inc_dirs, lib_dirs, [])

        # Specified a name to be looked up in pkgconfig
        if self.hdf5_pkgconfig_name:
            import pkgconfig
            if not pkgconfig.exists(self.hdf5_pkgconfig_name):
                raise ValueError(
                    f"No pkgconfig information for {self.hdf5_pkgconfig_name}"
                )
            pc = pkgconfig.parse(self.hdf5_pkgconfig_name)
            return (pc['include_dirs'], pc['library_dirs'], pc['define_macros'])

        # Re-use previously specified settings
        if olds.get('hdf5_includedirs') and olds.get('hdf5_libdirs'):
            return (
                olds['hdf5_includedirs'],
                olds['hdf5_libdirs'],
                olds.get('hdf5_define_macros', []),
            )

        # Fallback: query pkgconfig for default hdf5 names
        import pkgconfig
        pc_name = 'hdf5-openmpi' if mpi else 'hdf5'
        pc = {}
        try:
            if pkgconfig.exists(pc_name):
                pc = pkgconfig.parse(pc_name)
        except EnvironmentError:
            if os.name != 'nt':
                print(
                    "Building h5py requires pkg-config unless the HDF5 path "
                    "is explicitly specified", file=sys.stderr
                )
                raise

        return (
            pc.get('include_dirs', []),
            pc.get('library_dirs', []),
            pc.get('define_macros', []),
        )
Esempio n. 2
0
def check_build_dependencies():
    """Check that required libraries are present before trying to build."""
    for library in BOOST_LIBRARIES:
        if not find_library(library):
            raise Exception("Could not find {} library".format(library))

    if (not pkgconfig.exists("hdf5")) and (not find_library("hdf5")):
        raise Exception("Could not find hdf5")

    if not pkgconfig.exists("eigen3"):
        raise Exception("Could not find hdf5")
Esempio n. 3
0
    def run(self):

        py_version_short = self.config_vars['py_version_short']
        py_version_nodot = self.config_vars['py_version_nodot']

        cmake_bin = binary_exists('cmake')
        make_bin = binary_exists('make')
        comp_bin = binary_exists('c++') or binary_exists(
            'g++') or binary_exists('clang')

        import pkgconfig
        zlib_dev = pkgconfig.exists('zlib')
        openssl_dev = pkgconfig.exists('openssl')

        pyname = None
        if py_version_nodot[0] == '3':
            python_dev = pkgconfig.exists('python3') or pkgconfig.exists(
                'python' + py_version_nodot)
            pyname = 'python3'
        else:
            python_dev = pkgconfig.exists('python')
            pyname = 'python'

        missing_dep = not (cmake_bin and make_bin and comp_bin and zlib_dev
                           and openssl_dev and python_dev)

        if missing_dep:
            print('Some dependencies are missing:')
            if not cmake_bin: print('\tcmake is missing!')
            if not make_bin: print('\tmake is missing!')
            if not comp_bin:
                print('\tC++ compiler is missing (g++, c++, clang, etc.)!')
            if not zlib_dev: print('\tzlib development package is missing!')
            if not openssl_dev:
                print('\topenssl development package is missing!')
            if not python_dev:
                print('\t{} development package is missing!'.format(pyname))
            raise Exception('Dependencies missing!')

        useropt = ''
        command = ['./install.sh']
        if self.user:
            prefix = self.install_usersite + '/xrdcl'
            useropt = '--user'
        else:
            prefix = sys.prefix
        command.append(prefix)
        command.append(py_version_short)
        command.append(useropt)
        rc = subprocess.call(command)
        if rc:
            raise Exception('Install step failed!')
Esempio n. 4
0
def get_cblas_pc_module_name() -> str:
    """
    Return the name of the BLAS libraries to be used.
    """
    import pkgconfig
    cblas_pc_modules = CBLAS_PC_MODULES.split(':')
    return next((blas_lib for blas_lib in cblas_pc_modules if pkgconfig.exists(blas_lib)))
Esempio n. 5
0
def pagexml_Extension(magick):
    import pkgconfig
    libs = ['opencv', 'libxml-2.0', 'libxslt', 'gdal']
    if magick:
        libs += ['Magick++']
    compile_args = ['-std=c++11']
    link_args = []
    for lib in libs:
        if not pkgconfig.exists(lib):
            raise FileNotFoundError('pkgconfig did not find ' + lib)
        compile_args += pkgconfig.cflags(lib).split()
        link_args += pkgconfig.libs(lib).split()
    #compile_args += pkgconfig.cflags('opencv').split()
    #cvre = re.compile('^-L|^-lopencv_core|^-lopencv_imgproc|^-lopencv_imgcodecs|^-lopencv_highgui')
    #link_args += [x for x in pkgconfig.libs('opencv').split() if cvre.match(x)]
    cvinc = pkgconfig.cflags('opencv').split()[0].rsplit('/opencv', 1)[0]
    defimage = '__PAGEXML_IMG_MAGICK__' if magick else '__PAGEXML_IMG_CV__'
    pageimage = 'Magick::Image' if magick else 'cv::Mat'
    define_macros = [('__PAGEXML_OGR__', ''), (defimage, '')
                     ] + ([('__PAGEXML_MAGICK__', '')] if magick else [])
    swig_opts = [
        '-D__PAGEXML_OGR__', '-D' + defimage, '-DPageImage=' + pageimage
    ] + (['-D__PAGEXML_MAGICK__'] if magick else [])
    print('pagexml_Extension configured with ' + defimage)
    return Extension(
        '_pagexml',
        define_macros=define_macros + [('SWIG_PYTHON_SILENT_MEMLEAK', '')],
        extra_compile_args=compile_args,
        extra_link_args=link_args,
        swig_opts=swig_opts +
        [cvinc, '-I./opencv-swig/lib', '-modern', '-keyword', '-w511', '-c++'],
        sources=['pagexml/PageXML.i', 'pagexml/PageXML.cc'])
Esempio n. 6
0
def textfeat_Extension(magick=False):
    import pkgconfig
    libs = ['opencv', 'libxml-2.0', 'Magick++']
    compile_args = ['-std=c++11']
    link_args = []
    for lib in libs:
        if not pkgconfig.exists(lib):
            raise FileNotFoundError('pkgconfig did not find ' + lib)
        compile_args += pkgconfig.cflags(lib).split()
        link_args += pkgconfig.libs(lib).split()
    #compile_args += pkgconfig.cflags('opencv').split()
    #cvre = re.compile('^-L|^-lopencv_core|^-lopencv_imgproc|^-lopencv_imgcodecs|^-lopencv_flann')
    #link_args += [x for x in pkgconfig.libs('opencv').split() if cvre.match(x)]
    cvinc = pkgconfig.cflags('opencv').split()[0].rsplit('/opencv', 1)[0]
    defimage = '__PAGEXML_IMG_MAGICK__' if magick else '__PAGEXML_IMG_CV__'
    pageimage = 'Magick::Image' if magick else 'cv::Mat'
    define_macros = [(defimage, ''), ('__PAGEXML_MAGICK__', '')]
    swig_opts = [
        '-D' + defimage, '-DPageImage=' + pageimage, '-D__PAGEXML_MAGICK__'
    ]
    print('textfeat_Extension configured with ' + defimage)
    return Extension(
        '_textfeat',
        define_macros=define_macros + [('SWIG_PYTHON_SILENT_MEMLEAK', '')],
        extra_compile_args=compile_args,
        extra_link_args=link_args,
        swig_opts=swig_opts + [cvinc, '-modern', '-keyword', '-c++'],
        sources=[
            'textfeat/TextFeatExtractor.i', 'textfeat/TextFeatExtractor.cc',
            'textfeat/intimg.cc', 'textfeat/mem.cc'
        ])
Esempio n. 7
0
def get_blas_config() -> PackageInfo:
    """
    Find CBLAS-compatible BLAS

    :return:
        blas related package information
    """

    blaspkgcfg = {
        'include_dirs': [],
        'library_dirs': [],
        'libraries': [],
        'define_macros': [],
        'extra_compile_args': [],
        'extra_link_args': []
    }

    # Check environment variables
    if 'BLAS_CFLAGS' in os.environ:
        blaspkgcfg['extra_compile_args'].extend(
            shlex.split(os.environ['BLAS_CFLAGS']))

    if 'BLAS_LIBS' in os.environ:
        blaspkgcfg['extra_link_args'].extend(
            shlex.split(os.environ['BLAS_LIBS']))

    if 'BLAS_CFLAGS' in os.environ or 'BLAS_LIBS' in os.environ:
        # If options have been provided by the user, we don't try to detect
        # anything by ourselves
        return blaspkgcfg

    # Try environment modules
    # MKL
    if 'MKLROOT' in os.environ:
        if 'MKL_INC' in os.environ:
            blaspkgcfg['extra_compile_args'].extend(
                shlex.split(os.environ['MKL_INC']))
        if 'MKL_LIB' in os.environ:
            blaspkgcfg['extra_link_args'].extend(
                shlex.split(os.environ['MKL_LIB']))
        blaspkgcfg['define_macros'].append(('AMICI_BLAS_MKL', None), )
        return blaspkgcfg

    # Try pkgconfig
    if pkgconfig:
        for blas_name in ['cblas', 'openblas']:
            if pkgconfig.exists(blas_name):
                blaspkgcfg = pkgconfig.parse(blas_name)
                blaspkgcfg['extra_compile_args'] = [
                    pkgconfig.cflags(blas_name)
                ]
                blaspkgcfg['extra_link_args'] = [pkgconfig.libs(blas_name)]

                return blaspkgcfg

    # If none of the previous worked, fall back to libcblas in default paths
    blaspkgcfg['libraries'] = ['cblas']

    return blaspkgcfg
Esempio n. 8
0
def autodetect_version(hdf5_dir=None):
    """
    Detect the current version of HDF5, and return X.Y.Z version string.

    Intended for Unix-ish platforms (Linux, OS X, BSD).
    Does not support Windows. Raises an exception if anything goes wrong.

    hdf5_dir: optional HDF5 install directory to look in (containing "lib")
    """

    import os
    import sys
    import os.path as op
    import re
    import ctypes
    from ctypes import byref

    import pkgconfig

    if sys.platform.startswith('darwin'):
        regexp = re.compile(r'^libhdf5.dylib')
    else:
        regexp = re.compile(r'^libhdf5.so')

    libdirs = ['/usr/local/lib', '/opt/local/lib']
    try:
        if pkgconfig.exists("hdf5"):
            libdirs.extend(pkgconfig.parse("hdf5")['library_dirs'])
    except EnvironmentError:
        pass
    if hdf5_dir is not None:
        libdirs.insert(0, op.join(hdf5_dir, 'lib'))

    path = None
    for d in libdirs:
        try:
            candidates = [x for x in os.listdir(d) if regexp.match(x)]
        except Exception:
            continue  # Skip invalid entries

        if len(candidates) != 0:
            candidates.sort(
                key=lambda x: len(x))  # Prefer libfoo.so to libfoo.so.X.Y.Z
            path = op.abspath(op.join(d, candidates[0]))
            break

    if path is None:
        path = "libhdf5.so"

    lib = ctypes.cdll.LoadLibrary(path)

    major = ctypes.c_uint()
    minor = ctypes.c_uint()
    release = ctypes.c_uint()

    lib.H5get_libversion(byref(major), byref(minor), byref(release))

    return "{0}.{1}.{2}".format(int(major.value), int(minor.value),
                                int(release.value))
Esempio n. 9
0
def check_pkgconfig(progs):
    for prog in progs:
        sys.stdout.write(f'checking for "{prog}" (via pkg-config)... ')
        if pkgconfig.exists(prog):
            sys.stdout.write('found\n')
        else:
            sys.stdout.write('not found\n')
            die(f'please install "{prog}" dependency first')
Esempio n. 10
0
def find_pybind11(hint=None):
    r'''
Try to find the pybind11 library. If successful the include directory is returned.
  '''

    # search with "get_include"
    # -------------------------

    if hint is None:

        import pybind11

        incl = pybind11.get_include(False)
        if len(incl) > 0:
            return incl

        incl = pybind11.get_include(True)
        if len(incl) > 0:
            return incl

    # search with pkgconfig
    # ---------------------

    if hint is None:

        import pkgconfig

        if pkgconfig.exists('pybind11'):
            return pkgconfig.parse('pybind11')['include_dirs'][0]

    # manual search
    # -------------

    search_dirs = [] if hint is None else hint
    search_dirs += [
        "/usr/local/include",
        "/usr/local/homebrew/include",
        "/opt/local/var/macports/software",
        "/opt/local/include",
        "/usr/include",
        "/usr/include/local",
        "/usr/include",
    ]

    for d in search_dirs:
        path = os.path.join(d, "pybind11", "xtensor_config.hpp")
        if os.path.exists(path):
            src = open(path, "r").read()
            v1 = re.findall("#define PYBIND11_VERSION_MAJOR (.+)", src)
            v2 = re.findall("#define PYBIND11_VERSION_MINOR (.+)", src)
            v3 = re.findall("#define PYBIND11_VERSION_PATCH (.+)", src)
            if not len(v1) or not len(v2) or not len(v3):
                continue
            v = "{0}.{1}.{2}".format(v1[0], v2[0], v3[0])
            print("Found pybind11 version {0} in: {1}".format(v, d))
            return d

    return None
Esempio n. 11
0
def autodetect_version(hdf5_dir=None):
    """
    Detect the current version of HDF5, and return X.Y.Z version string.

    Intended for Unix-ish platforms (Linux, OS X, BSD).
    Does not support Windows. Raises an exception if anything goes wrong.

    hdf5_dir: optional HDF5 install directory to look in (containing "lib")
    """

    import os
    import sys
    import os.path as op
    import re
    import ctypes
    from ctypes import byref

    import pkgconfig
    
    if sys.platform.startswith('darwin'):
        regexp = re.compile(r'^libhdf5.dylib')
    else:
        regexp = re.compile(r'^libhdf5.so')
        
    libdirs = ['/usr/local/lib', '/opt/local/lib']
    try:
        if pkgconfig.exists("hdf5"):
            libdirs.extend(pkgconfig.parse("hdf5")['library_dirs'])
    except EnvironmentError:
        pass
    if hdf5_dir is not None:
        libdirs.insert(0, op.join(hdf5_dir, 'lib'))

    path = None
    for d in libdirs:
        try:
            candidates = [x for x in os.listdir(d) if regexp.match(x)]
        except Exception:
            continue   # Skip invalid entries

        if len(candidates) != 0:
            candidates.sort(key=lambda x: len(x))   # Prefer libfoo.so to libfoo.so.X.Y.Z
            path = op.abspath(op.join(d, candidates[0]))
            break

    if path is None:
        path = "libhdf5.so"

    lib = ctypes.cdll.LoadLibrary(path)

    major = ctypes.c_uint()
    minor = ctypes.c_uint()
    release = ctypes.c_uint()

    lib.H5get_libversion(byref(major), byref(minor), byref(release))

    return "{0}.{1}.{2}".format(int(major.value), int(minor.value), int(release.value))
Esempio n. 12
0
def check_lib(name, version):
    lib_installed = pkgconfig.exists(name)
    if not lib_installed:
        raise RuntimeError("lib{0} not installed".format(name))

    lib_min = pkgconfig.installed(name, version)
    if not lib_min:
        raise RuntimeError("requires lib{0} {1} ".format(name, version))
    return pkgconfig.parse(name)
Esempio n. 13
0
def compile_cpp_code(cpp_code):
    """Compile a user C(++) string to a Python object with pybind11.  Note
       this is still experimental.

    """

    if not pkgconfig.exists('dolfin'):
        raise RuntimeError(
            "Could not find DOLFIN pkg-config file. Please make sure appropriate paths are set."
        )

    # Get pkg-config data for DOLFIN
    d = pkgconfig.parse('dolfin')

    # Set compiler/build options
    # FIXME: need to locate Python libs and pybind11
    from distutils import sysconfig
    params = dijitso.params.default_params()
    pyversion = "python" + sysconfig.get_config_var("LDVERSION")
    params['cache']['lib_prefix'] = ""
    params['cache']['lib_basename'] = ""
    params['cache']['lib_loader'] = "import"
    params['build']['include_dirs'] = d["include_dirs"] + get_pybind_include(
    ) + [sysconfig.get_config_var("INCLUDEDIR") + "/" + pyversion]
    params['build']['libs'] = d["libraries"] + [pyversion]
    params['build']['lib_dirs'] = d["library_dirs"] + [
        sysconfig.get_config_var("LIBDIR")
    ]
    params['build']['cxxflags'] += ('-fno-lto', )

    # enable all define macros from DOLFIN
    dmacros = ()
    for dm in d['define_macros']:
        if len(dm[1]) == 0:
            dmacros += ('-D' + dm[0], )
        else:
            dmacros += ('-D' + dm[0] + '=' + dm[1], )

    params['build']['cxxflags'] += dmacros

    # This seems to be needed by OSX but not in Linux
    # FIXME: probably needed for other libraries too
    if cpp.common.has_petsc():
        import os
        params['build']['libs'] += ['petsc']
        params['build']['lib_dirs'] += [os.environ["PETSC_DIR"] + "/lib"]

    module_hash = hashlib.md5(cpp_code.encode('utf-8')).hexdigest()
    module_name = "dolfin_cpp_module_" + module_hash

    module, signature = dijitso.jit(cpp_code,
                                    module_name,
                                    params,
                                    generate=jit_generate)

    return module
Esempio n. 14
0
    def _make_extensions(config):
        """ Produce a list of Extension instances which can be passed to
        cythonize().

        This is the point at which custom directories, MPI options, etc.
        enter the build process.
        """
        import numpy
        import pkgconfig

        settings = COMPILER_SETTINGS.copy()

        # Ensure that if a custom HDF5 location is specified, prevent
        # pkg-config and fallback locations from appearing in the settings
        if config.hdf5 is not None:
            settings['include_dirs'].insert(0, op.join(config.hdf5, 'include'))
            settings['library_dirs'].insert(0, op.join(config.hdf5, 'lib'))
        else:
            try:
                if pkgconfig.exists('hdf5'):
                    pkgcfg = pkgconfig.parse("hdf5")
                    settings['include_dirs'].extend(pkgcfg['include_dirs'])
                    settings['library_dirs'].extend(pkgcfg['library_dirs'])
                    settings['define_macros'].extend(pkgcfg['define_macros'])
            except EnvironmentError:
                if os.name != 'nt':
                    print(
                        "h5py requires pkg-config unless the HDF5 path is explicitly specified",
                        file=sys.stderr)
                    raise
            settings['include_dirs'].extend(FALLBACK_PATHS['include_dirs'])
            settings['library_dirs'].extend(FALLBACK_PATHS['library_dirs'])

        try:
            numpy_includes = numpy.get_include()
        except AttributeError:
            # if numpy is not installed get the headers from the .egg directory
            import numpy.core
            numpy_includes = os.path.join(os.path.dirname(numpy.core.__file__),
                                          'include')

        settings['include_dirs'] += [numpy_includes]
        if config.mpi:
            import mpi4py
            settings['include_dirs'] += [mpi4py.get_include()]

        # TODO: should this only be done on UNIX?
        if os.name != 'nt':
            settings['runtime_library_dirs'] = settings['library_dirs']

        def make_extension(module):
            sources = [localpath('h5py', module + '.pyx')] + EXTRA_SRC.get(
                module, [])
            return Extension('h5py.' + module, sources, **settings)

        return [make_extension(m) for m in MODULES]
Esempio n. 15
0
def get_motr_dir():
    try:
        # Motr devel rpm takes precedence over M0_SRC_DIR
        if pkgconfig.exists('motr'):
            return pkgconfig.variables('motr')['includedir']
    except EnvironmentError:
        # fall back to M0_SRC_DIR handling if `pkg-config` is not available in
        # the system
        pass

    d = os.environ.get('M0_SRC_DIR')
    if d:
        return d
    return P.normpath(P.dirname(P.abspath(__file__)) + '/../../cortx-motr')
Esempio n. 16
0
    def _make_extensions(config):
        """ Produce a list of Extension instances which can be passed to
        cythonize().
        
        This is the point at which custom directories, MPI options, etc.
        enter the build process.
        """
        import numpy
        import pkgconfig

        settings = COMPILER_SETTINGS.copy()

        try:
            if pkgconfig.exists('hdf5'):
                pkgcfg = pkgconfig.parse("hdf5")
                settings['include_dirs'].extend(pkgcfg['include_dirs'])
                settings['library_dirs'].extend(pkgcfg['library_dirs'])
                settings['define_macros'].extend(pkgcfg['define_macros'])
        except EnvironmentError:
            pass

        try:
            numpy_includes = numpy.get_include()
        except AttributeError:
            # if numpy is not installed get the headers from the .egg directory
            import numpy.core
            numpy_includes = os.path.join(os.path.dirname(numpy.core.__file__),
                                          'include')

        settings['include_dirs'] += [numpy_includes]
        if config.mpi:
            import mpi4py
            settings['include_dirs'] += [mpi4py.get_include()]

        # Ensure a custom location appears first, so we don't get a copy of
        # HDF5 from some default location in COMPILER_SETTINGS
        if config.hdf5 is not None:
            settings['include_dirs'].insert(0, op.join(config.hdf5, 'include'))
            settings['library_dirs'].insert(0, op.join(config.hdf5, 'lib'))

        # TODO: should this only be done on UNIX?
        if os.name != 'nt':
            settings['runtime_library_dirs'] = settings['library_dirs']

        def make_extension(module):
            sources = [localpath('h5py', module + '.pyx')] + EXTRA_SRC.get(
                module, [])
            return Extension('h5py.' + module, sources, **settings)

        return [make_extension(m) for m in MODULES]
Esempio n. 17
0
    def _make_extensions(config):
        """ Produce a list of Extension instances which can be passed to
        cythonize().

        This is the point at which custom directories, MPI options, etc.
        enter the build process.
        """
        import numpy
        import pkgconfig

        settings = COMPILER_SETTINGS.copy()

        try:
            if pkgconfig.exists("hdf5"):
                pkgcfg = pkgconfig.parse("hdf5")
                settings["include_dirs"].extend(pkgcfg["include_dirs"])
                settings["library_dirs"].extend(pkgcfg["library_dirs"])
                settings["define_macros"].extend(pkgcfg["define_macros"])
        except EnvironmentError:
            pass

        try:
            numpy_includes = numpy.get_include()
        except AttributeError:
            # if numpy is not installed get the headers from the .egg directory
            import numpy.core

            numpy_includes = os.path.join(os.path.dirname(numpy.core.__file__), "include")

        settings["include_dirs"] += [numpy_includes]
        if config.mpi:
            import mpi4py

            settings["include_dirs"] += [mpi4py.get_include()]

        # Ensure a custom location appears first, so we don't get a copy of
        # HDF5 from some default location in COMPILER_SETTINGS
        if config.hdf5 is not None:
            settings["include_dirs"].insert(0, op.join(config.hdf5, "include"))
            settings["library_dirs"].insert(0, op.join(config.hdf5, "lib"))

        # TODO: should this only be done on UNIX?
        if os.name != "nt":
            settings["runtime_library_dirs"] = settings["library_dirs"]

        def make_extension(module):
            sources = [localpath("h5py", module + ".pyx")] + EXTRA_SRC.get(module, [])
            return Extension("h5py." + module, sources, **settings)

        return [make_extension(m) for m in MODULES]
Esempio n. 18
0
    def _make_extensions(config):
        """ Produce a list of Extension instances which can be passed to
        cythonize().

        This is the point at which custom directories, MPI options, etc.
        enter the build process.
        """
        import numpy
        import pkgconfig

        settings = COMPILER_SETTINGS.copy()

        # Ensure that if a custom HDF5 location is specified, prevent
        # pkg-config and fallback locations from appearing in the settings
        if config.hdf5 is not None:
            settings['include_dirs'].insert(0, op.join(config.hdf5, 'include'))
            settings['library_dirs'].insert(0, op.join(config.hdf5, 'lib'))
        else:
            try:
                if pkgconfig.exists('hdf5'):
                    pkgcfg = pkgconfig.parse("hdf5")
                    settings['include_dirs'].extend(pkgcfg['include_dirs'])
                    settings['library_dirs'].extend(pkgcfg['library_dirs'])
                    settings['define_macros'].extend(pkgcfg['define_macros'])
            except EnvironmentError:
                pass
            settings['include_dirs'].extend(FALLBACK_PATHS['include_dirs'])
            settings['library_dirs'].extend(FALLBACK_PATHS['library_dirs'])

        try:
            numpy_includes = numpy.get_include()
        except AttributeError:
            # if numpy is not installed get the headers from the .egg directory
            import numpy.core
            numpy_includes = os.path.join(os.path.dirname(numpy.core.__file__), 'include')

        settings['include_dirs'] += [numpy_includes]
        if config.mpi:
            import mpi4py
            settings['include_dirs'] += [mpi4py.get_include()]

        # TODO: should this only be done on UNIX?
        if os.name != 'nt':
            settings['runtime_library_dirs'] = settings['library_dirs']

        def make_extension(module):
            sources = [localpath('h5py', module+'.pyx')] + EXTRA_SRC.get(module, [])
            return Extension('h5py.'+module, sources, **settings)

        return [make_extension(m) for m in MODULES]
Esempio n. 19
0
def validate_pkg_config_packages(wizard, packages):
    if packages is None:
        return True

    if type(packages) != list:
        print "Incorrect type, expected list or None"
        return False

    for package in packages:
        if not pkgconfig.exists(package):
            print "package %s does not exist" % package
            return False

    return True
Esempio n. 20
0
def get_motr_libs_dir():
    try:
        # Motr devel rpm takes precedence over M0_SRC_DIR
        if pkgconfig.exists('motr'):
            return pkgconfig.variables('motr')['libdir']
    except EnvironmentError:
        # fall back to M0_SRC_DIR handling if `pkg-config` is not available in
        # the system
        pass

    libs_dir = get_motr_dir() + '/motr/.libs'
    libmotr = libs_dir + '/libmotr.so'
    assert P.isfile(libmotr), f'{libmotr}: No such file'
    return libs_dir
Esempio n. 21
0
def get_motr_cflags():
    try:
        # Motr devel rpm takes precedence over M0_SRC_DIR
        if pkgconfig.exists('motr'):
            return pkgconfig.cflags('motr').split()
    except EnvironmentError:
        # fall back to M0_SRC_DIR handling if `pkg-config` is not available in
        # the system
        pass

    return [
        '-g', '-Werror', '-Wall', '-Wextra', '-Wno-attributes',
        '-Wno-unused-parameter'
    ]
Esempio n. 22
0
def get_libraries():
    """Get libraries for building EM2.

    This is mostly just finding hdf5. Boost doesn't seem to work with
    pkg-config.
    """

    all_libraries = list(BOOST_LIBRARIES)
    if pkgconfig.exists("hdf5"):
        all_libraries.extend(pkgconfig.parse("hdf5")['libraries'])
    else:
        all_libraries.append("hdf5")
    all_libraries.append("hdf5_cpp")

    return all_libraries
Esempio n. 23
0
def get_include_dirs():
    import pkgconfig
    import numpy

    if not pkgconfig.exists('eigen3'):
        raise Exception(
            'Missing `eigen3` library. Please install it using the package manager of your operating system'
        )

    np_include_dir = numpy.get_include()

    # We have to throw away the `-I` part of the `pkgconfig` output
    # because it is not part of the include directory.
    eigen3_include_dir = pkgconfig.cflags('eigen3')[2:]

    return [np_include_dir, eigen3_include_dir]
Esempio n. 24
0
def find_eigen(hint=None):
    r'''
Try to find the Eigen library. If successful the include directory is returned.
  '''

    # search with pkgconfig
    # ---------------------

    if hint is None:

        import pkgconfig

        if pkgconfig.exists('eigen3'):
            return pkgconfig.parse('eigen3')['include_dirs'][0]

    # manual search
    # -------------

    search_dirs = [] if hint is None else hint
    search_dirs += [
        "/usr/local/include/eigen3",
        "/usr/local/homebrew/include/eigen3",
        "/opt/local/var/macports/software/eigen3",
        "/opt/local/include/eigen3",
        "/usr/include/eigen3",
        "/usr/include/local",
        "/usr/include",
    ]

    for d in search_dirs:
        path = os.path.join(d, "Eigen", "Dense")
        if os.path.exists(path):
            vf = os.path.join(d, "Eigen", "src", "Core", "util", "Macros.h")
            if not os.path.exists(vf):
                continue
            src = open(vf, "r").read()
            v1 = re.findall("#define EIGEN_WORLD_VERSION (.+)", src)
            v2 = re.findall("#define EIGEN_MAJOR_VERSION (.+)", src)
            v3 = re.findall("#define EIGEN_MINOR_VERSION (.+)", src)
            if not len(v1) or not len(v2) or not len(v3):
                continue
            v = "{0}.{1}.{2}".format(v1[0], v2[0], v3[0])
            print("Found Eigen version {0} in: {1}".format(v, d))
            return d

    return None
Esempio n. 25
0
def find_xsimd(hint=None):
    r'''
Try to find the xsimd library. If successful the include directory is returned.
  '''

    # search with pkgconfig
    # ---------------------

    if hint is None:

        import pkgconfig

        if pkgconfig.exists('xsimd'):
            return pkgconfig.parse('xsimd')['include_dirs'][0]

    # manual search
    # -------------

    search_dirs = [] if hint is None else hint
    search_dirs += [
        "/usr/local/include",
        "/usr/local/homebrew/include",
        "/opt/local/var/macports/software",
        "/opt/local/include",
        "/usr/include",
        "/usr/include/local",
        "/usr/include",
    ]

    for d in search_dirs:
        path = os.path.join(d, "xsimd", "config", "xsimd_config.hpp")
        print(path)
        if os.path.exists(path):
            src = open(path, "r").read()
            v1 = re.findall("#define XSIMD_VERSION_MAJOR (.+)", src)
            v2 = re.findall("#define XSIMD_VERSION_MINOR (.+)", src)
            v3 = re.findall("#define XSIMD_VERSION_PATCH (.+)", src)
            if not len(v1) or not len(v2) or not len(v3):
                continue
            v = "{0}.{1}.{2}".format(v1[0], v2[0], v3[0])
            print("Found xsimd version {0} in: {1}".format(v, d))
            return d

    return None
Esempio n. 26
0
    def _make_extensions(config):
        """ Produce a list of Extension instances which can be passed to
        cythonize().
        
        This is the point at which custom directories, MPI options, etc.
        enter the build process.
        """
        import numpy
        import pkgconfig

        settings = COMPILER_SETTINGS.copy()

        try:
            if pkgconfig.exists('hdf5'):
                pkgcfg = pkgconfig.parse("hdf5")
                settings['include_dirs'].extend(pkgcfg['include_dirs'])
                settings['library_dirs'].extend(pkgcfg['library_dirs'])
                settings['define_macros'].extend(pkgcfg['define_macros'])
        except EnvironmentError:
            pass

        settings['include_dirs'] += [numpy.get_include()]
        if config.mpi:
            import mpi4py
            settings['include_dirs'] += [mpi4py.get_include()]
            
        # Ensure a custom location appears first, so we don't get a copy of
        # HDF5 from some default location in COMPILER_SETTINGS
        if config.hdf5 is not None:
            settings['include_dirs'].insert(0, op.join(config.hdf5, 'include'))
            settings['library_dirs'].insert(0, op.join(config.hdf5, 'lib'))

        # TODO: should this only be done on UNIX?
        if os.name != 'nt':
            settings['runtime_library_dirs'] = settings['library_dirs']
        
        def make_extension(module):
            sources = [localpath('h5py', module+'.pyx')] + EXTRA_SRC.get(module, [])
            return Extension('h5py.'+module, sources, **settings)

        return [make_extension(m) for m in MODULES]
def getBlasConfig():
    """
    Find CBLAS-compatible BLAS

    Arguments:

    Returns:

    Raises:

    """

    blaspkgcfg = {'include_dirs': [],
                  'library_dirs': [],
                  'libraries': [],
                  'define_macros': [],
                  'extra_compile_args': [],
                  'extra_link_args': []
                  }

    if platform.system() in ['Linux', 'Darwin']:
        blaspkgcfg['libraries'] = ['cblas']

    if pkgconfig:
        if pkgconfig.exists('cblas'):
            blaspkgcfg = pkgconfig.parse('cblas')
            blaspkgcfg['extra_compile_args'] = [pkgconfig.cflags('cblas')]
            blaspkgcfg['extra_link_args'] = [pkgconfig.libs('cblas')]

    if 'BLAS_CFLAGS' in os.environ:
        blaspkgcfg['extra_compile_args'].extend(
            shlex.split(os.environ['BLAS_CFLAGS'])
        )

    if 'BLAS_LIBS' in os.environ:
        blaspkgcfg['extra_link_args'].extend(
            shlex.split(os.environ['BLAS_LIBS'])
        )

    return blaspkgcfg
Esempio n. 28
0
def check_gromacs_dirs():
    ''' Check for GROMACS directories and flags
    '''
    import pkgconfig

    # If gromacs not in pkgconfig, return from here
    if not pkgconfig.exists('libgromacs'):
        return

    out = dict()

    cppflags_t = pkgconfig.re.split('\s+', pkgconfig.cflags('libgromacs'))
    out['cppflags'] = []
    out['ldflags'] = []
    out['include'] = []
    out['lib_dirs'] = []
    out['libs'] = []

    # Extract include directory and CXXFLAGS
    for flags in cppflags_t:
        if '-I' in flags:
            out['include'].append(flags[2:])
        else:
            out['cppflags'].append(flags)

    # Extract lib directory and LDFLAGS
    ldflags_t = pkgconfig.re.split('\s+', pkgconfig.libs('libgromacs'))
    for flags in ldflags_t:
        if '-L' in flags:
            out['lib_dirs'].append(flags[2:])
        elif '-l' in flags:
            out['libs'].append(flags[2:])
        else:
            out['ldflags'].append(flags)

    if '-fopenmp' not in out['ldflags']:
        out['ldflags'].append('-fopenmp')

    return out
Esempio n. 29
0
"""Helper functions for AMICI core and module package preparation"""

import os
import platform
import shlex
import sys
import subprocess
import shutil

try:
    import pkgconfig  # optional
    # pkgconfig python module might be installed without pkg-config binary being available
    pkgconfig.exists('somePackageName')
except (ModuleNotFoundError, EnvironmentError):
    pkgconfig = None


def getBlasConfig():
    """
    Find CBLAS-compatible BLAS

    Arguments:

    Returns:

    Raises:

    """

    blaspkgcfg = {
        'include_dirs': [],
Esempio n. 30
0
LIBS_SUNDIALS = ['sundials_nvecserial']
LIBS_IDA = ['sundials_ida']
LIBS_CVODE = ['sundials_cvode']

# paths for FORTRAN
LIB_DIRS_FORTRAN = []
LIBS_FORTRAN = []

# use pkgconfig to find sundials
PKGCONFIG_CVODE = 'sundials-cvode-serial'

try:
    import pkgconfig
    try:
        if pkgconfig.exists(PKGCONFIG_CVODE):
            pkgconf = pkgconfig.parse(PKGCONFIG_CVODE)
            for d in pkgconf['library_dirs']:
                LIB_DIRS_SUNDIALS.append(str(d))
            for d in pkgconf['include_dirs']:
                INCL_DIRS_SUNDIALS.append(str(d))
    except EnvironmentError:
        pass
except ImportError:
    print("pkgconfig module not found, using preset paths")

if "SUNDIALS_INST" in os.environ:
    LIB_DIRS_SUNDIALS.append(os.path.join(os.environ["SUNDIALS_INST"], "lib"))
    INCL_DIRS_SUNDIALS.append(
        os.path.join(os.environ["SUNDIALS_INST"], "include"))
    print("SUNDIALS installation path set to `{}` via $SUNDIALS_INST.".format(
Esempio n. 31
0
    def _find_hdf5_compiler_settings(mpi=False):
        """Get compiler settings from environment or pkgconfig.

        Returns (include_dirs, lib_dirs, define_macros)
        """
        hdf5 = os.environ.get('HDF5_DIR')
        hdf5_includedir = os.environ.get('HDF5_INCLUDEDIR')
        hdf5_libdir = os.environ.get('HDF5_LIBDIR')
        hdf5_pkgconfig_name = os.environ.get('HDF5_PKGCONFIG_NAME')

        if sum([
                bool(hdf5_includedir or hdf5_libdir),
                bool(hdf5),
                bool(hdf5_pkgconfig_name)
        ]) > 1:
            raise ValueError(
                "Specify only one of: HDF5 lib/include dirs, HDF5 prefix dir, "
                "or HDF5 pkgconfig name")

        if hdf5_includedir or hdf5_libdir:
            inc_dirs = [hdf5_includedir] if hdf5_includedir else []
            lib_dirs = [hdf5_libdir] if hdf5_libdir else []
            return (inc_dirs, lib_dirs, [])

        # Specified a prefix dir (e.g. '/usr/local')
        if hdf5:
            inc_dirs = [op.join(hdf5, 'include')]
            lib_dirs = [op.join(hdf5, 'lib')]
            if sys.platform.startswith('win'):
                lib_dirs.append(op.join(hdf5, 'bin'))
            return (inc_dirs, lib_dirs, [])

        # Specified a name to be looked up in pkgconfig
        if hdf5_pkgconfig_name:
            import pkgconfig
            if not pkgconfig.exists(hdf5_pkgconfig_name):
                raise ValueError(
                    f"No pkgconfig information for {hdf5_pkgconfig_name}")
            pc = pkgconfig.parse(hdf5_pkgconfig_name)
            return (pc['include_dirs'], pc['library_dirs'],
                    pc['define_macros'])

        # Fallback: query pkgconfig for default hdf5 names
        import pkgconfig
        pc_name = 'hdf5-openmpi' if mpi else 'hdf5'
        pc = {}
        try:
            if pkgconfig.exists(pc_name):
                pc = pkgconfig.parse(pc_name)
        except EnvironmentError:
            if os.name != 'nt':
                print(
                    "Building h5py requires pkg-config unless the HDF5 path "
                    "is explicitly specified",
                    file=sys.stderr)
                raise

        return (
            pc.get('include_dirs', []),
            pc.get('library_dirs', []),
            pc.get('define_macros', []),
        )
Esempio n. 32
0
LIBS_SUNDIALS = ['sundials_nvecserial']
LIBS_IDA      = ['sundials_ida']
LIBS_CVODE    = ['sundials_cvode']

# paths for FORTRAN
LIB_DIRS_FORTRAN = []
LIBS_FORTRAN     = []

# use pkgconfig to find sundials
PKGCONFIG_CVODE = 'sundials-cvode-serial'

try:
    import pkgconfig
    try:
        if pkgconfig.exists(PKGCONFIG_CVODE):
            pkgconf = pkgconfig.parse(PKGCONFIG_CVODE)
            for d in pkgconf['library_dirs']:
                LIB_DIRS_SUNDIALS.append(str(d))
            for d in pkgconf['include_dirs']:
                INCL_DIRS_SUNDIALS.append(str(d))
    except EnvironmentError:
        pass
except ImportError:
    print("pkgconfig module not found, using preset paths")

if "SUNDIALS_INST" in os.environ:
    LIB_DIRS_SUNDIALS.append(os.path.join(os.environ["SUNDIALS_INST"], "lib"))
    INCL_DIRS_SUNDIALS.append(os.path.join(os.environ["SUNDIALS_INST"], "include"))
    print("SUNDIALS installation path set to `{}` via $SUNDIALS_INST.".format(
        os.environ["SUNDIALS_INST"]))
Esempio n. 33
0
# Copyright (c) 2016, Imperial College London
# Copyright (c) 2016, Ghislain Antony Vaillant
# All rights reserved.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the BSD license. See the accompanying LICENSE file
# or read the terms at https://opensource.org/licenses/BSD-3-Clause.


from cffi import FFI
import pkgconfig


if not pkgconfig.exists("fftw3"):
    raise RuntimeError("NFFT library not found via pkgconfig.")
# Transform pkgconfig output to a dictionary of lists, which is the only format
# accepted by distutils.
pc_fftw3 = {key: list(val) for (key, val) in pkgconfig.parse("fftw3").items()}


ffi = FFI()

ffi.cdef(
    """
    #define FFTW_FORWARD ...
    #define FFTW_BACKWARD ...
    #define FFTW_MEASURE ...
    #define FFTW_DESTROY_INPUT ...
    #define FFTW_UNALIGNED ...
    #define FFTW_CONSERVE_MEMORY ...
    #define FFTW_EXHAUSTIVE ...
Esempio n. 34
0
"""

from distutils.core import setup, Extension
import warnings

pkg_dict = dict(
    libraries=['hdf5'],
    library_dirs=[],
    include_dirs=[],
)
try:
    import pkgconfig
except ImportError:
    warnings.warn('python-pkgconfig not installed, using default search path to find HDF5')
else:
    if pkgconfig.exists('hdf5'):
        pkg_dict = pkgconfig.parse('hdf5')
    else:
        warnings.warn('pkgconfig cannot find HDF5, using default path')

setup(name="digital_rf_hdf5",
        version="1.1.3",
        description="Python tools to read and write digital rf data in Hdf5 format",
        author="Bill Rideout",
        author_email="*****@*****.**",
        url="http://www.haystack.mit.edu/~brideout/",
        package_dir = {'': 'source'},
        py_modules=['digital_rf_hdf5', 'digital_metadata'],
        ext_modules=[Extension("_py_rf_write_hdf5",
                              ["source/_py_rf_write_hdf5.c", "source/rf_write_hdf5.c"],
                              libraries=list(pkg_dict['libraries']),
Esempio n. 35
0
#sets up all the environment variables required by openvdb
import pkgconfig
print pkgconfig.exists('glib-2.0')
print pkgconfig.cflags('boost')
import os
import subprocess as sub

def callcmd(cmd):
	p = sub.Popen(cmd,stdout=sub.PIPE,stderr=sub.PIPE, shell=True)
	output, errors = p.communicate()
	#print errors
	return output

def locatePathToFile(filename, guesses=[]):
	#check hypothesises first
	for guess in guesses:
		dirname=os.path.dirname(guess)
		if os.path.isdir(dirname):
			print "found "+filename+" in "+dirname
			return dirname
	#use the OS locate feature
	hypothesis=callcmd("locate "+filename)
	hlist=hypothesis.split("\n")
	dirname=os.path.dirname(hlist[0])
	if (not os.path.isdir(dirname)):
		raise Exception(filename+" not found!")
	print "found "+filename+" in "+dirname
	return dirname

def locateIncludeDir(dirname, file_inside, guesses=[]):
	"""
Esempio n. 36
0
# flake8: noqa

import pkgconfig
from cffi import FFI

# we must have the vips package to be able to do anything
if not pkgconfig.exists('vips'):
    raise Exception('unable to find pkg-config package "vips"')
if pkgconfig.installed('vips', '< 8.2'):
    raise Exception(
        'pkg-config "vips" is too old -- need libvips 8.2 or later')

ffibuilder = FFI()

ffibuilder.set_source("_libvips", r""" 
        #include <vips/vips.h>
    """, **pkgconfig.parse('vips'))

features = {
    # in API mode
    'api': True,
    # at_least_libvips(8, 4):
    '8.4+': pkgconfig.installed('vips', '>= 8.4'),
    # at_least_libvips(8, 5):
    '8.5+': pkgconfig.installed('vips', '>= 8.5'),
    # at_least_libvips(8, 6):
    '8.6+': pkgconfig.installed('vips', '>= 8.6'),
}

from pyvips import decls
Esempio n. 37
0
def test_exists():
    assert pkgconfig.exists(PACKAGE_NAME)
    assert pkgconfig.exists('fake-openssl')
Esempio n. 38
0
def test_exists():
    nt.assert_true(pkgconfig.exists(PACKAGE_NAME))
Esempio n. 39
0
from setuptools import setup, Extension

try:
  from Cython.Build import cythonize
  have_cython = True
except ImportError:
  have_cython = False

try:
  import pkgconfig
  have_pkgconfig = True
except ImportError:
  have_pkgconfig = False

if have_pkgconfig and pkgconfig.exists('libdiscid'):
  flags = pkgconfig.parse('libdiscid')
  define_macros = flags['define_macros']
  include_dirs = flags['include_dirs']
  library_dirs = flags['library_dirs']
  libraries = list(flags['libraries'])
else:
  define_macros = ''
  include_dirs = ''
  library_dirs = ''
  libraries = 'discid'

if have_cython:
  # if Cython is available, rebuild _discid.c
  ext = cythonize([
    Extension('libdiscid._discid',
Esempio n. 40
0
# Use pkg-config to find location of libbson and libmongoc.
try:
    import pkgconfig
except ImportError:
    # Set to default locations for libmongoc and libbson.
    warnings.warn(
        ("WARNING: the python package pkgconfig is not installed. "
         "If you have pkg-config installed on your system, please "
         "install the python's pkgconfig, e.g. \"pip install "
         "pkgconfig\". Will use libmongoc=%s and libbson=%s instead." %
         (mongoc_src, bson_src)))

else:
    try:
        # Use pkgconfig to find location of libmongoc or libbson.
        if pkgconfig.exists("libmongoc-1.0"):
            pkgcfg = pkgconfig.parse("libmongoc-1.0")
            settings['include_dirs'] = list(pkgcfg['include_dirs'])
            settings['library_dirs'] = list(pkgcfg['library_dirs'])
            settings['libraries'] = list(pkgcfg['libraries'])
            settings['define_macros'] = list(pkgcfg['define_macros'])
        else:
            warnings.warn(("WARNING: unable to find libmongoc-1.0 with "
                           "pkgconfig. Please check that PKG_CONFIG_PATH is "
                           "set to a path that can find the .pc files for "
                           "libbson and libmongoc. Will use libmongoc=%s and "
                           "libbson=%s instead." % (mongoc_src, bson_src)))
    except EnvironmentError:
        warnings.warn(("WARNING: the system tool pkg-config is not installed. "
                       "Will use libmongoc=%s and libbson=%s instead." %
                       (mongoc_src, bson_src)))
Esempio n. 41
0
    def run(self):

        py_version_short = self.config_vars['py_version_short']
        py_version_nodot = self.config_vars['py_version_nodot']

        cmake_bin, cmake_path = cmake_exists()
        make_bin = binary_exists('make')
        comp_bin = binary_exists('c++') or binary_exists(
            'g++') or binary_exists('clang')

        import pkgconfig
        zlib_dev = pkgconfig.exists('zlib')
        openssl_dev = pkgconfig.exists('openssl')
        uuid_dev = pkgconfig.exists('uuid')

        if is_rhel7():
            if has_cxx14():
                devtoolset7 = True  # we only care about devtoolset7 if the compiler does not support C++14
                need_devtoolset = "false"
            else:
                devtoolset7 = has_devtoolset()
                need_devtoolset = "true"
        else:
            devtoolset7 = True  # we only care about devtoolset7 on rhel7
            need_devtoolset = "false"

        pyname = None
        if py_version_nodot[0] == '3':
            python_dev = pkgconfig.exists('python3') or pkgconfig.exists(
                'python' + py_version_nodot)
            pyname = 'python3'
        else:
            python_dev = pkgconfig.exists('python')
            pyname = 'python'

        missing_dep = not (cmake_bin and make_bin and comp_bin and zlib_dev
                           and openssl_dev and python_dev and uuid_dev
                           and devtoolset7)

        if missing_dep:
            print('Some dependencies are missing:')
            if not cmake_bin: print('\tcmake (version 3) is missing!')
            if not make_bin: print('\tmake is missing!')
            if not comp_bin:
                print('\tC++ compiler is missing (g++, c++, clang, etc.)!')
            if not zlib_dev: print('\tzlib development package is missing!')
            if not openssl_dev:
                print('\topenssl development package is missing!')
            if not python_dev:
                print('\t{} development package is missing!'.format(pyname))
            if not uuid_dev: print('\tuuid development package is missing')
            if not devtoolset7:
                print('\tdevtoolset-7-gcc-c++ package is missing')
            raise Exception('Dependencies missing!')

        useropt = ''
        command = ['./install.sh']
        if self.user:
            prefix = self.install_usersite
            useropt = '--user'
        else:
            prefix = self.install_platlib
        command.append(prefix)
        command.append(py_version_short)
        command.append(useropt)
        command.append(cmake_path)
        command.append(need_devtoolset)
        command.append(sys.executable)
        rc = subprocess.call(command)
        if rc:
            raise Exception('Install step failed!')
Esempio n. 42
0
def test_exists():
    assert pkgconfig.exists(PACKAGE_NAME)
    assert pkgconfig.exists('fake-openssl')
Esempio n. 43
0
import sys
import pkgconfig

from distutils.core import setup
from distutils.extension import Extension

from Cython.Build import cythonize
from pip.req import parse_requirements

if pkgconfig.exists("watchy") is False:
    print >>sys.stderr, "Make sure pkg-config watchy --cflags --libs works."
    sys.exit(1)
watchy = pkgconfig.parse("watchy")
extensions = [
    Extension(
        "pywatchy",
        ["bindings/python/pywatchy.pyx"],
        include_dirs=list(watchy["include_dirs"]),
        libraries=list(watchy["libraries"]),
        library_dirs=list(watchy["library_dirs"]),
        runtime_library_dirs=list(watchy["library_dirs"]),
    )
]
install_reqs = parse_requirements("./requirements.txt")
reqs = [str(ir.req) for ir in install_reqs]
setup(
    name="Watchy",
    version="0.2",
    url="https://github.com/redbrain/watchy",
    author="Philip Herron",
    author_email="*****@*****.**",
Esempio n. 44
0
import sys
from distutils.core import setup, Extension
from Cython.Distutils import build_ext
import numpy
import pkgconfig

if pkgconfig.exists('opencv4'):
    opencv_pkginfo = pkgconfig.parse('opencv4')
    extra_compile_args = ['-std=c++11', '-DUSE_OPENCV4']
elif pkgconfig.exists('opencv'):
    opencv_pkginfo = pkgconfig.parse('opencv')
    extra_compile_args = ['-std=c++11']
else:
    print("opencv package config is not found.", file=sys.stderr)
    exit(1)

libdr = ['/usr/local/lib'] + opencv_pkginfo["library_dirs"]
incdr = [numpy.get_include(), '/usr/local/include/'
         ] + opencv_pkginfo["include_dirs"]

ext = [
    Extension('cvt', ['python/cvt.pyx'],
              language='c++',
              extra_compile_args=extra_compile_args,
              include_dirs=incdr,
              library_dirs=libdr,
              libraries=['opencv_core']),
    Extension('KCF', ['python/KCF.pyx', 'src/kcftracker.cpp', 'src/fhog.cpp'],
              language='c++',
              extra_compile_args=extra_compile_args,
              include_dirs=incdr,
Esempio n. 45
0
# Use pkg-config to find location of libbson and libmongoc.
try:
    import pkgconfig
except ImportError:
    # Set to default locations for libmongoc and libbson.
    warnings.warn(("WARNING: the python package pkgconfig is not installed. "
                   "If you have pkg-config installed on your system, please "
                   "install the python's pkgconfig, e.g. \"pip install "
                   "pkgconfig\". Will use libmongoc=%s and libbson=%s instead."
                   % (mongoc_src, bson_src)))

else:
    try:
        # Use pkgconfig to find location of libmongoc or libbson.
        if pkgconfig.exists("libmongoc-1.0"):
            pkgcfg = pkgconfig.parse("libmongoc-1.0")
            settings['include_dirs'] = list(pkgcfg['include_dirs'])
            settings['library_dirs'] = list(pkgcfg['library_dirs'])
            settings['libraries'] = list(pkgcfg['libraries'])
            settings['define_macros'] = list(pkgcfg['define_macros'])
        else:
            warnings.warn(("WARNING: unable to find libmongoc-1.0 with "
                           "pkgconfig. Please check that PKG_CONFIG_PATH is "
                           "set to a path that can find the .pc files for "
                           "libbson and libmongoc. Will use libmongoc=%s and "
                           "libbson=%s instead." % (mongoc_src, bson_src)))
    except EnvironmentError:
        warnings.warn(("WARNING: the system tool pkg-config is not installed. "
                      "Will use libmongoc=%s and libbson=%s instead."
                       % (mongoc_src, bson_src)))
Esempio n. 46
0
# -*- coding: utf-8 -*-

import pkgconfig
import numpy
import hashlib
import dijitso
import dolfin.cpp as cpp

from dolfin.cpp import MPI
from functools import wraps
import ffc
from dolfin.cpp.parameter import parameters

# Get DOLFIN pkg-config data
if pkgconfig.exists("dolfin"):
    dolfin_pc = pkgconfig.parse("dolfin")
else:
    raise RuntimeError("Could not find DOLFIN pkg-config file. Please make sure appropriate paths are set.")


# Copied over from site-packages
def mpi_jit_decorator(local_jit, *args, **kwargs):
    """A decorator for jit compilation

    Use this function as a decorator to any jit compiler function.  In
    a parallel run, this function will first call the jit compilation
    function on the first process. When this is done, and the module
    is in the cache, it will call the jit compiler on the remaining
    processes, which will then use the cached module.

    *Example*
if "PKG_CONFIG_PATH" not in os.environ:
    os.environ["PKG_CONFIG_PATH"] = ""

pkg_config_path = os.environ["PKG_CONFIG_PATH"].split(":")

if "CONDA_PREFIX" in os.environ:
    conda_env_pkg_config = os.path.join(os.environ["CONDA_PREFIX"], "lib",
                                        "pkgconfig")
    if (os.path.exists(conda_env_pkg_config)
            and not conda_env_pkg_config in pkg_config_path):
        os.environ["PKG_CONFIG_PATH"] += ":" + conda_env_pkg_config

if "/usr/local/lib/pkgconfig" not in pkg_config_path:
    os.environ["PKG_CONFIG_PATH"] += ":/usr/local/lib/pkgconfig"

if not pkgconfig.exists("libsemigroups"):
    raise ImportError("cannot locate libsemigroups library")
elif not compare_version_numbers(libsemigroups_version(),
                                 minimum_libsemigroups_version()):
    raise ImportError(
        "libsemigroups version at least {0} is required, found {1}".format(
            minimum_libsemigroups_version(), libsemigroups_version()))


class get_pybind_include(object):
    """Helper class to determine the pybind11 include path

    The purpose of this class is to postpone importing pybind11
    until it is actually installed, so that the ``get_include()``
    method can be invoked."""
    def __init__(self, user=False):
Esempio n. 48
0
# Copyright (c) 2016, Imperial College London
# Copyright (c) 2016, Ghislain Antony Vaillant
# All rights reserved.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the BSD license. See the accompanying LICENSE file
# or read the terms at https://opensource.org/licenses/BSD-3-Clause.


from cffi import FFI
import pkgconfig


if not pkgconfig.exists("nfft3"):
    raise RuntimeError("NFFT library not found via pkgconfig.")
# Transform pkgconfig output to a dictionary of lists, which is the only format
# accepted by distutils.
pc_nfft3 = {key: list(val) for (key, val) in pkgconfig.parse("nfft3").items()}


ffi = FFI()

ffi.cdef("""
    typedef ... fftw_complex;
    
    #define FFTW_MEASURE ...
    #define FFTW_DESTROY_INPUT ...
    
    typedef struct {
        fftw_complex *f_hat;
        fftw_complex *f;
Esempio n. 49
0
import sys
import pkgconfig

from distutils.core import setup
from distutils.extension import Extension

from Cython.Build import cythonize
from pip.req import parse_requirements

if pkgconfig.exists ('watchy') is False:
    print >> sys.stderr, "Make sure pkg-config watchy --cflags --libs works."
    sys.exit (1)
watchy = pkgconfig.parse ('watchy')
extensions = [
    Extension ('pywatchy', ['bindings/python/pywatchy.pyx'],
               include_dirs = list (watchy ['include_dirs']),
               libraries = list (watchy ['libraries']),
               library_dirs = list (watchy ['library_dirs']),
               runtime_library_dirs = list (watchy ['library_dirs']))
]
install_reqs = parse_requirements ('./requirements.txt')
reqs = [str(ir.req) for ir in install_reqs]
setup (
    name = "Watchy",
    version = "0.2",
    url = 'https://github.com/redbrain/watchy',
    author = 'Philip Herron',
    author_email = '*****@*****.**',
    license = "MIT",
    description = 'A stats agregation daemon over UDP',
    platforms = ('Any',),
Esempio n. 50
0
import bagwacl

import pyopencl as cl

from distutils.core import setup,Extension
import pkgconfig

assert pkgconfig.exists('lal')
assert pkgconfig.exists('lalsimulation')
assert pkgconfig.exists('lalinference')

# Compile flags
c=pkgconfig.parse('lal lalsimulation lalinference')

bagwacl.generate_bagwacl_data()

setup(
    name='bagwacl',
    version='0.1',
    packages=['bagwacl'],
    scripts=['bin/lalinference_bagwacl'],
    ext_modules=[
        Extension(
            'libbagwacl',
            ['./src/bagwacl.c'],
            libraries=list(c['libraries']),
            library_dirs=list(c['library_dirs']),
            include_dirs=list(c['include_dirs']),
            runtime_library_dirs=list(c['library_dirs']),
            extra_compile_args=['-std=c99'],
        )