def halton_seq(self,output_array, start_dim, seed): array_1d_double = npct.ndpointer(dtype=numpy.double, ndim=1, flags='CONTIGUOUS') array_2d_double = npct.ndpointer(dtype=numpy.double, ndim=2, flags='CONTIGUOUS') self.so.halton_seq.argtypes = [c_int, c_int, c_int, c_int, array_2d_double] self.so.halton_seq.restype = c_int return self.so.halton_seq(len(output_array), len(output_array[0]), start_dim, seed, output_array)
def solve(self, b, verbose = None): b_shp = b.shape if b.ndim == 2 and b.shape[1] == 1: b = b.ravel() nrhs = 1 elif b.ndim == 2 and b.shape[1] != 1: nrhs = b.shape[1] b = b.ravel(order='F') else: b = b.ravel() nrhs = 1 if self._is_complex: data_type = np.complex128 if b.dtype != np.complex128: b = b.astype(np.complex128, copy=False) else: data_type = np.float64 if b.dtype != np.float64: b = b.astype(np.float64, copy=False) # Create solution array (x) and pointers to x and b if self._is_complex: x = np.zeros(b.shape, dtype=np.complex128, order='C') else: x = np.zeros(b.shape, dtype=np.float64, order='C') np_x = x.ctypes.data_as(ctypeslib.ndpointer(data_type, ndim=1, flags='C')) np_b = b.ctypes.data_as(ctypeslib.ndpointer(data_type, ndim=1, flags='C')) error = np.zeros(1,dtype=np.int32) np_error = error.ctypes.data_as(ctypeslib.ndpointer(np.int32, ndim=1, flags='C')) #Call solver _solve_start = time.time() pardiso(self._np_pt, byref(c_int(1)), byref(c_int(1)), byref(c_int(self._mtype)), byref(c_int(33)), byref(c_int(self._dim)), self._data, self._indptr, self._indices, self._np_perm, byref(c_int(nrhs)), self._np_iparm, byref(c_int(0)), np_b, np_x, np_error) self._solve_time = time.time() -_solve_start if error[0] != 0: raise Exception(pardiso_error_msgs[str(error[0])]) if verbose: print('Solution Stage') print('--------------') print('Solution time: ',round(self._solve_time,4)) print('Solution memory (Mb): ',round(self._iparm[16]/1024.,4)) print('Number of iterative refinements:',self._iparm[6]) print('Total memory (Mb): ',round(sum(self._iparm[15:17])/1024.,4)) print() # Return solution vector x if nrhs==1: if x.shape != b_shp: x = np.reshape(x, b_shp) return x else: return np.reshape(x, b_shp, order='F')
def loadXDRLibrary(LoadDirectFromMSMBuilder=True): global _xdrlib xdr_library_path = find_library("xdrfile") if xdr_library_path and not LoadDirectFromMSMBuilder: _xdrlib = CDLL(xdr_library_path) elif LoadDirectFromMSMBuilder==True: MSMBuilderPath=imp.find_module("msmbuilder")[1] _xdrlib=CDLL(MSMBuilderPath+"/libxdrfile.so") else: # Lutz: find_library does not look in LD_LIBRARY_PATH on linux machines (see http://bugs.python.org/issue2936), even though cdll.LoadLibrary does # as a workaround, we try to load the shared object file manually if sys.platform.startswith("linux"): try: _xdrlib = CDLL("libxdrfile.so") except: raise RuntimeError("Unable to find xdrfile library. Make sure that it is compiled as a shared library, and that its location is known to the dynamic linker (e.g., set LD_LIBRARY_PATH on Linux).") else: raise RuntimeError("Unable to find xdrfile library. Make sure that it is compiled as a shared library, and that its location is known to the dynamic linker (e.g., set DYLD_LIBRARY_PATH on Mac OS X, LD_LIBRARY_PATH on Linux).") # declare interface for functions in the xdr library to insure some amount of type safety # for use of numpy arrays in ctypes, see http://thread.gmane.org/gmane.comp.python.numeric.general/7418/focus=7418 _xdrlib.read_xtc_natoms.argtypes = [c_char_p, POINTER(c_int)] _xdrlib.read_trr_natoms.argtypes = [c_char_p, POINTER(c_int)] _xdrlib.xdrfile_open.argtypes = [c_char_p, c_char_p] _xdrlib.xdrfile_open.restype = c_void_p _xdrlib.xdrfile_close.argtypes = [c_void_p] _xdrlib.read_xtc.argtypes = [c_void_p, c_int, POINTER(c_int), POINTER(c_float), ndpointer(dtype="single",shape=(3,3),flags="C_CONTIGUOUS"), ndpointer(dtype="single",ndim=2,flags="C_CONTIGUOUS"), POINTER(c_float)] _xdrlib.read_trr.argtypes = [c_void_p, c_int, POINTER(c_int), POINTER(c_float),POINTER(c_float), ndpointer(dtype="single",shape=(3,3),flags="C_CONTIGUOUS"), ndpointer(dtype="single",ndim=2,flags="C_CONTIGUOUS"),ndpointer(dtype="single",ndim=2,flags="C_CONTIGUOUS"),ndpointer(dtype="single",ndim=2,flags="C_CONTIGUOUS")] _xdrlib.write_xtc.argtypes = [c_void_p, c_int, c_int, c_float, ndpointer(dtype="single",shape=(3,3),flags="C_CONTIGUOUS"), ndpointer(dtype="single",ndim=2,flags="C_CONTIGUOUS"), c_float]
def resize(img,scale): """ downsample img to scale """ sdims=img.shape datatype=c_double if img.dtype!=datatype: print "Error the image must be of doubles!" raise RuntimeError if scale>1.0: print "Invalid scaling factor!" raise RuntimeError img = asfortranarray(img,c_double) # make array continguous try: mresize = ctypeslib.load_library("libresize.so",".") except: print "Unable to load resize library" raise RuntimeError #use two times the 1d resize to get a 2d resize fresize = mresize.resize1dtran fresize.restype = None fresize.argtypes = [ ctypeslib.ndpointer(dtype=datatype, ndim=3), c_int,ctypeslib.ndpointer(dtype=datatype, ndim=3), c_int, c_int , c_int ] ddims = [int(round(sdims[0]*scale)),int(round(sdims[1]*scale)),sdims[2]]; mxdst = zeros((ddims), dtype=datatype) tmp = zeros((ddims[0],sdims[1],sdims[2]), dtype=datatype) img1=img t1=time() fresize(img1, sdims[0], tmp, ddims[0], sdims[1], sdims[2]); fresize(tmp, sdims[1], mxdst, ddims[1], ddims[0], sdims[2]); t2=time() return mxdst.reshape(ddims[2],ddims[1],ddims[0]).T
def __init__(self, nx, ny): self.nx = nx self.ny = ny self.nx_p = byref(c_int(nx)) self.ny_p = byref(c_int(ny)) # Load the library using numpy libm = npct.load_library('my_math', './') modname = 'my_math' my_cos = getattr(libm, '__{}_MOD_{}'.format(modname, 'my_cos')) my_cos_2d = getattr(libm, '__{}_MOD_{}'.format(modname, 'my_cos_2d')) # Set the argument and return type c_int_p = POINTER(c_int) arr_1d_f8 = npct.ndpointer(ndim=1, dtype='f8') my_cos.argtypes = (c_int_p, arr_1d_f8, arr_1d_f8) my_cos.restype = None arr_2d_f8 = npct.ndpointer(ndim=2, dtype='f8', flags='F') my_cos_2d.argtypes = (c_int_p, c_int_p, arr_2d_f8, arr_2d_f8) my_cos_2d.restype = None # Set to public self.libm = libm self.my_cos = my_cos self.my_cos_2d = my_cos_2d
def __init__(self, rho, sigma, scorebook): """ :param rho: gap opening penalty :param sigma: gap extension penalty :param scorebook: see `from_submatr` method """ self.rho = rho self.sigma = sigma self.scorebook = scorebook arrflages = str('C') self.lib = ctypes.cdll.LoadLibrary(locate_lib('align.so')) self.build = self.lib.build self.build.argtypes = [ ndpointer(self.score_type, flags=arrflages), self.index_type, # isize self.index_type, # jsize self.score_type, # rho self.score_type, # sigma self.short_type, # local_ ] self.backtrack = self.lib.backtrack self.backtrack.rettype = self.index_type self.backtrack.argtypes = [ ndpointer(self.score_type, flags=arrflages), self.index_type, # isize self.index_type, # jsize self.index_type, # istart self.index_type, # jstart ndpointer(self.index_type, flags=arrflages), # iarr index ndpointer(self.index_type, flags=arrflages), # jarr index self.short_type, # global_ ]
def loadPupilFitC(): pupil_fit = loadclib.loadCLibrary("pupil_fit") # From sa_library/multi_fit.c pupil_fit.mFitGetFitImage.argtypes = [ctypes.c_void_p, ndpointer(dtype=numpy.float64)] pupil_fit.mFitGetNError.argtypes = [ctypes.c_void_p] pupil_fit.mFitGetNError.restype = ctypes.c_int pupil_fit.mFitGetPeakPropertyDouble.argtypes = [ctypes.c_void_p, ndpointer(dtype=numpy.float64), ctypes.c_char_p] pupil_fit.mFitGetPeakPropertyInt.argtypes = [ctypes.c_void_p, ndpointer(dtype=numpy.int32), ctypes.c_char_p] pupil_fit.mFitGetResidual.argtypes = [ctypes.c_void_p, ndpointer(dtype=numpy.float64)] pupil_fit.mFitGetUnconverged.argtypes = [ctypes.c_void_p] pupil_fit.mFitGetUnconverged.restype = ctypes.c_int pupil_fit.mFitIterateLM.argtypes = [ctypes.c_void_p] pupil_fit.mFitNewBackground.argtypes = [ctypes.c_void_p, ndpointer(dtype=numpy.float64)] pupil_fit.mFitNewImage.argtypes = [ctypes.c_void_p, ndpointer(dtype=numpy.float64)] pupil_fit.mFitRemoveErrorPeaks.argtypes = [ctypes.c_void_p] pupil_fit.mFitRemoveRunningPeaks.argtypes = [ctypes.c_void_p] pupil_fit.mFitSetPeakStatus.argtypes = [ctypes.c_void_p, ndpointer(dtype=numpy.int32)] # From pupilfn/pupil_fit.c pupil_fit.pfitCleanup.argtypes = [ctypes.c_void_p] pupil_fit.pfitInitialize.argtypes = [ctypes.c_void_p, ndpointer(dtype=numpy.float64), ndpointer(dtype=numpy.float64), ctypes.c_double, ctypes.c_int, ctypes.c_int] pupil_fit.pfitInitialize.restype = ctypes.POINTER(daoFitC.fitData) pupil_fit.pfitNewPeaks.argtypes = [ctypes.c_void_p, ndpointer(dtype=numpy.float64), ctypes.c_char_p, ctypes.c_int] pupil_fit.pfitSetZRange.argtypes = [ctypes.c_void_p, ctypes.c_double, ctypes.c_double] return pupil_fit
def pmc(ei,ej,nnodes,nnedges): #ei, ej is edge list whose index starts from 0 degrees = np.zeros(nnodes,dtype = np.int32) new_ei = [] new_ej = [] for i in range(nnedges): degrees[ei[i]] += 1 if ej[i] <= ei[i] + 1: new_ei.append(ei[i]) new_ej.append(ej[i]) maxd = max(degrees) offset = 0 new_ei = np.array(new_ei,dtype = np.int32) new_ej = np.array(new_ej,dtype = np.int32) outsize = maxd output = np.zeros(maxd,dtype = np.int32) lib = ctypes.cdll.LoadLibrary("libpmc.dylib") fun = lib.max_clique #call C function fun.restype = np.int32 fun.argtypes = [ctypes.c_int32,ndpointer(ctypes.c_int32, flags="C_CONTIGUOUS"), ndpointer(ctypes.c_int32, flags="C_CONTIGUOUS"),ctypes.c_int32, ctypes.c_int32,ndpointer(ctypes.c_int32, flags="C_CONTIGUOUS")] clique_size = fun(len(new_ei),new_ei,new_ej,offset,outsize,output) max_clique = np.empty(clique_size,dtype = np.int32) max_clique[:]=[output[i] for i in range(clique_size)] return max_clique
def does_mapping_exist(v, this_type, atom_pos, atomtype, eps): """No XML documentation summary. """ libpath = path.join(path.dirname(__file__), "ftypes.celib.so") method = static_symbol("symmetry_module_c", "does_mapping_exist_c", libpath, True) method.argtypes = [ndpointer(dtype=float, ndim=1, shape=(3,), flags="F"), c_int_p, ndpointer(dtype=float, ndim=2, flags="F"), c_int_p, c_int_p, ndpointer(dtype=int, ndim=1, flags="F"), c_int_p, c_bool_p, c_double_p] v_a = require(v, float, "F") this_type_c = c_int(this_type) atom_pos_a = require(atom_pos, float, "F") atom_pos_0 = c_int(atom_pos_a.shape[0]) atom_pos_1 = c_int(atom_pos_a.shape[1]) atomtype_a = require(atomtype, int, "F") atomtype_0 = c_int(atomtype_a.shape[0]) mapped_c = c_bool(False) eps_c = c_double(eps) method(v_a, byref(this_type_c), atom_pos_a, byref(atom_pos_0), byref(atom_pos_1), atomtype_a, byref(atomtype_0), byref(mapped_c), byref(eps_c)) result = FtypesResult("symmetry_module", "does_mapping_exist", "Subroutine") result.add("mapped", mapped_c.value) return result
def kmeans(X, nclst, maxiter=0, numruns=1): """Wrapper for Peter Gehlers accelerated MPI-Kmeans routine.""" mpikmeanslib = N.ctypeslib.load_library("libmpikmeans.so", ".") mpikmeanslib.kmeans.restype = c_double mpikmeanslib.kmeans.argtypes = [ ndpointer(dtype=c_double, ndim=1, flags="C_CONTIGUOUS"), ndpointer(dtype=c_double, ndim=1, flags="C_CONTIGUOUS"), ndpointer(dtype=c_uint, ndim=1, flags="C_CONTIGUOUS"), c_uint, c_uint, c_uint, c_uint, c_uint, ] npts, dim = X.shape assignments = empty((npts), c_uint) # bestSSE=N.Inf # bestassignments=empty( (npts), c_uint) Xvec = array(reshape(X, (-1,)), c_double, order="C") permutation = N.random.permutation(range(npts)) # randomize order of points CX = array(X[permutation[:nclst], :], c_double, order="C").flatten() print CX SSE = mpikmeanslib.kmeans(CX, Xvec, assignments, dim, npts, min(nclst, npts), maxiter, numruns) return reshape(CX, (nclst, dim)), SSE, (assignments + 1)
def __init__(self, method='full', sampling=(-1,-1), rank=5, reg=0.01, tol=1E-6, iters=500, verbose=True): modes = {'full':0 , 'subsample': 1} if method not in modes: raise ValueError("'method' must be one of" + modes.keys()) self.method = method self._mode = modes[method] if method == 'subsample' and -1 in sampling: raise ValueError("'method' is set to 'subsample' but 'sampling' is not set.") self.sampling = sampling self.rank = rank self.reg = reg self.tol = tol self.iters = iters self.verbose = verbose libpath = os.path.dirname(os.path.abspath(__file__)) + '/librosl.so.0.2' self._pyrosl = ctypes.cdll.LoadLibrary(libpath).pyROSL self._pyrosl.restype = ctypes.c_int self._pyrosl.argtypes = [ ndpointer(ctypes.c_double, flags="F_CONTIGUOUS"), ndpointer(ctypes.c_double, flags="F_CONTIGUOUS"), ndpointer(ctypes.c_double, flags="F_CONTIGUOUS"), ndpointer(ctypes.c_double, flags="F_CONTIGUOUS"), ctypes.c_int, ctypes.c_int, ctypes.c_int, ctypes.c_double, ctypes.c_double, ctypes.c_int, ctypes.c_int, ctypes.c_int, ctypes.c_int, ctypes.c_bool] self.components_ = None
def test_dtype(self): dt = np.intc p = ndpointer(dtype=dt) self.assertTrue(p.from_param(np.array([1], dt))) dt = "<i4" p = ndpointer(dtype=dt) self.assertTrue(p.from_param(np.array([1], dt))) dt = np.dtype(">i4") p = ndpointer(dtype=dt) p.from_param(np.array([1], dt)) self.assertRaises(TypeError, p.from_param, np.array([1], dt.newbyteorder("swap"))) dtnames = ["x", "y"] dtformats = [np.intc, np.float64] dtdescr = {"names": dtnames, "formats": dtformats} dt = np.dtype(dtdescr) p = ndpointer(dtype=dt) self.assertTrue(p.from_param(np.zeros((10,), dt))) samedt = np.dtype(dtdescr) p = ndpointer(dtype=samedt) self.assertTrue(p.from_param(np.zeros((10,), dt))) dt2 = np.dtype(dtdescr, align=True) if dt.itemsize != dt2.itemsize: self.assertRaises(TypeError, p.from_param, np.zeros((10,), dt2)) else: self.assertTrue(p.from_param(np.zeros((10,), dt2)))
def __init__(self, scheme="midpoint", solver="hll"): from ctypes import CDLL, POINTER, CFUNCTYPE, Structure, c_double, c_int from numpy import float64, int32 from numpy.ctypeslib import ndpointer from os.path import abspath, dirname from os import popen dbl_arr = ndpointer(dtype=float64, flags=("C_CONTIGUOUS", "WRITEABLE")) dbl_vec = ndpointer(dtype=float64, flags=("C_CONTIGUOUS")) int_arr = ndpointer(dtype=int32, flags=("C_CONTIGUOUS", "WRITEABLE")) int_vec = ndpointer(dtype=int32, flags=("C_CONTIGUOUS")) lib_home = dirname(abspath(popen("find . -name *.so").readline())) clib = CDLL(lib_home + "/" + self.libname + ".so") self.schemes = ["fwd_euler", "midpoint", "RK3", "ctu_hancock"] self.ghost_cells = dict(zip(self.schemes, (2, 4, 6, 4))) self.advance = {} assert scheme in self.schemes assert solver in self.solvers for sname in self.schemes: self.advance[sname] = getattr(clib, "advance_state_" + sname) self.advance[sname].argtypes = [dbl_arr, c_double] clib.integrate_init.argtypes = [int_vec, dbl_vec, c_int] clib.integrate_free.argtypes = [] clib.get_failure_mask.argtypes = [int_arr] clib.set_riemann_solver.argtypes = [c_int] self.clib = clib self.scheme = scheme self.NumGhostCells = self.ghost_cells[self.scheme] self.solver = solver
def setCInterface(homotopy_lib): global directory global homotopy if sys.platform == "win32": homotopy = cdll.LoadLibrary(directory + homotopy_lib + ".dll") else: homotopy = cdll.LoadLibrary(directory + homotopy_lib + ".so") l1flt_size = homotopy.getL1FLTSize() if l1flt_size == 4: float_type = c_float float_array_type = numpy.float32 elif l1flt_size == 8: float_type = c_double float_array_type = numpy.float64 homotopy.getXVector.argtypes = [ndpointer(dtype=float_array_type)] homotopy.initialize.argtypes = [ndpointer(dtype=float_array_type), c_int, c_int, c_int, c_int, c_int] homotopy.l2Error.argtypes = [ndpointer(dtype=float_array_type)] homotopy.l2Error.restype = float_type homotopy.newYVector.argtypes = [ndpointer(dtype=float_array_type)] homotopy.solve.argtypes = [float_type, c_int] homotopy.solve.restype = float_type if hasattr(homotopy, "getVisited"): homotopy.getVisited.argtypes = [ndpointer(dtype=numpy.int32)] if hasattr(homotopy, "initializeGPU"): homotopy.initializeGPU.argtypes = [c_char_p, c_int, c_int, c_int]
def test_dtype(self): dt = np.intc p = ndpointer(dtype=dt) self.assertTrue(p.from_param(np.array([1], dt))) dt = '<i4' p = ndpointer(dtype=dt) self.assertTrue(p.from_param(np.array([1], dt))) dt = np.dtype('>i4') p = ndpointer(dtype=dt) p.from_param(np.array([1], dt)) self.assertRaises(TypeError, p.from_param, np.array([1], dt.newbyteorder('swap'))) dtnames = ['x', 'y'] dtformats = [np.intc, np.float64] dtdescr = {'names' : dtnames, 'formats' : dtformats} dt = np.dtype(dtdescr) p = ndpointer(dtype=dt) self.assertTrue(p.from_param(np.zeros((10,), dt))) samedt = np.dtype(dtdescr) p = ndpointer(dtype=samedt) self.assertTrue(p.from_param(np.zeros((10,), dt))) dt2 = np.dtype(dtdescr, align=True) if dt.itemsize != dt2.itemsize: self.assertRaises(TypeError, p.from_param, np.zeros((10,), dt2)) else: self.assertTrue(p.from_param(np.zeros((10,), dt2)))
def actionAngleTorus_Freqs_c(pot,jr,jphi,jz, tol=0.003): """ NAME: actionAngleTorus_Freqs_c PURPOSE: compute frequencies on a single torus INPUT: pot - Potential object or list thereof jr - radial action (scalar) jphi - azimuthal action (scalar) jz - vertical action (scalar) tol= (0.003) goal for |dJ|/|J| along the torus OUTPUT: (Omegar,Omegaphi,Omegaz,flag) HISTORY: 2015-08-05/07 - Written - Bovy (UofT) """ #Parse the potential npot, pot_type, pot_args= _parse_pot(pot,potfortorus=True) #Set up result Omegar= numpy.empty(1) Omegaphi= numpy.empty(1) Omegaz= numpy.empty(1) flag= ctypes.c_int(0) #Set up the C code ndarrayFlags= ('C_CONTIGUOUS','WRITEABLE') actionAngleTorus_FreqsFunc= _lib.actionAngleTorus_Freqs actionAngleTorus_FreqsFunc.argtypes=\ [ctypes.c_double, ctypes.c_double, ctypes.c_double, ctypes.c_int, ndpointer(dtype=numpy.int32,flags=ndarrayFlags), ndpointer(dtype=numpy.float64,flags=ndarrayFlags), ctypes.c_double, ndpointer(dtype=numpy.float64,flags=ndarrayFlags), ndpointer(dtype=numpy.float64,flags=ndarrayFlags), ndpointer(dtype=numpy.float64,flags=ndarrayFlags), ctypes.POINTER(ctypes.c_int)] #Array requirements Omegar= numpy.require(Omegar,dtype=numpy.float64,requirements=['C','W']) Omegaphi= numpy.require(Omegaphi,dtype=numpy.float64,requirements=['C','W']) Omegaz= numpy.require(Omegaz,dtype=numpy.float64,requirements=['C','W']) #Run the C code actionAngleTorus_FreqsFunc(ctypes.c_double(jr), ctypes.c_double(jphi), ctypes.c_double(jz), ctypes.c_int(npot), pot_type, pot_args, ctypes.c_double(tol), Omegar,Omegaphi,Omegaz, ctypes.byref(flag)) return (Omegar[0],Omegaphi[0],Omegaz[0],flag.value)
def setCInterface(homotopy_lib): global homotopy homotopy = loadclib.loadCLibrary(homotopy_lib) l1flt_size = homotopy.getL1FLTSize() if(l1flt_size == 4): float_type = c_float float_array_type = numpy.float32 elif(l1flt_size == 8): float_type = c_double float_array_type = numpy.float64 homotopy.getXVector.argtypes = [ndpointer(dtype=float_array_type)] homotopy.initialize.argtypes = [ndpointer(dtype=float_array_type), c_int, c_int, c_int, c_int, c_int] homotopy.l2Error.argtypes = [ndpointer(dtype=float_array_type)] homotopy.l2Error.restype = float_type homotopy.newYVector.argtypes = [ndpointer(dtype=float_array_type)] homotopy.solve.argtypes = [float_type, c_int] homotopy.solve.restype = float_type if(hasattr(homotopy, "getVisited")): homotopy.getVisited.argtypes = [ndpointer(dtype=numpy.int32)] if(hasattr(homotopy, "initializeGPU")): homotopy.initializeGPU.argtypes = [c_char_p, c_int, c_int, c_int]
def actionAngleStaeckel_calcu0(E,Lz,pot,delta): """ NAME: actionAngleStaeckel_calcu0 PURPOSE: Use C to calculate u0 in the Staeckel approximation INPUT: E, Lz - energy and angular momentum pot - Potential or list of such instances delta - focal length of prolate spheroidal coordinates OUTPUT: (u0,err) u0 : array, shape (len(E)) err - non-zero if error occured HISTORY: 2012-12-03 - Written - Bovy (IAS) """ #Parse the potential npot, pot_type, pot_args= _parse_pot(pot,potforactions=True) #Set up result arrays u0= numpy.empty(len(E)) err= ctypes.c_int(0) #Set up the C code ndarrayFlags= ('C_CONTIGUOUS','WRITEABLE') actionAngleStaeckel_actionsFunc= _lib.calcu0 actionAngleStaeckel_actionsFunc.argtypes= [ctypes.c_int, ndpointer(dtype=numpy.float64,flags=ndarrayFlags), ndpointer(dtype=numpy.float64,flags=ndarrayFlags), ctypes.c_int, ndpointer(dtype=numpy.int32,flags=ndarrayFlags), ndpointer(dtype=numpy.float64,flags=ndarrayFlags), ctypes.c_double, ndpointer(dtype=numpy.float64,flags=ndarrayFlags), ctypes.POINTER(ctypes.c_int)] #Array requirements, first store old order f_cont= [E.flags['F_CONTIGUOUS'], Lz.flags['F_CONTIGUOUS']] E= numpy.require(E,dtype=numpy.float64,requirements=['C','W']) Lz= numpy.require(Lz,dtype=numpy.float64,requirements=['C','W']) u0= numpy.require(u0,dtype=numpy.float64,requirements=['C','W']) #Run the C code actionAngleStaeckel_actionsFunc(len(E), E, Lz, ctypes.c_int(npot), pot_type, pot_args, ctypes.c_double(delta), u0, ctypes.byref(err)) #Reset input arrays if f_cont[0]: E= numpy.asfortranarray(E) if f_cont[1]: Lz= numpy.asfortranarray(Lz) return (u0,err.value)
def test_populate_z_shells(clib, formal_integral_model, p): ''' Test the case where p > r[0] ''' func = clib.populate_z func.restype = ctypes.c_int64 func.argtypes = [ ctypes.POINTER(StorageModel), # storage c_double, # p ndpointer(dtype=np.float64), # oz ndpointer(dtype=np.int64) # oshell_id ] size = formal_integral_model.no_of_shells_i r_inner = as_array(formal_integral_model.r_inner_i, (size,)) r_outer = as_array(formal_integral_model.r_outer_i, (size,)) p = r_inner[0] + (r_outer[-1] - r_inner[0]) * p idx = np.searchsorted(r_outer, p, side='right') oz = np.zeros(size * 2) oshell_id = np.zeros_like(oz, dtype=np.int64) offset = size - idx expected_N = (offset) * 2 expected_oz = np.zeros_like(oz) expected_oshell_id = np.zeros_like(oshell_id) # Calculated way to determine which shells get hit expected_oshell_id[:expected_N] = np.abs( np.arange(0.5, expected_N, 1) - offset) - 0.5 + idx expected_oz[0:offset] = 1 + calculate_z( r_outer[np.arange(size, idx, -1) - 1], p) expected_oz[offset:expected_N] = 1 - calculate_z( r_outer[np.arange(idx, size, 1)], p) N = func( formal_integral_model, p, oz, oshell_id ) assert N == expected_N ntest.assert_allclose( oshell_id, expected_oshell_id ) ntest.assert_allclose( oz, expected_oz, atol=1e-5 )
def __init__(self, dbname, host, user, password): self.connect = "dbname=%s host=%s user=%s password=%s"%(dbname, host, user, password) #TODO Harcode self.array_1d_double = npct.ndpointer(dtype=np.double, ndim=1, flags='CONTIGUOUS') self.array_1d_int = npct.ndpointer(dtype=np.int64, ndim=1, flags='CONTIGUOUS') self.array_2d_double = npct.ndpointer(dtype=np.double, ndim=2, flags='CONTIGUOUS') #TODO path harcode self.libcd = npct.load_library("cfsfdp", "/home/sergio/iibm/workspace/NeuroDB/NeuroDB/cfunctions/cfsfdp")
def sens(self, input_time, input_bp, input_angle, input_respiration, output_time, output_hr, parameters, output_sensitivity, flags=numpy.array([0.0])): array_1d_double = npct.ndpointer(dtype=numpy.double, ndim=1, flags='CONTIGUOUS') array_3d_double = npct.ndpointer(dtype=numpy.double, ndim=3, flags='CONTIGUOUS') self.so.sens.argtypes = [c_int, array_1d_double, array_1d_double, array_1d_double, array_1d_double, c_int, array_1d_double, array_1d_double, c_int, array_1d_double, array_3d_double, array_1d_double] self.so.sens.restype = c_int return self.so.sens(len(input_time), input_time, input_bp, input_angle, input_respiration, len(output_time), output_time, output_hr, len(parameters), parameters, output_sensitivity, flags)
def genTriangles(bp1, bp2, k1, k2): # TODO: Make work on Windows lib = ctypes.cdll.LoadLibrary("libtriangle.so") cGenTri = lib.buildTwoLayerTriangles cGenTri.argtypes = [ ndpointer(ctypes.c_int), ndpointer(ctypes.c_int), ctypes.c_int, ctypes.c_int, ndpointer(ctypes.c_int), ctypes.c_int, ctypes.c_int, ] len1 = np.array([bp.shape[0] for bp in bp1]) len2 = np.array([bp.shape[0] for bp in bp2]) ind1 = np.argsort(len1) ind2 = np.argsort(len2) i1 = ind1[-1] i2 = ind2[-1] BP1 = (2 * bp1[i1]).astype(np.int32) BP2 = (2 * bp2[i2]).astype(np.int32) dist = ((BP1[0] - BP2) * (BP1[0] - BP2)).sum(axis=1) ind = np.argmin(dist) BP2 = np.roll(BP2, -ind, axis=0) n1 = BP1.shape[0] n2 = BP2.shape[0] BP1 = BP1.reshape(2 * n1) BP2 = BP2.reshape(2 * n2) triangles = np.ascontiguousarray(np.zeros((n1 + n2) * 3 * 3, dtype=np.int32)) cGenTri( triangles, np.ascontiguousarray(BP1, dtype=np.int32), n1, 2 * k1, np.ascontiguousarray(BP2, dtype=np.int32), n2, 2 * k2, ) triangles = triangles.reshape((n1 + n2, 3, 3)) """ tri1 = [ [0,0,0],[1,0,0],[0,1,0]] tri2 = [ [0,0,0],[1,0,0],[0,0,1]] tri3 = [ [0,0,0],[0,0,1],[0,1,0]] tri4 = [ [1,0,0],[0,1,0],[0,0,1]] return np.array([tri1, tri2, tri3, tri4]) """ return triangles
def eval_force_c(pot, R, z, zforce=False): """ NAME: eval_force_c PURPOSE: Use C to evaluate the interpolated potential's forces INPUT: pot - Potential or list of such instances R - array z - array zforce= if True, return the vertical force, otherwise return the radial force OUTPUT: force evaluated R and z HISTORY: 2013-01-29 - Written - Bovy (IAS) """ from galpy.orbit_src.integrateFullOrbit import _parse_pot # here bc otherwise there is an infinite loop # Parse the potential npot, pot_type, pot_args = _parse_pot(pot) # Set up result arrays out = numpy.empty((len(R))) err = ctypes.c_int(0) # Set up the C code ndarrayFlags = ("C_CONTIGUOUS", "WRITEABLE") if zforce: interppotential_calc_forceFunc = _lib.eval_zforce else: interppotential_calc_forceFunc = _lib.eval_rforce interppotential_calc_forceFunc.argtypes = [ ctypes.c_int, ndpointer(dtype=numpy.float64, flags=ndarrayFlags), ndpointer(dtype=numpy.float64, flags=ndarrayFlags), ctypes.c_int, ndpointer(dtype=numpy.int32, flags=ndarrayFlags), ndpointer(dtype=numpy.float64, flags=ndarrayFlags), ndpointer(dtype=numpy.float64, flags=ndarrayFlags), ctypes.POINTER(ctypes.c_int), ] # Array requirements, first store old order f_cont = [R.flags["F_CONTIGUOUS"], z.flags["F_CONTIGUOUS"]] R = numpy.require(R, dtype=numpy.float64, requirements=["C", "W"]) z = numpy.require(z, dtype=numpy.float64, requirements=["C", "W"]) out = numpy.require(out, dtype=numpy.float64, requirements=["C", "W"]) # Run the C code interppotential_calc_forceFunc(len(R), R, z, ctypes.c_int(npot), pot_type, pot_args, out, ctypes.byref(err)) # Reset input arrays if f_cont[0]: R = numpy.asfortranarray(R) if f_cont[1]: z = numpy.asfortranarray(z) return (out, err.value)
def test_flags(self): x = np.array([[1, 2], [3, 4]], order='F') p = ndpointer(flags='FORTRAN') self.assertTrue(p.from_param(x)) p = ndpointer(flags='CONTIGUOUS') self.assertRaises(TypeError, p.from_param, x) p = ndpointer(flags=x.flags.num) self.assertTrue(p.from_param(x)) self.assertRaises(TypeError, p.from_param, np.array([[1, 2], [3, 4]]))
def check_ndim(self): p = ndpointer(ndim=0) self.assert_(p.from_param(N.array(1))) self.assertRaises(TypeError, p.from_param, N.array([1])) p = ndpointer(ndim=1) self.assertRaises(TypeError, p.from_param, N.array(1)) self.assert_(p.from_param(N.array([1]))) p = ndpointer(ndim=2) self.assert_(p.from_param(N.array([[1]])))
def eval_potential_c(pot,R,z): """ NAME: eval_potential_c PURPOSE: Use C to evaluate the interpolated potential INPUT: pot - Potential or list of such instances R - array z - array OUTPUT: potential evaluated R and z HISTORY: 2013-01-24 - Written - Bovy (IAS) """ from galpy.orbit.integrateFullOrbit import _parse_pot #here bc otherwise there is an infinite loop #Parse the potential npot, pot_type, pot_args= _parse_pot(pot,potforactions=True) #Set up result arrays out= numpy.empty((len(R))) err= ctypes.c_int(0) #Set up the C code ndarrayFlags= ('C_CONTIGUOUS','WRITEABLE') interppotential_calc_potentialFunc= _lib.eval_potential interppotential_calc_potentialFunc.argtypes= [ctypes.c_int, ndpointer(dtype=numpy.float64,flags=ndarrayFlags), ndpointer(dtype=numpy.float64,flags=ndarrayFlags), ctypes.c_int, ndpointer(dtype=numpy.int32,flags=ndarrayFlags), ndpointer(dtype=numpy.float64,flags=ndarrayFlags), ndpointer(dtype=numpy.float64,flags=ndarrayFlags), ctypes.POINTER(ctypes.c_int)] #Array requirements, first store old order f_cont= [R.flags['F_CONTIGUOUS'], z.flags['F_CONTIGUOUS']] R= numpy.require(R,dtype=numpy.float64,requirements=['C','W']) z= numpy.require(z,dtype=numpy.float64,requirements=['C','W']) out= numpy.require(out,dtype=numpy.float64,requirements=['C','W']) #Run the C code interppotential_calc_potentialFunc(len(R), R, z, ctypes.c_int(npot), pot_type, pot_args, out, ctypes.byref(err)) #Reset input arrays if f_cont[0]: R= numpy.asfortranarray(R) if f_cont[1]: z= numpy.asfortranarray(z) return (out,err.value)
def test_ndim(self): p = ndpointer(ndim=0) self.assertTrue(p.from_param(np.array(1))) self.assertRaises(TypeError, p.from_param, np.array([1])) p = ndpointer(ndim=1) self.assertRaises(TypeError, p.from_param, np.array(1)) self.assertTrue(p.from_param(np.array([1]))) p = ndpointer(ndim=2) self.assertTrue(p.from_param(np.array([[1]])))
def check_flags(self): x = N.array([[1,2,3]], order='F') p = ndpointer(flags='FORTRAN') self.assert_(p.from_param(x)) p = ndpointer(flags='CONTIGUOUS') self.assertRaises(TypeError, p.from_param, x) p = ndpointer(flags=x.flags.num) self.assert_(p.from_param(x)) self.assertRaises(TypeError, p.from_param, N.array([[1,2,3]]))
def test_ndim(self): p = ndpointer(ndim=0) assert_(p.from_param(np.array(1))) assert_raises(TypeError, p.from_param, np.array([1])) p = ndpointer(ndim=1) assert_raises(TypeError, p.from_param, np.array(1)) assert_(p.from_param(np.array([1]))) p = ndpointer(ndim=2) assert_(p.from_param(np.array([[1]])))
def setnodeprobs(self, node_p, parent_states, probs): parenttype = ndpointer('int32', ndim=1, shape=(len(parent_states),), flags='C') self.ln.SetNodeProbs_bn.argtypes = [ c_void_p, parenttype, ndpointer('float32', ndim=1, shape=(len(probs),),flags='C') ] self.ln.SetNodeProbs_bn.restype = None self.ln.SetNodeProbs_bn(node_p, parent_states, probs)
def actionAngleStaeckel_calcu0(E, Lz, pot, delta): """ NAME: actionAngleStaeckel_calcu0 PURPOSE: Use C to calculate u0 in the Staeckel approximation INPUT: E, Lz - energy and angular momentum pot - Potential or list of such instances delta - focal length of prolate spheroidal coordinates OUTPUT: (u0,err) u0 : array, shape (len(E)) err - non-zero if error occured HISTORY: 2012-12-03 - Written - Bovy (IAS) """ #Parse the potential from ..orbit.integrateFullOrbit import _parse_pot npot, pot_type, pot_args = _parse_pot(pot, potforactions=True) #Set up result arrays u0 = numpy.empty(len(E)) err = ctypes.c_int(0) #Parse delta delta = numpy.atleast_1d(delta) ndelta = len(delta) #Set up the C code ndarrayFlags = ('C_CONTIGUOUS', 'WRITEABLE') actionAngleStaeckel_actionsFunc = _lib.calcu0 actionAngleStaeckel_actionsFunc.argtypes = [ ctypes.c_int, ndpointer(dtype=numpy.float64, flags=ndarrayFlags), ndpointer(dtype=numpy.float64, flags=ndarrayFlags), ctypes.c_int, ndpointer(dtype=numpy.int32, flags=ndarrayFlags), ndpointer(dtype=numpy.float64, flags=ndarrayFlags), ctypes.c_int, ndpointer(dtype=numpy.float64, flags=ndarrayFlags), ndpointer(dtype=numpy.float64, flags=ndarrayFlags), ctypes.POINTER(ctypes.c_int) ] #Array requirements, first store old order f_cont = [ E.flags['F_CONTIGUOUS'], Lz.flags['F_CONTIGUOUS'], delta.flags['F_CONTIGUOUS'] ] E = numpy.require(E, dtype=numpy.float64, requirements=['C', 'W']) Lz = numpy.require(Lz, dtype=numpy.float64, requirements=['C', 'W']) delta = numpy.require(delta, dtype=numpy.float64, requirements=['C', 'W']) u0 = numpy.require(u0, dtype=numpy.float64, requirements=['C', 'W']) #Run the C code actionAngleStaeckel_actionsFunc(len(E), E, Lz, ctypes.c_int(npot), pot_type, pot_args, ctypes.c_int(ndelta), delta, u0, ctypes.byref(err)) #Reset input arrays if f_cont[0]: E = numpy.asfortranarray(E) if f_cont[1]: Lz = numpy.asfortranarray(Lz) if f_cont[2]: delta = numpy.asfortranarray(delta) return (u0, err.value)
def actionAngleUminUmaxVminStaeckel_c(pot, delta, R, vR, vT, z, vz, u0=None): """ NAME: actionAngleUminUmaxVminStaeckel_c PURPOSE: Use C to calculate umin, umax, and vmin using the Staeckel approximation INPUT: pot - Potential or list of such instances delta - focal length of prolate spheroidal coordinates R, vR, vT, z, vz - coordinates (arrays) OUTPUT: (umin,umax,vmin,err) umin,umax,vmin : array, shape (len(R)) err - non-zero if error occured HISTORY: 2017-12-12 - Written - Bovy (UofT) """ if u0 is None: u0, dummy = bovy_coords.Rz_to_uv(R, z, delta=numpy.atleast_1d(delta)) #Parse the potential from ..orbit.integrateFullOrbit import _parse_pot npot, pot_type, pot_args = _parse_pot(pot, potforactions=True) #Parse delta delta = numpy.atleast_1d(delta) ndelta = len(delta) #Set up result arrays umin = numpy.empty(len(R)) umax = numpy.empty(len(R)) vmin = numpy.empty(len(R)) err = ctypes.c_int(0) #Set up the C code ndarrayFlags = ('C_CONTIGUOUS', 'WRITEABLE') actionAngleStaeckel_actionsFunc = _lib.actionAngleStaeckel_uminUmaxVmin actionAngleStaeckel_actionsFunc.argtypes = [ ctypes.c_int, ndpointer(dtype=numpy.float64, flags=ndarrayFlags), ndpointer(dtype=numpy.float64, flags=ndarrayFlags), ndpointer(dtype=numpy.float64, flags=ndarrayFlags), ndpointer(dtype=numpy.float64, flags=ndarrayFlags), ndpointer(dtype=numpy.float64, flags=ndarrayFlags), ndpointer(dtype=numpy.float64, flags=ndarrayFlags), ctypes.c_int, ndpointer(dtype=numpy.int32, flags=ndarrayFlags), ndpointer(dtype=numpy.float64, flags=ndarrayFlags), ctypes.c_int, ndpointer(dtype=numpy.float64, flags=ndarrayFlags), ndpointer(dtype=numpy.float64, flags=ndarrayFlags), ndpointer(dtype=numpy.float64, flags=ndarrayFlags), ndpointer(dtype=numpy.float64, flags=ndarrayFlags), ctypes.POINTER(ctypes.c_int) ] #Array requirements, first store old order f_cont = [ R.flags['F_CONTIGUOUS'], vR.flags['F_CONTIGUOUS'], vT.flags['F_CONTIGUOUS'], z.flags['F_CONTIGUOUS'], vz.flags['F_CONTIGUOUS'], u0.flags['F_CONTIGUOUS'], delta.flags['F_CONTIGUOUS'] ] R = numpy.require(R, dtype=numpy.float64, requirements=['C', 'W']) vR = numpy.require(vR, dtype=numpy.float64, requirements=['C', 'W']) vT = numpy.require(vT, dtype=numpy.float64, requirements=['C', 'W']) z = numpy.require(z, dtype=numpy.float64, requirements=['C', 'W']) vz = numpy.require(vz, dtype=numpy.float64, requirements=['C', 'W']) u0 = numpy.require(u0, dtype=numpy.float64, requirements=['C', 'W']) delta = numpy.require(delta, dtype=numpy.float64, requirements=['C', 'W']) umin = numpy.require(umin, dtype=numpy.float64, requirements=['C', 'W']) umax = numpy.require(umax, dtype=numpy.float64, requirements=['C', 'W']) vmin = numpy.require(vmin, dtype=numpy.float64, requirements=['C', 'W']) #Run the C code actionAngleStaeckel_actionsFunc(len(R), R, vR, vT, z, vz, u0, ctypes.c_int(npot), pot_type, pot_args, ctypes.c_int(ndelta), delta, umin, umax, vmin, ctypes.byref(err)) #Reset input arrays if f_cont[0]: R = numpy.asfortranarray(R) if f_cont[1]: vR = numpy.asfortranarray(vR) if f_cont[2]: vT = numpy.asfortranarray(vT) if f_cont[3]: z = numpy.asfortranarray(z) if f_cont[4]: vz = numpy.asfortranarray(vz) if f_cont[5]: u0 = numpy.asfortranarray(u0) if f_cont[6]: delta = numpy.asfortranarray(delta) return (umin, umax, vmin, err.value)
def __init__(self, ident): """Create an em empty model for parameter estimation. Args: ident (string): Name of the model instance. Returns: SysIdent model object. """ if (sys.platform == 'win32'): self.obj = cdll.LoadLibrary("OMSimulator.dll") else: self.obj = cdll.LoadLibrary("libOMSimulator.so") self.obj.omsi_newSysIdentModel.argtypes = [ctypes.c_char_p] self.obj.omsi_newSysIdentModel.restype = ctypes.c_void_p self.obj.omsi_freeSysIdentModel.argtypes = [ctypes.c_void_p] self.obj.omsi_describe.argtypes = [ctypes.c_void_p] self.obj.omsi_describe.restype = ctypes.c_int self.obj.omsi_initialize.argtypes = [ ctypes.c_void_p, ctypes.c_int, ndpointer(dtype=np.float64, ndim=1, flags='C_CONTIGUOUS'), ctypes.c_int, ctypes.POINTER(ctypes.c_char_p), ctypes.c_int, ctypes.POINTER(ctypes.c_char_p), ctypes.c_int ] self.obj.omsi_initialize.restype = ctypes.c_int self.obj.omsi_addMeasurement.argtypes = [ ctypes.c_void_p, ctypes.c_int, ctypes.c_char_p, ndpointer(dtype=np.float64, ndim=1, flags='C_CONTIGUOUS'), ctypes.c_int ] self.obj.omsi_addMeasurement.restype = ctypes.c_int self.obj.omsi_addInput.argtypes = [ ctypes.c_void_p, ctypes.c_char_p, ndpointer(dtype=np.float64, ndim=1, flags='C_CONTIGUOUS'), ctypes.c_int ] self.obj.omsi_addInput.restype = ctypes.c_int self.obj.omsi_addParameter.argtypes = [ ctypes.c_void_p, ctypes.c_char_p, ctypes.c_double ] self.obj.omsi_addParameter.restype = ctypes.c_int self.obj.omsi_getParameter.argtype = [ ctypes.c_void_p, ctypes.c_char_p, ctypes.POINTER(ctypes.c_double), ctypes.POINTER(ctypes.c_double) ] self.obj.omsi_getParameter.restype = ctypes.c_int self.obj.omsi_solve.argtypes = [ctypes.c_void_p, ctypes.c_char_p] self.obj.omsi_solve.restype = ctypes.c_int self.obj.omsi_setOptions_max_num_iterations.argtypes = [ ctypes.c_void_p, ctypes.c_int ] self.obj.omsi_setOptions_max_num_iterations.restype = ctypes.c_int self.obj.omsi_getState.argtypes = [ ctypes.c_void_p, ctypes.POINTER(ctypes.c_int) ] self.obj.omsi_getState.restype = ctypes.c_int self.simodel = self.obj.omsi_newSysIdentModel(ident) self.ident = ident
# TITLE, OR NON-INFRINGEMENT. IN NO EVENT SHALL ETH ZURICH BE LIABLE FOR ANY # DAMAGES, INCLUDING BUT NOT LIMITED TO DIRECT, INDIRECT, # SPECIAL OR CONSEQUENTIAL DAMAGES, ARISING OUT OF, RESULTING FROM, OR IN # ANY WAY CONNECTED WITH THIS SOFTWARE (WHETHER OR NOT BASED UPON WARRANTY, # CONTRACT, TORT OR OTHERWISE). # # from zonoml_imports import * from elina_manager_h import * from elina_abstract0_h import * import numpy as np from numpy.ctypeslib import ndpointer import ctypes _doublepp = ndpointer(dtype=np.uintp, ndim=1, flags='C') # ====================================================================== # # Basics # ====================================================================== # def zonoml_manager_alloc(): """ Allocates an ElinaManager. Returns ------- man : ElinaManagerPtr Pointer to the newly allocated ElinaManager.
("deltas", c_int * max_bispectrum_deltas), ("do_parity_odd", c_int), # logical ("DoFisher", c_int), # logical ("export_alpha_beta", c_int), # logical ("FisherNoise", c_double), ("FisherNoisePol", c_double), ("FisherNoiseFwhmArcmin", c_double), ("FullOutputFile", c_char * Ini_max_string_len), ("SparseFullOutput", c_int), # logical ] int_arg = POINTER(c_int) utils_3j = camblib.__amlutils_MOD_getthreejs utils_3j.argtypes = [ ndpointer(c_double, flags='C_CONTIGUOUS'), int_arg, int_arg, int_arg, int_arg ] def threej(l2, l3, m2, m3): """ Convenience wrapper around standard 3j function, returning array for all allowed l1 values :param l2: L_2 :param l3: L_3 :param m2: M_2 :param m3: M_3 :return: array of 3j from max(abs(l2-l3),abs(m2+m3)) .. l2+l3 """ l1min = max(np.abs(l2 - l3), np.abs(m2 + m3)) result = np.zeros(int(l3 + l2 - l1min + 1))
vl_kmeans_delete.restype = None vl_kmeans_delete.argtypes = [VlKMeans_p] # basic data processing vl_kmeans_reset = LIB['vl_kmeans_reset'] vl_kmeans_reset.restype = None vl_kmeans_reset.argtypes = [VlKMeans_p] vl_kmeans_cluster = LIB['vl_kmeans_cluster'] vl_kmeans_cluster.restype = c_double vl_kmeans_cluster.argtypes = [VlKMeans_p, c_void_p, vl_size, vl_size, vl_size] vl_kmeans_quantize = LIB['vl_kmeans_quantize'] vl_kmeans_quantize.restype = None vl_kmeans_quantize.argtypes = [ VlKMeans_p, npc.ndpointer(dtype=np.uint32), c_void_p, c_void_p, vl_size] # advanced data processing vl_kmeans_set_centers = LIB['vl_kmeans_set_centers'] vl_kmeans_set_centers.restype = None vl_kmeans_set_centers.argtypes = [VlKMeans_p, c_void_p, vl_size, vl_size] vl_kmeans_seed_centers_with_rand_data = \ LIB['vl_kmeans_seed_centers_with_rand_data'] vl_kmeans_seed_centers_with_rand_data.restype = None vl_kmeans_seed_centers_with_rand_data.argtypes = [ VlKMeans_p, c_void_p, vl_size, vl_size, vl_size] vl_kmeans_seed_centers_plus_plus = LIB['vl_kmeans_seed_centers_plus_plus'] vl_kmeans_seed_centers_plus_plus.restype = None vl_kmeans_seed_centers_plus_plus.argtypes = [
comm = MPI.COMM_WORLD rank = comm.Get_rank() size = comm.Get_size() # Ctypes initialization _IIRABM = ctypes.CDLL('/home/chase/IIRABM_MRM_GA/IIRABM_RuleGA.so') #_IIRABM = ctypes.CDLL('/users/r/c/rcockrel/iirabm_fullga/IIRABM_RuleGA.so') #_IIRABM = ctypes.CDLL('/global/cscratch1/sd/cockrell/IIRABM_RuleGA.so') # (oxyHeal,infectSpread,numRecurInj,numInfectRepeat,inj_number,seed,numMatrixElements,internalParameterization) _IIRABM.mainSimulation.argtypes = (ctypes.c_float, ctypes.c_int, ctypes.c_int, ctypes.c_int, ctypes.c_int, ctypes.c_int, ctypes.c_int, ctypes.POINTER(ctypes.c_float), ctypes.c_int) _IIRABM.mainSimulation.restype = ndpointer(dtype=ctypes.c_float, shape=(20, 5280)) numMatrixElements = 432 numStochasticReplicates = 40 array_type = ctypes.c_float * numMatrixElements selectedTimePoints = np.array([ 29, 59, 89, 119, 149, 179, 209, 239, 359, 479, 719, 1199, 1919, 3599, 5279 ]) numDataPoints = selectedTimePoints.shape[0] tnfMins = np.array([ 22.34, 20.74, 0, 0, 9.57, 1.6, 9.57, 0, 1.6, 0, 0, 0, 14.36, 19.15, 15.96 ]) tnfMaxs = np.array([ 135.64, 79, 47.87, 43.09, 49.47, 47.87, 55.85, 43.09, 60.64, 57.45, 97.34, 121.28, 84.57, 49.47, 76.60
_crequest_infer_ctx_result_new.argtypes = [POINTER(c_void_p), c_void_p, _utf8] _crequest_infer_ctx_result_del = _crequest.InferContextResultDelete _crequest_infer_ctx_result_del.argtypes = [c_void_p] _crequest_infer_ctx_result_modelname = _crequest.InferContextResultModelName _crequest_infer_ctx_result_modelname.restype = c_void_p _crequest_infer_ctx_result_modelname.argtypes = [c_void_p, POINTER(c_char_p)] _crequest_infer_ctx_result_modelver = _crequest.InferContextResultModelVersion _crequest_infer_ctx_result_modelver.restype = c_void_p _crequest_infer_ctx_result_modelver.argtypes = [c_void_p, POINTER(c_uint32)] _crequest_infer_ctx_result_dtype = _crequest.InferContextResultDataType _crequest_infer_ctx_result_dtype.restype = c_void_p _crequest_infer_ctx_result_dtype.argtypes = [c_void_p, POINTER(c_uint32)] _crequest_infer_ctx_result_dims = _crequest.InferContextResultDims _crequest_infer_ctx_result_dims.restype = c_void_p _crequest_infer_ctx_result_dims.argtypes = [c_void_p, c_uint64, ndpointer(c_uint32, flags="C_CONTIGUOUS"), POINTER(c_uint64)] _crequest_infer_ctx_result_next_raw = _crequest.InferContextResultNextRaw _crequest_infer_ctx_result_next_raw.restype = c_void_p _crequest_infer_ctx_result_next_raw.argtypes = [c_void_p, c_uint64, POINTER(c_char_p), POINTER(c_uint64)] _crequest_infer_ctx_result_class_cnt = _crequest.InferContextResultClassCount _crequest_infer_ctx_result_class_cnt.restype = c_void_p _crequest_infer_ctx_result_class_cnt.argtypes = [c_void_p, c_uint64, POINTER(c_uint64)] _crequest_infer_ctx_result_next_class = _crequest.InferContextResultNextClass _crequest_infer_ctx_result_next_class.restype = c_void_p _crequest_infer_ctx_result_next_class.argtypes = [c_void_p, c_uint64, POINTER(c_uint64), POINTER(c_float), POINTER(c_char_p)] def _raise_if_error(err):
import ctypes import math import numpy from numpy.ctypeslib import ndpointer import os import sys import storm_control.c_libraries.loadclib as loadclib try: image_manip = loadclib.loadCLibrary("c_image_manipulation") # C interface definition. image_manip.compare.argtypes = [ ndpointer(dtype=numpy.uint8), ndpointer(dtype=numpy.uint8), ctypes.c_int ] image_manip.compare.restype = ctypes.c_int rescale_fn_arg_types = [ ndpointer(dtype=numpy.uint8), ndpointer(dtype=numpy.uint16), ctypes.c_int, ctypes.c_int, ctypes.c_int, ctypes.c_int, ctypes.c_int, ctypes.c_double, ctypes.c_void_p, ctypes.c_void_p ] image_manip.rescaleImage000.argtypes = rescale_fn_arg_types image_manip.rescaleImage001.argtypes = rescale_fn_arg_types image_manip.rescaleImage010.argtypes = rescale_fn_arg_types image_manip.rescaleImage011.argtypes = rescale_fn_arg_types image_manip.rescaleImage100.argtypes = rescale_fn_arg_types
import os import platform import warnings import numpy as np import numpy.ctypeslib as npct from ctypes import c_int, c_uint, c_ulong, c_ulonglong, c_float, c_double, c_char, \ c_char_p, addressof, create_string_buffer, byref, POINTER, CDLL from ctypes.util import find_library import sys np_double_1D = npct.ndpointer(dtype=np.double, ndim=1, flags='CONTIGUOUS') np_float_1D = npct.ndpointer(dtype=np.float32, ndim=1, flags='CONTIGUOUS') np_int16_1D = npct.ndpointer(dtype=np.int16, ndim=1, flags='CONTIGUOUS') np_int8_1D = npct.ndpointer(dtype=np.int8, ndim=1, flags='CONTIGUOUS') np_uint64_1D = npct.ndpointer(dtype=np.uint64, ndim=1, flags='CONTIGUOUS') np_uint32_1D = npct.ndpointer(dtype=np.uint32, ndim=1, flags='CONTIGUOUS') np_uint16_1D = npct.ndpointer(dtype=np.uint16, ndim=1, flags='CONTIGUOUS') np_uint8_1D = npct.ndpointer(dtype=np.uint8, ndim=1, flags='CONTIGUOUS') # load the shared library # try with and without "lib" prefix libpath = find_library("aps2") if libpath is None: libpath = find_library("libaps2") # if we still can't find it, then look in python prefix (where conda stores binaries) if libpath is None: libpath = sys.prefix + '/lib' libaps2 = npct.load_library("libaps2", libpath) else: libaps2 = CDLL(libpath)
def __init__(self): if platform.system() == 'Windows': if struct.calcsize("P") * 8 == 64: dll_path = 'lib\\MLModule.dll' else: dll_path = 'lib\\MLModule32.dll' elif platform.system() == 'Darwin': dll_path = 'lib/libMLModule.dylib' else: dll_path = 'lib/libMLModule.so' full_path = pkg_resources.resource_filename(__name__, dll_path) if os.path.isfile(full_path): # for python we load dll by direct path but this dll may depend on other dlls and they will not be found! # to solve it we can load all of them before loading the main one or change PATH\LD_LIBRARY_PATH env var. # env variable looks better, since it can be done only once for all dependencies dir_path = os.path.abspath(os.path.dirname(full_path)) if platform.system() == 'Windows': os.environ['PATH'] = dir_path + os.pathsep + os.environ.get( 'PATH', '') else: os.environ[ 'LD_LIBRARY_PATH'] = dir_path + os.pathsep + os.environ.get( 'LD_LIBRARY_PATH', '') self.lib = ctypes.cdll.LoadLibrary(full_path) else: raise FileNotFoundError( 'Dynamic library %s is missed, did you forget to compile brainflow before installation of python package?' % full_path) self.set_log_level_ml_module = self.lib.set_log_level_ml_module self.set_log_level_ml_module.restype = ctypes.c_int self.set_log_level_ml_module.argtypes = [ctypes.c_int] self.set_log_file_ml_module = self.lib.set_log_file_ml_module self.set_log_file_ml_module.restype = ctypes.c_int self.set_log_file_ml_module.argtypes = [ctypes.c_char_p] self.prepare = self.lib.prepare self.prepare.restype = ctypes.c_int self.prepare.argtypes = [ctypes.c_char_p] self.release = self.lib.release self.release.restype = ctypes.c_int self.release.argtypes = [ctypes.c_char_p] self.release_all = self.lib.release_all self.release_all.restype = ctypes.c_int self.release_all.argtypes = [] self.predict = self.lib.predict self.predict.restype = ctypes.c_int self.predict.argtypes = [ ndpointer(ctypes.c_double), ctypes.c_int, ndpointer(ctypes.c_double), ctypes.c_char_p ] self.get_version_ml_module = self.lib.get_version_ml_module self.get_version_ml_module.restype = ctypes.c_int self.get_version_ml_module.argtypes = [ ndpointer(ctypes.c_ubyte), ndpointer(ctypes.c_int32), ctypes.c_int ]
def integrateLinearOrbit_c(pot, yo, t, int_method, rtol=None, atol=None, dt=None): """ NAME: integrateLinearOrbit_c PURPOSE: C integrate an ode for a LinearOrbit INPUT: pot - Potential or list of such instances yo - initial condition [q,p], can be [N,2] or [2] t - set of times at which one wants the result int_method= 'leapfrog_c', 'rk4_c', 'rk6_c', 'symplec4_c' rtol, atol dt= (None) force integrator to use this stepsize (default is to automatically determine one; only for C-based integrators) OUTPUT: (y,err) y : array, shape (N,len(t),2) or (len(y0),len(t)) if N=1 Array containing the value of y for each desired time in t, \ with the initial value y0 in the first row. err: error message, if not zero: 1 means maximum step reduction happened for adaptive integrators HISTORY: 2018-10-06 - Written - Bovy (UofT) 2018-10-14 - Adapted to allow multiple orbits to be integrated at once - Bovy (UofT) """ if len(yo.shape) == 1: single_obj = True else: single_obj = False yo = numpy.atleast_2d(yo) nobj = len(yo) rtol, atol = _parse_tol(rtol, atol) npot, pot_type, pot_args = _parse_pot(pot) int_method_c = _parse_integrator(int_method) if dt is None: dt = -9999.99 #Set up result array result = numpy.empty((nobj, len(t), 2)) err = numpy.zeros(nobj, dtype=numpy.int32) #Set up the C code ndarrayFlags = ('C_CONTIGUOUS', 'WRITEABLE') integrationFunc = _lib.integrateLinearOrbit integrationFunc.argtypes = [ ctypes.c_int, ndpointer(dtype=numpy.float64, flags=ndarrayFlags), ctypes.c_int, ndpointer(dtype=numpy.float64, flags=ndarrayFlags), ctypes.c_int, ndpointer(dtype=numpy.int32, flags=ndarrayFlags), ndpointer(dtype=numpy.float64, flags=ndarrayFlags), ctypes.c_double, ctypes.c_double, ctypes.c_double, ndpointer(dtype=numpy.float64, flags=ndarrayFlags), ndpointer(dtype=numpy.int32, flags=ndarrayFlags), ctypes.c_int ] #Array requirements, first store old order f_cont = [yo.flags['F_CONTIGUOUS'], t.flags['F_CONTIGUOUS']] yo = numpy.require(yo, dtype=numpy.float64, requirements=['C', 'W']) t = numpy.require(t, dtype=numpy.float64, requirements=['C', 'W']) result = numpy.require(result, dtype=numpy.float64, requirements=['C', 'W']) err = numpy.require(err, dtype=numpy.int32, requirements=['C', 'W']) #Run the C code integrationFunc(ctypes.c_int(nobj), yo, ctypes.c_int(len(t)), t, ctypes.c_int(npot), pot_type, pot_args, ctypes.c_double(dt), ctypes.c_double(rtol), ctypes.c_double(atol), result, err, ctypes.c_int(int_method_c)) if numpy.any(err == -10): #pragma: no cover raise KeyboardInterrupt( "Orbit integration interrupted by CTRL-C (SIGINT)") #Reset input arrays if f_cont[0]: yo = numpy.asfortranarray(yo) if f_cont[1]: t = numpy.asfortranarray(t) if single_obj: return (result[0], err[0]) else: return (result, err)
def conv_matmult_zono(man, destructive, element, start_offset, filter_weights, filter_bias, input_size, expr_offset, filter_size, num_filters, strides, output_size, pad_top, pad_left, has_bias): """ Convolutional Matrix multiplication Parameters ---------- man : ElinaManagerPtr Pointer to the ElinaManager. destructive: c_bool Boolean flag element : ElinaAbstract0Ptr Pointer to the ElinaAbstract0 which dimensions need to be assigned. start_offset: ElinaDim The start offset from which the dimensions should be assigned. filter_weights: POINTER(double) filter weights filter_bias: POINTER(double) filter biases input_size: POINTER(c_size_t) size of the input expr_offset: c_size_t the offset of the first variable in the assignment expression filter_size: POINTER(c_size_t) size of the filters num_filters: c_size_t number of filters strides: POINTER(c_size_t) size of the strides is_valid_padding: c_bool if the padding is valid has_bias: c_bool if the filter has bias Returns ------- res: ElinaAbstract0Ptr Pointer to the new abstract object """ try: conv_matmult_zono_c = zonoml_api.conv_matmult_zono conv_matmult_zono_c.restype = ElinaAbstract0Ptr conv_matmult_zono_c.argtypes = [ ElinaManagerPtr, c_bool, ElinaAbstract0Ptr, ElinaDim, ndpointer(ctypes.c_double), ndpointer(ctypes.c_double), POINTER(c_size_t), c_size_t, POINTER(c_size_t), c_size_t, POINTER(c_size_t), POINTER(c_size_t), c_size_t, c_size_t, c_bool ] res = conv_matmult_zono_c(man, destructive, element, start_offset, filter_weights, filter_bias, input_size, expr_offset, filter_size, num_filters, strides, output_size, pad_top, pad_left, has_bias) except Exception as inst: print( 'Problem with loading/calling "conv_matmult_zono" from "libzonoml.so"' ) print(inst) return res
#!/usr/bin/env python import numpy as np import scipy.linalg as LA import ctypes from numpy.ctypeslib import ndpointer import os #import the c function using ctypes WaveletLogLikelihood_C = ctypes.CDLL('{}/WaveletLikelihood.so'.format( os.path.dirname(__file__))).WaveletLikelihood_C #specify the argument and return types #double WaveletLikelihood_C(double* array, int size, double sig_w, double sig_r, double gamma, int verbose) WaveletLogLikelihood_C.argtypes = [ ndpointer(ctypes.c_double), ctypes.c_int, ctypes.c_double, ctypes.c_double, ctypes.c_double, ctypes.c_int ] WaveletLogLikelihood_C.restype = ctypes.c_double def Wavelet(yerr, theta): """ Special kernel for wavelet methods - identical to white noise with different attributes """ #Calculate distance matrix without scaling sig = theta[0] * yerr return sig**2
from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np import ctypes as ct import numpy.ctypeslib as npct __arr_double_1__ = npct.ndpointer(dtype=np.double, ndim=1, flags='CONTIGUOUS') __arr_uint32_1__ = npct.ndpointer(dtype=np.uint32, ndim=1, flags='CONTIGUOUS') import os __lib__ = npct.load_library("_matern.so", __file__) __lib__.SFieldCreate.restype = None __lib__.SFieldCreate.argtypes = [ ct.c_voidp, ct.c_int32, ct.c_double, ct.c_double, ct.c_uint32, ct.c_double, ct.c_double, ct.c_double, ct.c_double, ct.c_double, ct.c_double, __arr_double_1__, ct.c_double ] __lib__.SFieldBeginRuns.restype = None __lib__.SFieldBeginRuns.argtypes = [ct.c_voidp, ct.c_uint32, __arr_uint32_1__] __lib__.SFieldSolveFor.restype = ct.c_double __lib__.SFieldSolveFor.argtypes = [ct.c_voidp, __arr_double_1__, ct.c_uint32] __lib__.SFieldGetSolution.restype = None __lib__.SFieldGetSolution.argtypes = [ ct.c_voidp, __arr_double_1__, ct.c_uint32, __arr_double_1__, __arr_double_1__, ct.c_uint32 ]
def __init__(self, country, config_file, runtime_dir): """ Initializes an OpenALPR instance in memory. :param country: The default region for license plates. E.g., "us" or "eu" :param config_file: The path to the OpenALPR config file :param runtime_dir: The path to the OpenALPR runtime data directory :return: An OpenALPR instance """ country = _convert_to_charp(country) config_file = _convert_to_charp(config_file) runtime_dir = _convert_to_charp(runtime_dir) try: # Load the .dll for Windows and the .so for Unix-based if platform.system().lower().find("windows") != -1: self._openalprpy_lib = ctypes.cdll.LoadLibrary( "D:/Documents/Python/camera/openalpr_32/openalprpy.dll") elif platform.system().lower().find("darwin") != -1: self._openalprpy_lib = ctypes.cdll.LoadLibrary( "libopenalprpy.dylib") else: self._openalprpy_lib = ctypes.cdll.LoadLibrary( "libopenalprpy.so") except OSError as e: nex = OSError( "Unable to locate the OpenALPR library. Please make sure that OpenALPR is properly " "installed on your system and that the libraries are in the appropriate paths." ) if _PYTHON_3: nex.__cause__ = e raise nex self._initialize_func = self._openalprpy_lib.initialize self._initialize_func.restype = ctypes.c_void_p self._initialize_func.argtypes = [ ctypes.c_char_p, ctypes.c_char_p, ctypes.c_char_p ] self._dispose_func = self._openalprpy_lib.dispose self._dispose_func.argtypes = [ctypes.c_void_p] self._is_loaded_func = self._openalprpy_lib.isLoaded self._is_loaded_func.argtypes = [ctypes.c_void_p] self._is_loaded_func.restype = ctypes.c_bool self._recognize_file_func = self._openalprpy_lib.recognizeFile self._recognize_file_func.restype = ctypes.c_void_p self._recognize_file_func.argtypes = [ctypes.c_void_p, ctypes.c_char_p] self._recognize_array_func = self._openalprpy_lib.recognizeArray self._recognize_array_func.restype = ctypes.c_void_p self._recognize_array_func.argtypes = [ ctypes.c_void_p, ctypes.POINTER(ctypes.c_ubyte), ctypes.c_uint ] try: import numpy as np import numpy.ctypeslib as npct #self._recognize_raw_image_func = self._openalprpy_lib.recognizeRawImage #self._recognize_raw_image_func.restype = ctypes.c_void_p array_1_uint8 = npct.ndpointer(dtype=np.uint8, ndim=1, flags='CONTIGUOUS') #self._recognize_raw_image_func.argtypes = [ #ctypes.c_void_p, array_1_uint8, ctypes.c_uint, ctypes.c_uint, ctypes.c_uint] except ImportError: pass #self._recognize_raw_image_func = None self._free_json_mem_func = self._openalprpy_lib.freeJsonMem self._set_country_func = self._openalprpy_lib.setCountry self._set_country_func.argtypes = [ctypes.c_void_p, ctypes.c_char_p] self._set_prewarp_func = self._openalprpy_lib.setPrewarp self._set_prewarp_func.argtypes = [ctypes.c_void_p, ctypes.c_char_p] self._set_default_region_func = self._openalprpy_lib.setDefaultRegion self._set_default_region_func.argtypes = [ ctypes.c_void_p, ctypes.c_char_p ] self._set_detect_region_func = self._openalprpy_lib.setDetectRegion self._set_detect_region_func.argtypes = [ ctypes.c_void_p, ctypes.c_bool ] self._set_top_n_func = self._openalprpy_lib.setTopN self._set_top_n_func.argtypes = [ctypes.c_void_p, ctypes.c_int] self._get_version_func = self._openalprpy_lib.getVersion self._get_version_func.argtypes = [ctypes.c_void_p] self._get_version_func.restype = ctypes.c_void_p self.alpr_pointer = self._initialize_func(country, config_file, runtime_dir) self.loaded = True
# initialize dynamic library bbcomp = CDLL(dllname) bbcomp.configure.restype = c_int bbcomp.login.restype = c_int bbcomp.numberOfTracks.restype = c_int bbcomp.trackName.restype = c_char_p bbcomp.setTrack.restype = c_int bbcomp.numberOfProblems.restype = c_int bbcomp.setProblem.restype = c_int bbcomp.dimension.restype = c_int bbcomp.numberOfObjectives.restype = c_int bbcomp.budget.restype = c_int bbcomp.evaluations.restype = c_int bbcomp.evaluate.restype = c_int bbcomp.evaluate.argtypes = [ ndpointer(c_double, flags="C_CONTIGUOUS"), ndpointer(c_double, flags="C_CONTIGUOUS") ] bbcomp.history.restype = c_int bbcomp.history.argtypes = [ c_int, ndpointer(c_double, flags="C_CONTIGUOUS"), ndpointer(c_double, flags="C_CONTIGUOUS") ] bbcomp.errorMessage.restype = c_char_p print "----------------------------------------------" print "black box example competition client in Python" print "----------------------------------------------" print
def loadPupilFitC(): pupil_fit = loadclib.loadCLibrary("pupil_fit") # From sa_library/multi_fit.c pupil_fit.mFitGetFitImage.argtypes = [ctypes.c_void_p, ndpointer(dtype=numpy.float64)] pupil_fit.mFitGetNError.argtypes = [ctypes.c_void_p] pupil_fit.mFitGetNError.restype = ctypes.c_int pupil_fit.mFitGetPeakPropertyDouble.argtypes = [ctypes.c_void_p, ndpointer(dtype=numpy.float64), ctypes.c_char_p] pupil_fit.mFitGetPeakPropertyInt.argtypes = [ctypes.c_void_p, ndpointer(dtype=numpy.int32), ctypes.c_char_p] pupil_fit.mFitGetResidual.argtypes = [ctypes.c_void_p, ndpointer(dtype=numpy.float64)] pupil_fit.mFitGetUnconverged.argtypes = [ctypes.c_void_p] pupil_fit.mFitGetUnconverged.restype = ctypes.c_int pupil_fit.mFitIterateLM.argtypes = [ctypes.c_void_p] pupil_fit.mFitNewBackground.argtypes = [ctypes.c_void_p, ndpointer(dtype=numpy.float64)] pupil_fit.mFitNewImage.argtypes = [ctypes.c_void_p, ndpointer(dtype=numpy.float64), ctypes.c_int] pupil_fit.mFitRemoveErrorPeaks.argtypes = [ctypes.c_void_p] pupil_fit.mFitRemoveRunningPeaks.argtypes = [ctypes.c_void_p] pupil_fit.mFitSetPeakStatus.argtypes = [ctypes.c_void_p, ndpointer(dtype=numpy.int32)] # From pupilfn/pupil_fit.c pupil_fit.pfitCleanup.argtypes = [ctypes.c_void_p] pupil_fit.pfitInitialize.argtypes = [ctypes.c_void_p, ndpointer(dtype=numpy.float64), ndpointer(dtype=numpy.float64), ctypes.c_double, ctypes.c_int, ctypes.c_int] pupil_fit.pfitInitialize.restype = ctypes.POINTER(daoFitC.fitData) pupil_fit.pfitNewPeaks.argtypes = [ctypes.c_void_p, ndpointer(dtype=numpy.float64), ctypes.c_char_p, ctypes.c_int] pupil_fit.pfitSetZRange.argtypes = [ctypes.c_void_p, ctypes.c_double, ctypes.c_double] return pupil_fit
import numpy as np import numpy.ctypeslib as npct from ctypes import c_int, c_double matrix = npct.ndpointer(dtype=np.int32, ndim=2, flags='CONTIGUOUS') vector = npct.ndpointer(dtype=np.double, ndim=1, flags='CONTIGUOUS') libm = npct.load_library("libmetrics", ".") libm.mAP.restype = c_double libm.mAP.argtypes = [matrix, matrix, c_int, c_int, c_int, vector] libm.topK.restype = None libm.topK.argtypes = [matrix, matrix, c_int, c_int, c_int, vector, vector] def mAP(cateTrainTest, IX, topk=None): cateTrainTest = np.ascontiguousarray(cateTrainTest, np.int32) IX = np.ascontiguousarray(IX, np.int32) m, n = cateTrainTest.shape m, n = np.int32(m), np.int32(n) if topk is None: topk = m mAPs = np.zeros(n, dtype=np.float64) return libm.mAP(cateTrainTest, IX, topk, m, n, mAPs) def topK(cateTrainTest, IX, topk=500): cateTrainTest = np.ascontiguousarray(cateTrainTest, np.int32) IX = np.ascontiguousarray(IX, np.int32)
# by Aidan Macdonald # # from numpy import * from numpy.ctypeslib import ndpointer from time import sleep import ctypes, h5py f = h5py.File('transistor.h5', 'w') lib = ctypes.cdll.LoadLibrary('./transistor.so') evolve = lib.evolve evolve.restype = None evolve.argtypes = [ ndpointer(ctypes.c_double, flags="C_CONTIGUOUS"), ndpointer(ctypes.c_double, flags="C_CONTIGUOUS"), ctypes.c_int, ctypes.c_int, ctypes.c_double, ctypes.c_double, ctypes.c_double, ctypes.c_double, ctypes.c_double, ctypes.c_double, ctypes.c_double, ctypes.c_double, ctypes.c_int ] dx = 0.05 dt = dx**2 V0 = 10.0 width = 1.0 height = 0.2 p_mom = 5.0 x = arange(-10, 10, dx).reshape(-1, 1)
def actionAngleAdiabatic_c(pot, gamma, R, vR, vT, z, vz): """ NAME: actionAngleAdiabatic_c PURPOSE: Use C to calculate actions using the adiabatic approximation INPUT: pot - Potential or list of such instances gamma - as in Lz -> Lz+\gamma * J_z R, vR, vT, z, vz - coordinates (arrays) OUTPUT: (jr,jz,err) jr,jz : array, shape (len(R)) err - non-zero if error occured HISTORY: 2012-12-10 - Written - Bovy (IAS) """ #Parse the potential from galpy.orbit.integrateFullOrbit import _parse_pot npot, pot_type, pot_args = _parse_pot(pot, potforactions=True) #Set up result arrays jr = numpy.empty(len(R)) jz = numpy.empty(len(R)) err = ctypes.c_int(0) #Set up the C code ndarrayFlags = ('C_CONTIGUOUS', 'WRITEABLE') actionAngleAdiabatic_actionsFunc = _lib.actionAngleAdiabatic_actions actionAngleAdiabatic_actionsFunc.argtypes = [ ctypes.c_int, ndpointer(dtype=numpy.float64, flags=ndarrayFlags), ndpointer(dtype=numpy.float64, flags=ndarrayFlags), ndpointer(dtype=numpy.float64, flags=ndarrayFlags), ndpointer(dtype=numpy.float64, flags=ndarrayFlags), ndpointer(dtype=numpy.float64, flags=ndarrayFlags), ctypes.c_int, ndpointer(dtype=numpy.int32, flags=ndarrayFlags), ndpointer(dtype=numpy.float64, flags=ndarrayFlags), ctypes.c_double, ndpointer(dtype=numpy.float64, flags=ndarrayFlags), ndpointer(dtype=numpy.float64, flags=ndarrayFlags), ctypes.POINTER(ctypes.c_int) ] #Array requirements, first store old order f_cont = [ R.flags['F_CONTIGUOUS'], vR.flags['F_CONTIGUOUS'], vT.flags['F_CONTIGUOUS'], z.flags['F_CONTIGUOUS'], vz.flags['F_CONTIGUOUS'] ] R = numpy.require(R, dtype=numpy.float64, requirements=['C', 'W']) vR = numpy.require(vR, dtype=numpy.float64, requirements=['C', 'W']) vT = numpy.require(vT, dtype=numpy.float64, requirements=['C', 'W']) z = numpy.require(z, dtype=numpy.float64, requirements=['C', 'W']) vz = numpy.require(vz, dtype=numpy.float64, requirements=['C', 'W']) jr = numpy.require(jr, dtype=numpy.float64, requirements=['C', 'W']) jz = numpy.require(jz, dtype=numpy.float64, requirements=['C', 'W']) #Run the C code actionAngleAdiabatic_actionsFunc(len(R), R, vR, vT, z, vz, ctypes.c_int(npot), pot_type, pot_args, ctypes.c_double(gamma), jr, jz, ctypes.byref(err)) #Reset input arrays if f_cont[0]: R = numpy.asfortranarray(R) if f_cont[1]: vR = numpy.asfortranarray(vR) if f_cont[2]: vT = numpy.asfortranarray(vT) if f_cont[3]: z = numpy.asfortranarray(z) if f_cont[4]: vz = numpy.asfortranarray(vz) return (jr, jz, err.value)
from collections import defaultdict from .mimc import Bunch from scipy.linalg import solve __all__ = [] def public(sym): __all__.append(sym.__name__) return sym import os import ctypes as ct import numpy.ctypeslib as npct __lib__ = setutil.__lib__ #npct.load_library("libset_util", __file__) __lib__.sample_optimal_leg_pts.restype = np.uint32 __lib__.sample_optimal_leg_pts.argtypes = [npct.ndpointer(dtype=np.uint32, ndim=1, flags='CONTIGUOUS'), ct.c_uint32, ct.c_voidp, npct.ndpointer(dtype=np.double, ndim=1, flags='CONTIGUOUS'), ct.c_double, ct.c_double] __lib__.sample_optimal_random_leg_pts.restype = np.uint32 __lib__.sample_optimal_random_leg_pts.argtypes = [ct.c_uint32, npct.ndpointer(dtype=np.uint32, ndim=1, flags='CONTIGUOUS'), ct.c_uint32, ct.c_voidp, npct.ndpointer(dtype=np.double, ndim=1, flags='CONTIGUOUS'), ct.c_double, ct.c_double] __lib__.evaluate_legendre_basis.restype = None __lib__.evaluate_legendre_basis.argtypes = [ct.c_voidp, ct.c_uint32, ct.c_uint32,
""" Author: Nicolas Munnich License: GNU GPL2+ """ lib = ctypes.cdll.LoadLibrary(os.path.join(os.path.dirname(__file__), "linear.so")) gen_vert_bil = lib.create_weights interp_bil = lib.apply_weights bil_weight_extra_len = 3 # Setup C function calling gen_vert_bil.restype = None gen_vert_bil.argtypes = [ ndpointer(ctypes.c_float), # Current h array ctypes.c_ulonglong, # h array length ndpointer(ctypes.c_float), # 3D array describing heights at each point, dims z, y, x # 3D array has dimensions z, y, x ctypes.c_ulonglong, # len(y) * len(x) ctypes.c_ulonglong, # len(z) ndpointer(ctypes.c_float), # 4D array containing weights of shape z, y, x, w ] interp_bil.restype = None interp_bil.argtypes = [ ndpointer(ctypes.c_float), # 4D weight array z, y, x, w ndpointer(ctypes.c_float), # 3D original array h, y, x ndpointer(ctypes.c_float), # 3D target array z, y, x ctypes.c_ulonglong, # len(z) * len(y) * len(x) ]
libspecfunc.so needs to be in the same directory as this module! [*] if mpmath is used, this does analytical continuation for |z| > 1 I guess this could be relativley easily implemented also for the faster case... """ import numpy as np import numpy.ctypeslib as npct from ctypes import * import os import mpmath as mp array_1d_complex = npct.ndpointer(dtype=np.complex128, ndim=1, flags='CONTIGUOUS') class Complex(Structure): _fields_ = [("re", c_double), ("im", c_double)] class PrmsAndInfo(Structure): _fields_ = [("max_iter", c_int), ("tol", c_double), ("iters_needed", c_int), ("tol_achieved", c_double), ("prec_warning", c_int)] def cmpl(val): return Complex(c_double(val.real), c_double(val.imag))
def actionAngleFreqAngleStaeckel_c(pot, delta, R, vR, vT, z, vz, phi, u0=None, order=10): """ NAME: actionAngleFreqAngleStaeckel_c PURPOSE: Use C to calculate actions, frequencies, and angles using the Staeckel approximation INPUT: pot - Potential or list of such instances delta - focal length of prolate spheroidal coordinates R, vR, vT, z, vz, phi - coordinates (arrays) u0= (None) if set, u0 to use order= (10) order of Gauss-Legendre integration of the relevant integrals OUTPUT: (jr,jz,Omegar,Omegaphi,Omegaz,Angler,Anglephi,Anglez,err) jr,jz,Omegar,Omegaphi,Omegaz,Angler,Anglephi,Anglez : array, shape (len(R)) err - non-zero if error occured HISTORY: 2013-08-27 - Written - Bovy (IAS) """ if u0 is None: u0, dummy = bovy_coords.Rz_to_uv(R, z, delta=numpy.atleast_1d(delta)) #Parse the potential from ..orbit.integrateFullOrbit import _parse_pot npot, pot_type, pot_args = _parse_pot(pot, potforactions=True) #Parse delta delta = numpy.atleast_1d(delta) ndelta = len(delta) #Set up result arrays jr = numpy.empty(len(R)) jz = numpy.empty(len(R)) Omegar = numpy.empty(len(R)) Omegaphi = numpy.empty(len(R)) Omegaz = numpy.empty(len(R)) Angler = numpy.empty(len(R)) Anglephi = numpy.empty(len(R)) Anglez = numpy.empty(len(R)) err = ctypes.c_int(0) #Set up the C code ndarrayFlags = ('C_CONTIGUOUS', 'WRITEABLE') actionAngleStaeckel_actionsFunc = _lib.actionAngleStaeckel_actionsFreqsAngles actionAngleStaeckel_actionsFunc.argtypes = [ ctypes.c_int, ndpointer(dtype=numpy.float64, flags=ndarrayFlags), ndpointer(dtype=numpy.float64, flags=ndarrayFlags), ndpointer(dtype=numpy.float64, flags=ndarrayFlags), ndpointer(dtype=numpy.float64, flags=ndarrayFlags), ndpointer(dtype=numpy.float64, flags=ndarrayFlags), ndpointer(dtype=numpy.float64, flags=ndarrayFlags), ctypes.c_int, ndpointer(dtype=numpy.int32, flags=ndarrayFlags), ndpointer(dtype=numpy.float64, flags=ndarrayFlags), ctypes.c_int, ndpointer(dtype=numpy.float64, flags=ndarrayFlags), ctypes.c_int, ndpointer(dtype=numpy.float64, flags=ndarrayFlags), ndpointer(dtype=numpy.float64, flags=ndarrayFlags), ndpointer(dtype=numpy.float64, flags=ndarrayFlags), ndpointer(dtype=numpy.float64, flags=ndarrayFlags), ndpointer(dtype=numpy.float64, flags=ndarrayFlags), ndpointer(dtype=numpy.float64, flags=ndarrayFlags), ndpointer(dtype=numpy.float64, flags=ndarrayFlags), ndpointer(dtype=numpy.float64, flags=ndarrayFlags), ctypes.POINTER(ctypes.c_int) ] #Array requirements, first store old order f_cont = [ R.flags['F_CONTIGUOUS'], vR.flags['F_CONTIGUOUS'], vT.flags['F_CONTIGUOUS'], z.flags['F_CONTIGUOUS'], vz.flags['F_CONTIGUOUS'], u0.flags['F_CONTIGUOUS'], delta.flags['F_CONTIGUOUS'] ] R = numpy.require(R, dtype=numpy.float64, requirements=['C', 'W']) vR = numpy.require(vR, dtype=numpy.float64, requirements=['C', 'W']) vT = numpy.require(vT, dtype=numpy.float64, requirements=['C', 'W']) z = numpy.require(z, dtype=numpy.float64, requirements=['C', 'W']) vz = numpy.require(vz, dtype=numpy.float64, requirements=['C', 'W']) u0 = numpy.require(u0, dtype=numpy.float64, requirements=['C', 'W']) delta = numpy.require(delta, dtype=numpy.float64, requirements=['C', 'W']) jr = numpy.require(jr, dtype=numpy.float64, requirements=['C', 'W']) jz = numpy.require(jz, dtype=numpy.float64, requirements=['C', 'W']) Omegar = numpy.require(Omegar, dtype=numpy.float64, requirements=['C', 'W']) Omegaphi = numpy.require(Omegaphi, dtype=numpy.float64, requirements=['C', 'W']) Omegaz = numpy.require(Omegaz, dtype=numpy.float64, requirements=['C', 'W']) Angler = numpy.require(Angler, dtype=numpy.float64, requirements=['C', 'W']) Anglephi = numpy.require(Anglephi, dtype=numpy.float64, requirements=['C', 'W']) Anglez = numpy.require(Anglez, dtype=numpy.float64, requirements=['C', 'W']) #Run the C code actionAngleStaeckel_actionsFunc(len(R), R, vR, vT, z, vz, u0, ctypes.c_int(npot), pot_type, pot_args, ctypes.c_int(ndelta), delta, ctypes.c_int(order), jr, jz, Omegar, Omegaphi, Omegaz, Angler, Anglephi, Anglez, ctypes.byref(err)) #Reset input arrays if f_cont[0]: R = numpy.asfortranarray(R) if f_cont[1]: vR = numpy.asfortranarray(vR) if f_cont[2]: vT = numpy.asfortranarray(vT) if f_cont[3]: z = numpy.asfortranarray(z) if f_cont[4]: vz = numpy.asfortranarray(vz) if f_cont[5]: u0 = numpy.asfortranarray(u0) if f_cont[6]: delta = numpy.asfortranarray(delta) badAngle = Anglephi != 9999.99 Anglephi[badAngle] = (Anglephi[badAngle] + phi[badAngle] % (2. * numpy.pi)) % (2. * numpy.pi) Anglephi[Anglephi < 0.] += 2. * numpy.pi return (jr, jz, Omegar, Omegaphi, Omegaz, Angler, Anglephi, Anglez, err.value)
""" ctypes interface to ForwardPass and EvalSubsetsUsingXtx. """ import ctypes from numpy import ctypeslib import orange _c_orange_lib = ctypeslib.load_library(orange.__file__, "") _c_forward_pass_ = _c_orange_lib.EarthForwardPass _c_forward_pass_.argtypes = \ [ctypes.POINTER(ctypes.c_int), #pnTerms: ctypeslib.ndpointer(dtype=ctypes.c_bool, ndim=1), #FullSet ctypeslib.ndpointer(dtype=ctypes.c_double, ndim=2, flags="F_CONTIGUOUS"), #bx ctypeslib.ndpointer(dtype=ctypes.c_int, ndim=2, flags="F_CONTIGUOUS"), #Dirs ctypeslib.ndpointer(dtype=ctypes.c_double, ndim=2, flags="F_CONTIGUOUS"), #Cuts ctypeslib.ndpointer(dtype=ctypes.c_int, ndim=1), #nFactorsInTerms ctypeslib.ndpointer(dtype=ctypes.c_int, ndim=1), #nUses ctypeslib.ndpointer(dtype=ctypes.c_double, ndim=2, flags="F_CONTIGUOUS"), #x ctypeslib.ndpointer(dtype=ctypes.c_double, ndim=2, flags="F_CONTIGUOUS"), #y ctypeslib.ndpointer(dtype=ctypes.c_double, ndim=1), # Weights ctypes.c_int, #nCases ctypes.c_int, #nResp ctypes.c_int, #nPred ctypes.c_int, #nMaxDegree ctypes.c_int, #nMaxTerms ctypes.c_double, #Penalty ctypes.c_double, #Thresh
def __init__(self): self.userobjs = {} self.NONLIN_BLOCKS = 4 self.NUM_VV = 4 self.NUM_MM = 4 self.NONLIN_LINE = self.NUM_VV * self.NUM_MM * 2 self.MAX_NONLINBIT = 6 self.NONLIN_BLOCK_SIZE = (1<<(self.MAX_NONLINBIT+1)) self.NONLIN_SIZE = self.NONLIN_BLOCK_SIZE * self.NONLIN_LINE self.SFT_RELU = 0 self.SFT_SIGMOID = 1 self.SFT_NORELU = 2 self.SFT_TANH = 3 self.ie_create = f.ie_create self.ie_create.restype = c_void_p self.handle = f.ie_create() self.ie_loadmulti = f.ie_loadmulti self.ie_loadmulti.argtypes = [c_void_p, POINTER(c_char_p), c_int] self.ie_loadmulti.restype = c_void_p self.ie_compile_vfp = f.ie_compile_vfp self.ie_compile_vfp.argtypes = [c_void_p, c_char_p, c_char_p, c_char_p, POINTER(c_uint), POINTER(POINTER(c_uint)), POINTER(POINTER(POINTER(c_ulonglong))), POINTER(POINTER(c_float)), POINTER(c_ulonglong), c_uint] self.ie_compile_vfp.restype = c_void_p self.ie_compile = f.ie_compile self.ie_compile.argtypes = [c_void_p, c_char_p, c_char_p, c_char_p, POINTER(c_uint), POINTER(POINTER(c_uint)), POINTER(POINTER(POINTER(c_ulonglong)))] self.ie_compile.restype = c_void_p self.ie_init = f.ie_init self.ie_init.argtypes = [c_void_p, c_char_p, POINTER(c_uint), POINTER(POINTER(c_uint)), POINTER(POINTER(POINTER(c_ulonglong))), c_void_p] self.ie_init.restype = c_void_p self.ie_free = f.ie_free self.ie_free.argtypes = [c_void_p] self.ie_setflag = f.ie_setflag self.ie_setflag.argtypes = [c_void_p, c_char_p, c_void_p] self.ie_getinfo = f.ie_getinfo self.ie_getinfo.argtypes = [c_void_p, c_char_p, c_void_p, c_size_t] self.ie_run = f.ie_run self.ie_run.argtypes = [c_void_p, POINTER(POINTER(c_float)), POINTER(c_ulonglong), c_uint, POINTER(POINTER(c_float)), POINTER(c_ulonglong), c_uint] self.ie_putinput = f.ie_putinput self.ie_putinput.argtypes = [c_void_p, POINTER(POINTER(c_float)), POINTER(c_ulonglong), c_uint, c_void_p] self.ie_getresult = f.ie_getresult self.ie_getresult.argtypes = [c_void_p, POINTER(POINTER(c_float)), POINTER(c_ulonglong), c_uint, POINTER(c_void_p)] self.ie_read_data = f.ie_read_data self.ie_read_data.argtypes = [c_void_p, c_ulonglong, c_void_p, c_ulonglong, c_int] self.ie_write_data = f.ie_write_data self.ie_write_data.argtypes = [c_void_p, c_ulonglong, c_void_p, c_ulonglong, c_int] self.ie_write_weights = f.ie_write_weights self.ie_write_weights.argtypes = [c_void_p, ndpointer(c_float, flags="C_CONTIGUOUS"), ndpointer(c_float, flags="C_CONTIGUOUS"), c_int, c_int, c_int] self.ie_create_memcard = f.ie_create_memcard self.ie_create_memcard.argtypes = [c_void_p, c_int, c_int, c_char_p] self.ie_malloc = f.ie_malloc self.ie_malloc.argtypes = [c_void_p, c_ulonglong, c_int, c_int, c_char_p] self.ie_malloc.restype = c_ulonglong self.ie_get_nonlin_coefs = f.ie_get_nonlin_coefs self.ie_get_nonlin_coefs.argtypes = [c_void_p, c_int] self.ie_get_nonlin_coefs.restype = POINTER(c_short) self.ie_readcode = f.ie_readcode self.ie_readcode.argtypes = [c_void_p, c_char_p, c_ulonglong, POINTER(c_ulonglong)] self.ie_readcode.restype = POINTER(c_uint32) self.ie_hwrun = f.ie_hwrun self.ie_hwrun.argtypes = [c_void_p, c_ulonglong, POINTER(c_double), POINTER(c_double), c_int] self.ie_run_sw = f.ie_run_sw self.ie_run_sw.argtypes = [c_void_p, POINTER(POINTER(c_float)), POINTER(c_ulonglong), c_uint, POINTER(POINTER(c_float)), POINTER(c_ulonglong), c_uint] self.ie_run_thnets = f.ie_run_thnets self.ie_run_thnets.argtypes = [c_void_p, POINTER(POINTER(c_float)), POINTER(c_ulonglong), c_uint, POINTER(POINTER(c_float)), POINTER(c_ulonglong), c_uint] #Training of linear layer self.trainlinear_start = f.ie_trainlinear_start self.trainlinear_start.argtypes = [c_void_p, c_int, c_int, c_int, ndpointer(c_float, flags="C_CONTIGUOUS"), ndpointer(c_float, flags="C_CONTIGUOUS"), c_int, c_int, c_int, c_int, c_float] self.trainlinear_data = f.ie_trainlinear_data self.trainlinear_data.argtypes = [c_void_p, FloatNdPtr, FloatNdPtr, c_int] self.trainlinear_step_sw = f.ie_trainlinear_step_sw self.trainlinear_step_sw.argtypes = [c_void_p] self.trainlinear_step_float = f.ie_trainlinear_step_float self.trainlinear_step_float.argtypes = [c_void_p] self.trainlinear_step = f.ie_trainlinear_step self.trainlinear_step.argtypes = [c_void_p, c_int] self.trainlinear_get = f.ie_trainlinear_get self.trainlinear_get.argtypes = [c_void_p, ndpointer(c_float, flags="C_CONTIGUOUS"), ndpointer(c_float, flags="C_CONTIGUOUS")] self.trainlinear_getY = f.ie_trainlinear_getY self.trainlinear_getY.argtypes = [c_void_p, ndpointer(c_float, flags="C_CONTIGUOUS")] self.trainlinear_end = f.ie_trainlinear_end self.trainlinear_end.argtypes = [c_void_p] v = self.GetInfo('version') if v != curversion: print('Wrong libmicrondla.so found, expecting', curversion, 'and found', v, 'quitting') quit()
def loadDaoFitC(): daofit = loadclib.loadCLibrary("storm_analysis.sa_library", "dao_fit") # These are from sa_library/multi_fit.c daofit.mFitGetFitImage.argtypes = [ ctypes.c_void_p, ndpointer(dtype=numpy.float64) ] daofit.mFitGetNError.argtypes = [ctypes.c_void_p] daofit.mFitGetNError.restype = ctypes.c_int daofit.mFitGetPeakPropertyDouble.argtypes = [ ctypes.c_void_p, ndpointer(dtype=numpy.float64), ctypes.c_char_p ] daofit.mFitGetPeakPropertyInt.argtypes = [ ctypes.c_void_p, ndpointer(dtype=numpy.int32), ctypes.c_char_p ] daofit.mFitGetResidual.argtypes = [ ctypes.c_void_p, ndpointer(dtype=numpy.float64) ] daofit.mFitGetUnconverged.argtypes = [ctypes.c_void_p] daofit.mFitGetUnconverged.restype = ctypes.c_int daofit.mFitIterateLM.argtypes = [ctypes.c_void_p] daofit.mFitIterateOriginal.argtypes = [ctypes.c_void_p] daofit.mFitNewBackground.argtypes = [ ctypes.c_void_p, ndpointer(dtype=numpy.float64) ] daofit.mFitNewImage.argtypes = [ ctypes.c_void_p, ndpointer(dtype=numpy.float64) ] daofit.mFitRemoveErrorPeaks.argtypes = [ctypes.c_void_p] daofit.mFitRemoveRunningPeaks.argtypes = [ctypes.c_void_p] daofit.mFitSetPeakStatus.argtypes = [ ctypes.c_void_p, ndpointer(dtype=numpy.int32) ] # These are from sa_library/dao_fit.c daofit.daoCleanup.argtypes = [ctypes.c_void_p] daofit.daoInitialize.argtypes = [ ndpointer(dtype=numpy.float64), ndpointer(dtype=numpy.float64), ctypes.c_double, ctypes.c_int, ctypes.c_int, ctypes.c_int ] daofit.daoInitialize.restype = ctypes.POINTER(fitData) daofit.daoInitialize2DFixed.argtypes = [ctypes.c_void_p] daofit.daoInitialize2D.argtypes = [ctypes.c_void_p] daofit.daoInitialize3D.argtypes = [ctypes.c_void_p] daofit.daoInitializeZ.argtypes = [ctypes.c_void_p] daofit.daoInitializeZ.argtypes = [ ctypes.c_void_p, ndpointer(dtype=numpy.float64), ndpointer(dtype=numpy.float64), ctypes.c_double, ctypes.c_double ] daofit.daoNewPeaks.argtypes = [ ctypes.c_void_p, ndpointer(dtype=numpy.float64), ctypes.c_char_p, ctypes.c_int ] return daofit
1024) # resolution in direction [z, y, x] # pass the dynamic library lib = ctypes.CDLL('./libperlinNoise.dylib') # get the 2d Perlin noise function perlinNoise2D = lib.perlinNoise2D # Need specify the types of the argument for function perlinNoise2D perlinNoise2D.argtypes = (ctypes.c_int, ctypes.c_int, ctypes.c_int, ctypes.c_int) # This note is extremely useful to understand how to return a 2d array! # https://stackoverflow.com/questions/43013870/how-to-make-c-return-2d-array-to-python?noredirect=1&lq=1 # We can never pass a 2d array, therefore return 1d array in a C function perlinNoise2D.restype = ndpointer(dtype=ctypes.c_float, shape=(resolution.y, resolution.x)) result = perlinNoise2D(ctypes.c_int(lattice.x), ctypes.c_int(lattice.y), ctypes.c_int(resolution.x), ctypes.c_int(resolution.y)) plt.imshow(result, cmap='gray') plt.tight_layout() plt.savefig("noise2d.png") plt.show() result = octavePerlin2d((8, 16), (512, 1024), 4) plt.imshow(result, cmap='gray') plt.tight_layout() plt.savefig("octavenoise2d.png") plt.show()
resp_pair = np.zeros((K, K), order=order) marg_pr_seq = np.zeros((1, 1), order=order) # Execute C++ code (fills in outputs in-place) lib.FwdBwdAlg(initPi, transPi, SoftEv, resp, resp_pair, marg_pr_seq, K, T) return resp, resp_pair, marg_pr_seq libpath = os.path.dirname(os.path.abspath(__file__)) libfilename = 'libfwdbwdcpp.so' hasEigenLibReady = True try: lib = ctypes.cdll.LoadLibrary(os.path.join(libpath, libfilename)) lib.FwdBwdAlg.restype = None lib.FwdBwdAlg.argtypes = \ [ndpointer(ctypes.c_double), ndpointer(ctypes.c_double), ndpointer(ctypes.c_double), ndpointer(ctypes.c_double), ndpointer(ctypes.c_double), ndpointer(ctypes.c_double), ctypes.c_int, ctypes.c_int] except OSError: # No compiled C++ library exists print("Failed to Load Cpp Core") hasEigenLibReady = False raise