def test01_kdcraw(self): """Doc strings for KDcrawIface (used to crash).""" import cppyy, pydoc # TODO: run a find for these paths qtpath = "/usr/include/qt5" kdcraw_h = "/usr/include/KF5/KDCRAW/kdcraw/kdcraw.h" if not os.path.isdir(qtpath) or not os.path.exists(kdcraw_h): py.test.skip("no KDE/Qt found, skipping test01_kdcraw") # need to resolve qt_version_tag for the incremental compiler; since # it's not otherwise used, just make something up cppyy.cppdef("int qt_version_tag = 42;") cppyy.add_include_path(qtpath) cppyy.include(kdcraw_h) # bring in some symbols to resolve the class cppyy.load_library("libQt5Core.so") cppyy.load_library("libKF5KDcraw.so") from cppyy.gbl import KDcrawIface self.__class__.helpout = [] pydoc.doc(KDcrawIface.KDcraw) helptext = ''.join(self.__class__.helpout) assert 'KDcraw' in helptext assert 'CPPInstance' in helptext
def TPyDispatcher(self): include('ROOT/TPyDispatcher.h') major, minor = sys.version_info[0:2] load_library('libROOTPythonizations{}_{}'.format(major, minor)) tpd = gbl_namespace.TPyDispatcher type(self).TPyDispatcher = tpd return tpd
def init(): """ Load the pHash C++ library. By default it looks for the lib file in the parent folder to this file, as this is the "site-packages" folder. If that doesn't work, it will try just loading any pHash it can. This is useful for development instances etc. :return: """ import cppyy site_packages = os.path.split(os.path.dirname(__file__))[0] cppyy.include(os.path.join(site_packages, 'pHash.h')) cppyy.load_library(os.path.join(site_packages, 'libpHash.so'))
def _load_pythonization_lib(): info = get_paths() for file in os.listdir(info['platlib']): if re.match(r'pysyscsc.*\.so', file): cppyy.load_library(os.path.join(info['platlib'], file)) full_path = os.path.join( info['data'], 'include/site/python%d.%d/PySysC/PyScModule.h' % sys.version_info[:2]) if os.path.isfile(full_path): cppyy.include(full_path) return
def __load_src(): for header in __HDR: if not cppyy.include(header): raise ImportError(f"unable to load {header}") cppyy.load_library(f"{PATH}/build/senet_xtc-0.0.1-x86_64-Linux.so") __internal = {} for smb in __SMBS: __internal[smb] = eval(f"cppyy.gbl.xtc.{smb}") globals().update(__internal) #cppyy.gbl.xtc
def juce_bootstrap(): root_path = __os.path.abspath(__os.path.join(__os.path.dirname(__file__))) __cppyy.add_include_path(__get_juce_include_path(root_path)) __cppyy.load_library(__get_juce_library_path(root_path)) __cppyy.cppdef(__get_juce_defs(root_path)) if __sys.platform in ["darwin"]: __cppyy.cppdef( "namespace juce { extern void initialiseNSApplication(); }")
def _load_systemc_cci(): if 'CCI_HOME' in os.environ: add_sys_include_path(os.path.join(os.environ['CCI_HOME'], 'include')) for l in ['lib', 'lib64', 'lib-linux', 'lib-linux64']: for f in ['libcciapi.so']: full_file = os.path.join(os.environ['CCI_HOME'], l, f) if os.path.isfile(full_file): cppyy.load_library(full_file) cppyy.include("cci_configuration") cci_loaded = True return True return False
def lib(self): """ It checks if the library is already loaded, or it loads it. """ if all((hasattr(cppyy.gbl, check) for check in self.check)): return cppyy.gbl for include in self.include: cppyy.add_include_path(include) for library in self.library: if isinstance(library, Lib): library.lib for header in self.header: for path in self.path: if not path.startswith(os.sep): path = self._cwd + "/" + path if os.path.isfile(path + "/include/" + header): cppyy.add_include_path(path + "/include") break if self.c_include: cppyy.c_include(header) else: cppyy.include(header) for library in self.library: if not isinstance(library, str): continue tmp = library if not tmp.startswith(os.sep): tmp = self._cwd + "/" + tmp if os.path.isfile(tmp): cppyy.load_library(tmp) else: found = False for path in self.path: if not path.startswith(os.sep): path = self._cwd + "/" + path if os.path.isfile(path + "/lib/" + library): cppyy.load_library(path + "/lib/" + library) found = True break assert found, "Library %s not found in paths %s" % (library, self.path) assert all((hasattr(cppyy.gbl, check) for check in self.check)), "Given checks not found." return cppyy.gbl
def get_lib(): "Retuns a cppyy.gbl object with DDalphaAMG loaded in it" global _lib if not _lib: # Making sure that mpi has been loaded from lyncs import mpi mpi.get_lib() # Loading DDalphaAMG import cppyy import lyncs_config as config cppyy.add_include_path(config.ddalphaamg_path + "/include") cppyy.c_include("DDalphaAMG.h") cppyy.load_library(config.ddalphaamg_path + "/lib/libDDalphaAMG.so") _lib = cppyy.gbl return _lib
def _load_pythonization_lib(): info = get_paths() for file in os.listdir(info['platlib']): if re.match(r'pysyscsc.*\.so', file): cppyy.load_library(os.path.join(info['platlib'], file)) full_path = os.path.join( info['data'], 'include/site/python%d.%d/PySysC/PyScModule.h' % sys.version_info[:2]) if os.path.isfile(full_path): cppyy.include(full_path) return # could not be found in sintall, maybe development environment pkgDir = os.path.join(os.path.dirname(os.path.realpath(__file__)), '..') for file in os.listdir(pkgDir): if re.match(r'pysyscsc.*\.so', file): cppyy.load_library(os.path.join(pkgDir, file)) full_path = os.path.join(pkgDir, 'PyScModule.h') if os.path.isfile(full_path): cppyy.include(full_path) return
def init(): """ Load the pHash C++ library. By default it looks for the lib file in the parent folder to this file, as this is the "site-packages" folder. If that doesn't work, it will try just loading any pHash it can. This is useful for development instances etc. :return: """ import cppyy import platform isMac = platform.system() == 'Darwin' isLinux = platform.system() == 'Linux' site_packages = os.path.split(os.path.dirname(__file__))[0] cppyy.include(os.path.join(site_packages, 'pHash.h')) if isLinux: cppyy.load_library(os.path.join(site_packages, 'libpHash.so')) else if isMac: cppyy.load_library(os.path.join(site_packages, 'libpHash.dylib'))
def get_results_from_solver(pbn, dealer): """Funkcja wyznaczająca liczbę lew, jaką weźmie każdy z graczy wraz z partnerem dla danego miana oraz zwracająca wartość punktową dla pary N-S (dla E-W jest taka sama wartość, tylko z przeciwnym znakiem) za optymalny kontrakt, gdy wszystkie pary licytują idealnie. Wykorzystano Double Dummy Solver napisany w C++. Wyznaczone liczby lew są w następującej kolejności: najpierw North i ilość lew dla poszczególnych mian kolejno: S, H, D, C, NT, a następnie East, South i West z identyczną kolejnością mian.""" try: cppyy.include("./gym_bridge_auction/envs/solver/dds_wrapper/ddswrapper.h") cppyy.load_library("ddswrapper") solver_result = cppyy.gbl.calcTricksAndScore(cppyy.gbl.std.string(pbn), dealer) solver_result = list(solver_result) number_of_tricks = solver_result[0:-1] optimum_score = solver_result[-1] return number_of_tricks, optimum_score except: print('Solver error') quit()
def load_argos(): cppyy.include( str( pathlib.Path(config.ARGOS_PREFIX) / "include/argos3/core/simulator/simulator.h")) cppyy.include( str( pathlib.Path(config.ARGOS_PREFIX) / "include/argos3/core/simulator/space/space.h")) cppyy.include( str( pathlib.Path(config.ARGOS_PREFIX) / "include/argos3/core/simulator/loop_functions.h")) cppyy.include( str( pathlib.Path(config.ARGOS_PREFIX) / "include/argos3/core/utility/plugins/dynamic_loading.h")) cppyy.load_library( str( pathlib.Path(config.ARGOS_PREFIX) / "lib/argos3/libargos3core_simulator.so")) cppyy.include( str( pathlib.Path(config.ARGOS_PREFIX) / "include/argos3/plugins/robots/e-puck/simulator/epuck_entity.h")) cppyy.include( str( pathlib.Path(config.ARGOS_PREFIX) / "include/argos3/demiurge/loop-functions/CoreLoopFunctions.h")) from cppyy.gbl import argos mak = argos.CSimulator.GetInstance() arr = argos.CDynamicLoading.LoadAllLibraries() return mak, arr
def read_config_from_conan(conanfile, build_type='Release'): global lang_level sys.stdout = NullLogger() #read conan configuration with tempfile.TemporaryDirectory() as tmpdirname: conan_api, client_cache, user_io = conan.Conan.factory() install_info = conan_api.install( path=conanfile, generators=['json'], settings=['build_type=%s' % build_type], install_folder=tmpdirname) for e in install_info['installed']: name = e['recipe']['name'] for p in e['packages']: if name == 'SystemC' and p['cpp_info']['rootpath']: os.environ['SYSTEMC_HOME'] = p['cpp_info']['rootpath'] elif name == 'SystemC-CCI' and p['cpp_info']['rootpath']: os.environ['CCI_HOME'] = p['cpp_info']['rootpath'] elif name == 'SystemCVerification' and p['cpp_info'][ 'rootpath']: os.environ['SCV_HOME'] = p['cpp_info']['rootpath'] with open(os.path.join(tmpdirname, "conanbuildinfo.json")) as f: data = json.load(f) # set include pathes and load libraries for d in data['dependencies']: for p in d['include_paths']: add_sys_include_path(p) if d['name'] == 'SystemC': for l in d['lib_paths']: if os.path.exists(l + '/' + 'libsystemc.so'): cppyy.load_library(l + '/' + 'libsystemc.so') lang_level = int(data['options']['SystemC']['stdcxx']) msg = sys.stdout.buffer sys.stdout = sys.stdout.terminal return msg
def load_systemc(): if 'SYSTEMC_HOME' in os.environ: add_sys_include_path( os.path.join(os.environ['SYSTEMC_HOME'], 'include')) for l in ['lib', 'lib64', 'lib-linux', 'lib-linux64']: for f in ['libsystemc.so']: full_file = os.path.join(os.environ['SYSTEMC_HOME'], l, f) if os.path.isfile(full_file): cppyy.load_library(full_file) cppyy.cppdef(""" #define SC_CPLUSPLUS %s #include "systemc" #include "tlm" namespace sc_core { extern void pln(); } """ % lang_symbols[lang_level]) systemc_loaded = True _load_systemc_cci() break if systemc_loaded: break if not interactive: cppyy.gbl.sc_core.pln() cppyy.gbl.sc_core.sc_in_action = True _load_pythonization_lib() return True return False
import ROOT import cppyy import os if "CMSSW_BASE" not in os.environ: # This is a standalone compile file_path = os.path.abspath(__file__) base_path = os.path.dirname(os.path.dirname(os.path.dirname(file_path))) cppyy.load_library(base_path + "/lib/libPlotUtils.so") cppyy.load_reflection_info(base_path + "/python/libpyPlotUtils.so") ## Renaming all the stuff to use a flatter interface # Unfortunately, the contents of cppyy userspace is dynamically generated, so # there is not easy way for programmatically running this renaming scheme. Simple1DCanvas = cppyy.gbl.usr.plt.Simple1DCanvas Ratio1DCanvas = cppyy.gbl.usr.plt.Ratio1DCanvas Flat2DCanvas = cppyy.gbl.usr.plt.Flat2DCanvas CommonXCanvas = cppyy.gbl.usr.plt.CommonXCanvas Pad1D = cppyy.gbl.usr.plt.Pad1D Pad2DFlat = cppyy.gbl.usr.plt.Pad2DFlat PlotUnder = cppyy.gbl.usr.plt.PlotUnder ExtryText = cppyy.gbl.usr.plt.EntryText TextColor = cppyy.gbl.usr.plt.TextColor TextSize = cppyy.gbl.usr.plt.TextSize TextAngle = cppyy.gbl.usr.plt.TextAngle TextAlign = cppyy.gbl.usr.plt.TextAlign LineColor = cppyy.gbl.usr.plt.LineColor LineStyle = cppyy.gbl.usr.plt.LineStyle LineWidth = cppyy.gbl.usr.plt.LineWidth FillColor = cppyy.gbl.usr.plt.FillColor
#!/usr/bin/python3 import cppyy cppyy.include('../../lib/proc.hpp') cppyy.load_library('../../libanti_noise.so') def do_anti(filename): # Return a filename, which is anti-noised. return cppyy.gbl.f_anti_noise(filename) if __name__ == '__main__': print("No, this is a interface wrapper.")
from tqdm import tqdm import cppyy import glob for header in glob.glob("../../IsoSpec++/*.h"): if not "mman.h" in header: cppyy.include(header) cppyy.load_library("../../IsoSpec++/libIsoSpec++.so") t = 0.0 for x in tqdm(xrange(1000000)): i = cppyy.gbl.IsoSpec.Iso("C100H100N100O100") t += i.getTheoreticalAverageMass() print t
import cppyy import pathlib __all__ = ['GCO'] _this_dir = pathlib.Path(__file__).parent cppyy.add_include_path(str(_this_dir / 'include')) cppyy.add_library_path(str(_this_dir)) # Include and load library cppyy.include("GCoptimization.h") cppyy.load_library("gco") from cppyy.gbl import GCO
This module contains some minimal wrapping code to interact with the libsemigroups C++ library: https://github.com/james-d-mitchell/libsemigroups via cppyy: https://bitbucket.org/wlav/cppyy/ ''' import cppyy from cppyy.gbl import std # This assumes that the header files are in the standard include path, # and that the libsemigroups dynamic library is in LD_LIBRARY_PATH cppyy.load_library('libsemigroups') cppyy.include('libsemigroups/libsemigroups.h') cppyy.include("python3.6m/Python.h") cppyy.include(__file__[:-31] + "python_element.h") # Variants: # cppyy.include('/usr/local/include/libsemigroups/libsemigroups.h') # cppyy.include('~/anaconda/include/libsemigroups/libsemigroups.h') # cppyy.include('/Users/jdm/libsemigroups/src/libsemigroups.h') CPPInstance = cppyy.gbl.libsemigroups.Element.__base__ from cppyy.gbl.libsemigroups import PBR, Bipartition, PythonElement def Transformation(images):
import sys cppyy.gbl path = os.environ["PATH"].split(":") for d in path: if d.find("include") != -1: try: cppyy.add_include_path(d) except: pass stderr, sys.stderr = sys.stderr, open(os.devnull, "w") stdout, sys.stdout = sys.stdout, open(os.devnull, "w") try: cppyy.load_library("libsemigroups.1") except Exception: cppyy.load_library("libsemigroups") sys.stderr = stderr sys.stdout = stdout cppyy.cppdef("#define FMT_HEADER_ONLY") cppyy.cppdef("#define HPCOMBI_CONSTEXPR_FUN_ARGS") cppyy.include("libsemigroups/action.hpp") cppyy.include("libsemigroups/bmat8.hpp") cppyy.include("libsemigroups/cong-pair.hpp") cppyy.include("libsemigroups/element.hpp") cppyy.include("libsemigroups/element-helper.hpp") cppyy.include("libsemigroups/froidure-pin.hpp") cppyy.include("libsemigroups/fpsemi.hpp")
import cppyy import numpy as np import ctypes import time from bqplot import Graph, LinearScale, ColorScale, Figure, Tooltip from ipywidgets import HBox,Label,IntSlider,Button,Layout,interact,dlink,interactive import ipywidgets as widgets from string import ascii_uppercase import os dir=os.path.dirname(__file__) cppyy.include(dir+"/features.h") cppyy.load_library(dir+"/libGraph") ### # Modifie la coloeur du print ### class color: PURPLE = '\033[95m' CYAN = '\033[96m' DARKCYAN = '\033[36m' BLUE = '\033[94m' GREEN = '\033[92m' PINK = '\033[80m' YELLOW = '\033[93m' RED = '\033[91m' BOLD = '\033[1m' UNDERLINE = '\033[4m' END = '\033[0m'
import sys import numpy as np import cppyy cppyy.include("src/logicle.hpp") cppyy.load_library("liblogicle.so") from cppyy.gbl import Logicle, FastLogicle from .utils import name_to_index def estimate_logicle(data, meta, col): """Estimate values for logicle function.""" t = meta[f"$P{name_to_index(meta, col)}R"] m = 4.5 negative_data = data.loc[data[col] < 0, col] if not negative_data.empty: r = sys.float_info.epsilon / data[col].quantile(0.05) w = (m - np.log10(t / abs(r))) / 2 else: w = 0 return FastLogicle(float(t), float(w), float(m), 0.0) def transform_logicle(fcsdata, channel, lgc): """Transform data column using provided logicle object.""" meta, data = fcsdata scaler = np.vectorize(lgc.scale) data.loc[:, channel] = scaler(data.loc[:, channel].values)
import sys import logging import os.path log = logging.getLogger(__name__) PYPCODENATIVE_PATH = os.path.join(os.path.dirname(__file__), 'pypcode-native') SLEIGH_PATH = os.path.join(PYPCODENATIVE_PATH, 'sleigh-2.1.0') SLEIGH_SRC_PATH = os.path.join(SLEIGH_PATH, 'src') SLEIGH_SPECFILES_PATH = os.path.join(SLEIGH_PATH, 'specfiles') log.debug('Loading Library') cppyy.include(os.path.join(PYPCODENATIVE_PATH, 'pypcode-native.h')) cppyy.include(os.path.join(SLEIGH_SRC_PATH, 'translate.hh')) cppyy.include(os.path.join(SLEIGH_SRC_PATH, 'error.hh')) cppyy.load_library(os.path.join(PYPCODENATIVE_PATH, 'pypcode-native.so')) class AssemblyEmitCacher(cppyy.gbl.AssemblyEmit): def dump(self, addr, mnem, body): self.addr = addr self.mnem = mnem self.body = body # Import names into this namespace from cppyy.gbl import Address from cppyy.gbl import AddrSpace from cppyy.gbl import ContextInternal from cppyy.gbl import DocumentStorage from cppyy.gbl import Element
topologic_inc = "/usr/local/include/TopologicCore" elif (os.path.isdir("/usr/include/TopologicCore")): topologic_inc = "/usr/include/TopologicCore" if (os.path.isdir("/usr/local/lib")): cppyy.add_library_path("/usr/local/lib") elif system == 'Windows': win_prefix = "C:/Topologic" topologic_inc = "{}/include".format(win_prefix) cppyy.add_include_path("{}/include/opencascade".format(win_prefix)) cppyy.add_include_path(topologic_inc) for header in headers: cppyy.include(topologic_inc + "/" + header) cppyy.load_library("TopologicCore") from cppyy.gbl import TopologicCore from cppyy.gbl import TopologicUtilities Aperture = TopologicCore.Aperture ApertureFactory = TopologicCore.ApertureFactory Attribute = TopologicCore.Attribute AttributeManager = TopologicCore.AttributeManager #Bitwise = TopologicCore.Bitwise Cell = TopologicCore.Cell CellComplex = TopologicCore.CellComplex CellComplexFactory = TopologicCore.CellComplexFactory CellFactory = TopologicCore.CellFactory CellUtility = TopologicUtilities.CellUtility Cluster = TopologicCore.Cluster ClusterFactory = TopologicCore.ClusterFactory
# So far, we have only determined the upper triangle of H. H += H.T - np.diag(np.diag(H)) return -0.5 * (delta - 2.0) * H # Speeding up Laplace Approximation using C++ code import os os.environ["LD_LIBRARY_PATH"] = "/usr/local/lib" os.environ["EXTRA_CLING_ARGS"] = "-I/usr/local/include -DNDB" import cppyy import igraph # We load igraph in the following fashion since it is a C instead of a C++ library. cppyy.c_include("igraph/igraph.h") cppyy.load_library("libigraph") cppyy.cppdef(""" #include <cmath> #include <iostream> #include <vector> // This code was tested using Blaze version 3.8.0 // (https://bitbucket.org/blaze-lib/blaze/src/master/) with the fix from this // pull request: https://bitbucket.org/blaze-lib/blaze/pull-requests/46. //#include </usr/local/include/blaze/math/DynamicMatrix.h> //#include </usr/local/include/blaze/math/DynamicVector.h> //#include </usr/local/include/blaze/math/Column.h> //#include </usr/local/include/blaze/math/Columns.h> //#include </usr/local/include/blaze/math/Row.h> //#include </usr/local/include/blaze/math/Rows.h>
try: from StringIO import StringIO except ImportError: from io import StringIO import cppyy import re cppyy.load_library("/usr/lib/libgsl") # Change this to your local setting. cppyy.include("gsl/gsl_matrix.h") cppyy.include("wrapper_python.h") cppyy.load_library("libDataTypes") from cppyy.gbl import wrapperPython # type matchers numpy -> gsl tm_np2gsl = dict() tm_np2gsl['float64'] = '' tm_np2gsl['float32'] = 'float' tm_np2gsl[cppyy.sizeof('long') == 4 and 'int32' or 'int64'] = 'long' tm_np2gsl[cppyy.sizeof('int') == 4 and 'int32' or 'int64'] = 'int' # etc. for other numpy types converters = dict() for key, value in tm_np2gsl.items(): if key == 'float64': converters[key] = 'gsl_matrix_view_array' else: converters[key] = 'gsl_matrix_%s_view_array' % value # gsl_matrix decorator
binary_file_name = "GGM_" + platform_name + ".so" # cppyy seems to be using the wrong BLAS on the Yale-NUS server. We therefore # explicitly specify the path to Intel MKL's LAPACK and BLAS taken from # `np.show_config()`. subprocess.run( compiler_opts \ + " -shared -fPIC -I/usr/local/include -std=c++17 " \ + "-L$CONDA_PREFIX/lib -L/usr/local -Wl,-rpath,$CONDA_PREFIX/lib " \ + "-lmkl_rt -ligraph -O2 -DNDEBUG -o " + binary_file_name \ + " GGM.cpp", shell=True, check=True ) cppyy.include("GGM.h") cppyy.load_library(binary_file_name) # Reduce Python overhead: rgwish_L_identity_cpp = cppyy.gbl.rgwish_L_identity_cpp update_G_cpp = cppyy.gbl.update_G_cpp update_G_both_cpp = cppyy.gbl.update_G_both_cpp rejection_sampling_cpp = cppyy.gbl.rejection_sampling_cpp sample_e_both_cpp = cppyy.gbl.sample_e_both_cpp c_einsum = np.core._multiarray_umath.c_einsum # As the metabolite data is not public, we use another example data set here. iris = sklearn.datasets.load_iris() data = iris["data"][(iris["target"] == ( iris["target_names"] == "virginica").nonzero()[0][0]).nonzero()[0], :]
EXAMPLES:: >>> from gmpxxyy import mpq >>> float(mpq(1, 3)) 0.3333333333333333 """ proxy.__float__ = lambda self: self.get_d() cppyy.py.add_pythonization(filtered(is_primitive_gmp_type)(enable_float)) # We need the GMP headers (with C++) to be around. We could ship them with this # Python library but then we would have to hope that the libgmpxx.so is # compatible. Most likely it is but it doesn't feel right to me. cppyy.load_library("gmp") cppyy.load_library("gmpxx") cppyy.include("gmpxx.h") cppyy.cppdef(""" namespace gmpxxyy { template <typename T> struct maybe { template <typename S> static auto cast(const S& s) { if constexpr(std::is_convertible_v<S, T>) return static_cast<T>(s); else return s; } }; }
# # Copyright (c) 2019 -2021 MINRES Technolgies GmbH # # SPDX-License-Identifier: Apache-2.0 # import cppyy cppyy.add_include_path('.') cppyy.load_library('../lib/libsystemc.so.2.3.3') cppyy.include('cppyy_systemc.h') cppyy.include('sysc/kernel/sc_module.h') import pdb from cppyy.gbl import sc_core from pprint import pprint as pp #pprint(dir(cppyy.gbl.sc_dt)) cppyy.cppdef(""" class my_module: public sc_core::sc_module { public: sc_core::sc_signal<sc_dt::sc_uint<32>> sig; sc_core::sc_out<sc_dt::sc_uint<32>> port; my_module():sc_core::sc_module("module"), sig("sig"){} }; void bind_port(sc_core::sc_signal<sc_dt::sc_uint<32>>& s, sc_core::sc_out<sc_dt::sc_uint<32>>& p){p(s);} """) v = cppyy.gbl.std.vector[int](10) #n = sc_module() n = cppyy.gbl.my_module() pp(sc_core.sc_time_stamp().to_string()) pp(n.simcontext().time_stamp().to_string())