Пример #1
0
 def test_basic(self):
     try:
         # Should succeed
         load_library("multiarray", np.core.multiarray.__file__)
     except ImportError as e:
         msg = "ctypes is not available on this python: skipping the test" " (import error was: %s)" % str(e)
         print(msg)
Пример #2
0
 def test_basic2(self):
     # Regression for #801: load_library with a full library name
     # (including extension) does not work.
     try:
         try:
             so = get_shared_lib_extension(is_python_ext=True)
             # Should succeed
             load_library("multiarray%s" % so, np.core.multiarray.__file__)
         except ImportError:
             print("No distutils available, skipping test.")
     except ImportError as e:
         msg = "ctypes is not available on this python: skipping the test" " (import error was: %s)" % str(e)
         print(msg)
Пример #3
0
 def test_basic2(self):
     # Regression for #801: load_library with a full library name
     # (including extension) does not work.
     try:
         try:
             so = get_shared_lib_extension(is_python_ext=True)
             # Should succeed
             load_library('_multiarray_umath%s' % so, np.core._multiarray_umath.__file__)
         except ImportError:
             print("No distutils available, skipping test.")
     except ImportError as e:
         msg = ("ctypes is not available on this python: skipping the test"
                " (import error was: %s)" % str(e))
         print(msg)
Пример #4
0
def cblas_matmul(a, b, c):
    lib_cblas = npct.load_library(
        'libopenblasp-r0-2ecf47d5.3.7.dev.so',
        '/home/anton/anaconda3/lib/python3.6/site-packages/numpy/.libs',
    )
    lib_cblas.cblas_dgemm.argtypes = [
        c_int,
        c_int,
        c_int,
        c_int,
        c_int,
        c_int,
        c_double,
        array_2d_double_p,
        c_int,
        array_2d_double_p,
        c_int,
        c_double,
        array_2d_double_p,
        c_int,
    ]
    lib_cblas.cblas_dgemm.restype = None
    M = a.shape[0]
    N = b.shape[1]
    K = a.shape[1]
    lib_cblas.cblas_dgemm(101, 111, 111, M, N, K, c_double(1), a, K, b, N,
                          c_double(1), c, N)
Пример #5
0
def find_table_plane(pcd):
    lib = npct.load_library(
        "/home/weizhang/Documents/pcl_post_processing/table_finder/testlib",
        ".")
    array_1d_double = npct.ndpointer(dtype=np.double,
                                     ndim=1,
                                     flags='CONTIGUOUS')
    out = np.zeros((500000))
    pcd_arr = np.ones((pcd.shape[0] * 3))
    pcd_arr[0:pcd.shape[0]] = pcd[:, 0]
    pcd_arr[pcd.shape[0]:pcd.shape[0] * 2] = pcd[:, 1]
    pcd_arr[2 * pcd.shape[0]:3 * pcd.shape[0]] = pcd[:, 2]

    lib.add_one.restype = ctypes.c_int
    lib.add_one.argtypes = [
        array_1d_double, ctypes.c_int, ctypes.c_int, array_1d_double
    ]
    num_idx = lib.add_one(pcd_arr, pcd.shape[0], 3, out)

    res_out = np.zeros((num_idx, 3))
    res_out[:, 0] = out[0:num_idx]
    res_out[:, 1] = out[num_idx:2 * num_idx]
    res_out[:, 2] = out[2 * num_idx:3 * num_idx]

    return res_out
Пример #6
0
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
Пример #7
0
 def check_basic(self):
     try:
         cdll = load_library('multiarray',
                             np.core.multiarray.__file__)
     except ImportError, e:
         sys.stdout.write('S')
         sys.stdout.flush()
Пример #8
0
def channelcollisions(line, file=None):
    libname = 'libcoll.so'
    libdir = get_pwd()

    lib = ctl.load_library(libname, libdir)

    c_double_p = ctypes.POINTER(ctypes.c_double)
    c_int_p = ctypes.POINTER(ctypes.c_int)

    channelcollisions = lib.channelcollisions
    channelcollisions.argtypes = [
        ctl.ndpointer(np.float64, flags='aligned, c_contiguous'), c_int_p,
        c_int_p, c_double_p
    ]

    #channelcollisions(np.array([1,2,3,4,5,6], dtype=np.float64))

    data1 = (ctypes.c_int * 30)()
    data2 = (ctypes.c_int * 30)()
    data3 = (ctypes.c_double * 30)()

    res = channelcollisions(line.astype(np.float64),
                            ctypes.cast(data1, c_int_p),
                            ctypes.cast(data2, c_int_p),
                            ctypes.cast(data3, c_double_p))

    data1 = np.array(data1)
    data2 = np.array(data2)
    data3 = np.array(data3)

    hit_channels = data1[data1 != 0]
    miss_channels = data2[data2 != 0]
    track_lengths = data3[data3 != 0]

    return (list(hit_channels), list(miss_channels), track_lengths)
Пример #9
0
    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
Пример #10
0
def call_histogram_integer(arr1, arr2, size1, size2, size3, location):

    ##################
    # input type for the cos_doubles function
    # must be an integer array, with single dimension that is contiguous
    array_1d_int = npct.ndpointer(dtype=np.int64, ndim=1, flags='CONTIGUOUS')
    
    # check the existence of the library
    filename =  location+"/histogram_integer.so"
    status = os.path.isfile(filename)
    if not(status):
        print filename+' not found by call_histogram_integer'
        return -1
    
    # load the library, using numpy mechanisms
    libcd = npct.load_library("histogram_integer", location)

    # setup the return typs and argument types
    libcd.histogram_integer.restype = None
    libcd.histogram_integer.argtypes = [array_1d_int, array_1d_int, c_int, c_int, c_int,array_1d_int ]

    n_ri = (size1*size2+size3+1)
    ri = np.zeros(n_ri, dtype=np.int64)
    libcd.histogram_integer(arr1, arr2, size1, size2, size3, ri )
    return ri
Пример #11
0
def slowRotatorGtoC(hpMap, nside, verbose=True):

    if verbose: print("Upgrading map...")

    nsideUp = nside * 2

    hpUp = hp.ud_grade(hpMap, nsideUp)

    array_1d_double = npct.ndpointer(dtype=np.double,
                                     ndim=1,
                                     flags='C_CONTIGUOUS')
    libcd = npct.load_library(
        "/astro/u/msyriac/repos/orphics/orphics/tools/deg2hp.so", ".")

    libcd.RotateMapGtoC.restype = None
    libcd.RotateMapGtoC.argtypes = [
        array_1d_double, array_1d_double, ctypes.c_long
    ]

    retMap = hpUp.copy() * 0.
    if verbose: print("Rotating ...")
    ret = libcd.RotateMapGtoC(hpUp, retMap, nsideUp)

    if verbose: print("Downgrading map...")

    return hp.ud_grade(retMap, nside)
Пример #12
0
def idweight(npts, xp, zp, val, pw, n1, n2, dh):
    """
    voronoi
    Coarse inversion gird to fine modelling grid using
    Voronoi tesselation.
    """

    # GRD library
    path = os.path.abspath(__file__)
    dirpath = os.path.dirname(path)
    clibgrd = load_library('libgrd', dirpath)

    # nessi_grd_vrn
    clibgrd.nessi_grd_idw.argtypes = [
        c_int,
        ndpointer(dtype=float32, ndim=1, flags='C_CONTIGUOUS'),
        ndpointer(dtype=float32, ndim=1, flags='C_CONTIGUOUS'),
        ndpointer(dtype=float32, ndim=1, flags='C_CONTIGUOUS'), c_int, c_int,
        c_float, c_int,
        ndpointer(dtype=float32, ndim=2, flags='C_CONTIGUOUS')
    ]

    # initalize models array
    model = zeros((n1, n2), dtype=float32, order='C')

    # convert to C order
    xp = ascontiguousarray(xp, dtype=float32)
    zp = ascontiguousarray(zp, dtype=float32)
    val = ascontiguousarray(val, dtype=float32)

    # call nessi_grd_vrn
    clibgrd.nessi_grd_idw(npts, xp, zp, val, n1, n2, dh, pw, model)

    return model
Пример #13
0
def load_lib(path):
    lib = npct.load_library(path, '.')

    lib.SetData.argtypes = [
        c_void_p, array_2d_uint16, array_2d_double, array_2d_double, c_int,
        c_bool
    ]
    lib.SetBin.argtypes = [c_void_p, array_1d_uint16, array_1d_double]
    lib.SetGH.argtypes = [c_void_p, array_2d_double, array_2d_double]

    lib.Boost.argtypes = [c_void_p]
    lib.Train.argtypes = [c_void_p, c_int]
    lib.Dump.argtypes = [c_void_p, c_char_p]
    lib.Load.argtypes = [c_void_p, c_char_p]

    lib.MultiNew.argtypes = [
        c_int, c_int, c_int, c_char_p, c_int, c_int, c_int, c_int, c_int,
        c_double, c_double, c_double, c_double, c_double, c_int, c_bool,
        c_bool, c_int
    ]

    lib.SingleNew.argtypes = [
        c_int, c_char_p, c_int, c_int, c_int, c_int, c_int, c_double, c_double,
        c_double, c_double, c_double, c_int, c_bool, c_int
    ]

    lib.TrainMulti.argtypes = [c_void_p, c_int, c_int]
    lib.PredictMulti.argtypes = [
        c_void_p, array_2d_double, array_1d_double, c_int, c_int, c_int
    ]
    lib.Reset.argtypes = [c_void_p]

    return lib
Пример #14
0
    def be_ctc_cpu(self, inputs, labels, grads, label_lens, input_lens, costs,
                   nout):
        """
        Calling Warp-CTC
        """

        libpath = os.path.join(os.path.dirname(__file__), "libwarpctc.so")
        assert os.path.isfile(libpath), "libwarpctc.so not found.  Run make"
        self.ctclib = npct.load_library(libpath, "")

        self.ctclib.cpu_ctc.restype = None
        self.ctclib.cpu_ctc.argtypes = [
            npct.ndpointer(dtype=np.float32, ndim=3),
            npct.ndpointer(dtype=np.float32, ndim=3),
            npct.ndpointer(dtype=np.int32, ndim=1),
            npct.ndpointer(dtype=np.int32, ndim=1),
            npct.ndpointer(dtype=np.int32, ndim=1), ctypes.c_int, ctypes.c_int,
            npct.ndpointer(dtype=np.float32, ndim=1), ctypes.c_int
        ]

        num_threads = 8
        _inputs = np.array(inputs.get(), dtype=np.float32)
        _grads = np.array(grads.get(), dtype=np.float32)
        _labels = np.array(labels.get().ravel(), dtype=np.int32)
        _label_lens = np.array(label_lens.get().ravel(), dtype=np.int32)
        _input_lens = np.array(input_lens.get().ravel(), dtype=np.int32)
        _costs = np.array(costs.get().ravel(), dtype=np.float32)
        self.ctclib.cpu_ctc(_inputs, _grads, _labels, _label_lens, _input_lens,
                            nout, self.be.bsz, _costs, num_threads)
        costs[:] = _costs
        grads[:] = _grads
        return
Пример #15
0
def GenericDB(dbpath, refdir=None):
    import numpy.ctypeslib as npct
    import ctypes
    libdir = os.path.join(os.path.dirname(os.path.realpath(__file__)), "src")
    logger.debug("loading go libs from {0}".format(libdir))
    try:
        lib = npct.load_library("py_cc2ce", libdir)
    except OSError:
        logger.debug("didn't build the py_cc2ce.so library")
        # FIXME: make a user visible error message
        return None
    fun_o = lib.GETOPTS
    fun_o.restype = ctypes.c_char_p
    fun_o.argtypes = [ctypes.c_char_p]
    retval = fun_o(dbpath)

    fun_i = lib.GETINCS
    fun_i.restype = ctypes.c_char_p
    fun_i.argtypes = [ctypes.c_char_p]
    incdirs = [x for x in fun_i(dbpath).split(b" ")]

    for inc in incdirs:
        if inc == b"":
            continue
        if refdir is None:
            retval += b"-I" + inc + b" "
        else:
            juggel = os.path.relpath(inc, refdir)
            if juggel[0:2] == "..":
                retval += b"-isystem " + inc + b" "
            else:
                retval += b"-I" + inc + b" "

    logger.debug("returning {0}".format(retval))
    return retval.split(b" ")
Пример #16
0
def dgesv(N,A,B):
    A = np.asfortranarray(A.astype(np.float64))
    B = np.asfortranarray(B.astype(np.float64))
    
    cN=c_int(N)
    NRHS=c_int(1)
    LDA=c_int(N)
    IPIV=(c_int * N)()
    LDB=c_int(N)
    INFO=c_int(1)

    lapack=load_library('liblapack.so','/usr/lib/')

    lapack.dgesv_.argtypes=[POINTER(c_int),POINTER(c_int),
                            ndpointer(dtype=np.float64,
                            ndim=2,
                            flags='FORTRAN'),
                            POINTER(c_int), POINTER(c_int),
                     
                            ndpointer(dtype=np.float64,
                                      ndim=2,
                                      flags='FORTRAN'),
                            POINTER(c_int),POINTER(c_int)]
                     
                     
    lapack.dgesv_(cN,NRHS,A,LDA,IPIV,B,LDB,INFO)
    return B
Пример #17
0
 def test_basic(self):
     try:
         cdll = load_library('multiarray', np.core.multiarray.__file__)
     except ImportError as e:
         msg = "ctypes is not available on this python: skipping the test" \
               " (import error was: %s)" % str(e)
         print msg
Пример #18
0
    def be_ctc(
            self,
            nout,
            inputs,
            labels,
            grads,
            label_lens,
            input_lens,
            costs):

        libpath = os.path.join(os.path.dirname(__file__),
                               "..", "src", "transforms", "libwarpctc.so")
        assert os.path.isfile(libpath), "libwarpctc.so not found.  Run make"
        self.ctclib = npct.load_library(libpath, "")

        if self.be.backend_name == "gpu":
            self.be_ctc_gpu(
                nout,
                inputs,
                labels,
                grads,
                label_lens,
                input_lens,
                costs)
        elif self.be.backend_name == "cpu" or self.be.backend_name == "mkl":
            self.be_ctc_cpu(
                inputs,
                labels,
                grads,
                label_lens,
                input_lens,
                costs,
                nout)
        else:
            raise NotImplementedError()
 def __init__(self):
     src_file = 'utils.c'
     lib_file = 'utils.so'
     log_file = 'utils.log'
     c_compiler = GNUCompiler()
     c_compiler.compile(src_file, lib_file, log_file)
     self.lib = npct.load_library(lib_file, '.')
Пример #20
0
def sibson1(npts, xp, zp, val, n1, n2, dh):
    """
    voronoi
    Coarse inversion gird to fine modelling grid using
    Voronoi tesselation.
    """

    # GRD library
    clibgrd = load_library('libgrd', '/home/pageotd/Work/nessi/nessi/grd/')

    # nessi_grd_vrn
    clibgrd.nessi_grd_ds1.argtypes = [
        c_int,
        ndpointer(dtype=float32, ndim=1, flags='C_CONTIGUOUS'),
        ndpointer(dtype=float32, ndim=1, flags='C_CONTIGUOUS'),
        ndpointer(dtype=float32, ndim=1, flags='C_CONTIGUOUS'), c_int, c_int,
        c_float,
        ndpointer(dtype=float32, ndim=2, flags='C_CONTIGUOUS')
    ]

    # initalize models array
    model = zeros((n1, n2), dtype=float32, order='C')

    # convert to C order
    xp = ascontiguousarray(xp, dtype=float32)
    zp = ascontiguousarray(zp, dtype=float32)
    val = ascontiguousarray(val, dtype=float32)

    # call nessi_grd_vrn
    clibgrd.nessi_grd_ds1(npts, xp, zp, val, n1, n2, dh, model)

    return model
Пример #21
0
def init(directory, name):
    # Here we load the c library that will start the MPI processes
    # and interface directly with the rank 0 process of the MPI world.
    lib = ctl.load_library(name, directory)

    functions = {}

    # We need to load and configure the initialization function.
    configure = lib.configure

    # Specifies that the first (and only) argument is a (char *)
    configure.argtypes = [
        c_float, c_float, c_int,
        ctl.ndpointer(dtype=c_float), c_int, c_int
    ]

    functions['configure'] = configure
    functions['finish'] = lib.finish

    getRMSE = lib.getRMSE
    getRMSE.argtypes = [ctl.ndpointer(dtype=c_float)]
    getRMSE.restype = c_float

    functions['getRMSE'] = getRMSE

    return functions
Пример #22
0
def ctc_cpu(acts, lbls, utt_lens, lbl_lens, grads, costs, n_threads=8):
    basepath = os.path.join(os.path.dirname(__file__), "..", "..", "..")
    temp_loc = os.path.join("examples", "deepspeech", "src", "libwarpctc.so")
    libpath = os.path.join(basepath, temp_loc)
    assert os.path.isfile(libpath), (
        "Expected libwarpctc.so at {} but not found. "
        "Try running make").format(libpath)
    ctclib = npct.load_library(libpath, "")
    ctclib.compute_ctc_loss_cpu.restype = int
    ctclib.compute_ctc_loss_cpu.argtypes = [
        npct.ndpointer(dtype=np.float32, ndim=3),
        npct.ndpointer(dtype=np.float32, ndim=3),
        npct.ndpointer(dtype=np.int32, ndim=1),
        npct.ndpointer(dtype=np.int32, ndim=1),
        npct.ndpointer(dtype=np.int32, ndim=1), ct.c_int, ct.c_int,
        npct.ndpointer(dtype=np.float32, ndim=1), ct.c_int
    ]
    max_t, bsz, nout = acts.shape
    utt_lens = utt_lens * max_t / 100
    utt_lens = utt_lens.astype(np.int32)
    costs.fill(0.)
    grads.fill(0.)
    status = ctclib.compute_ctc_loss_cpu(acts, grads, lbls.astype(np.int32),
                                         lbl_lens.astype(np.int32),
                                         utt_lens.astype(np.int32), nout, bsz,
                                         costs, n_threads)
    assert status is 0, "warp-ctc run failed"
Пример #23
0
 def lib(self, compiler=GNUCompiler()):
     if self._lib is None:
         with open(self.src_file, 'w') as f:
             f.write(self.ccode)
         compiler.compile(self.src_file, self.lib_file, self.log_file)
         print("Compiled %s ==> %s" % ("random", self.lib_file))
         self._lib = npct.load_library(self.lib_file, '.')
     return self._lib
Пример #24
0
    def __init__(self, dbname, host, user, password):
        array_1d_double = npct.ndpointer(dtype=np.double,
                                         ndim=1,
                                         flags='CONTIGUOUS')

        self.libcd = npct.load_library(
            "cfsfdp",
            "/home/sergio/Proyectos/NeuroDB/NeuroDB/neurodb/cfunctions/cfsfdp")

        self.libcd.get_dc.argtypes = [
            ctypes.c_char_p, ctypes.c_char_p, ctypes.c_char_p, ctypes.c_float,
            ctypes.c_int
        ]
        self.libcd.get_dc.restype = ctypes.c_float

        self.libcd.cluster_dp.argtypes = [
            ctypes.c_char_p, ctypes.c_char_p, ctypes.c_char_p, array_1d_double,
            array_1d_double, array_1d_double, array_1d_double, array_1d_double,
            ctypes.c_float, ctypes.c_int, ctypes.c_char_p
        ]
        self.libcd.cluster_dp.restype = ctypes.c_int

        self.libcd.get_n_dbspikes.argtypes = [
            ctypes.c_char_p, ctypes.c_char_p, ctypes.c_char_p
        ]
        self.libcd.get_n_dbspikes.restype = ctypes.c_int

        self.libcd.get_clusters.argtypes = [
            ctypes.c_char_p, ctypes.c_char_p, ctypes.c_char_p, array_1d_double,
            array_1d_double, array_1d_double, array_1d_double, ctypes.c_int,
            ctypes.c_float
        ]
        self.libcd.get_clusters.restype = ctypes.c_int

        self.libcd.get_n_dbspikes.argtypes = [
            ctypes.c_char_p, ctypes.c_char_p, ctypes.c_char_p
        ]
        self.libcd.get_n_dbspikes.restype = ctypes.c_int

        self.connect = "dbname=%s host=%s user=%s password=%s" % (
            dbname, host, user, password)  #TODO Harcode

        #TODO path harcode
        self.libcd = npct.load_library(
            "cfsfdp",
            "/home/sergio/iibm/workspace/NeuroDB/NeuroDB/cfunctions/cfsfdp")
Пример #25
0
def findAndLoadLibray(libFiles, libname):

    for libFile in libFiles:
        if libname == libFile[1].split('.')[0]:
            return ctl.load_library(libFile[1], libFile[0])
        else:
            ValueError('Cannot find ' + libname +
                       ' libray. Make sure it is compiled.')
Пример #26
0
def load(basename, compiler):
    """Load a compiled library

    :param basename: Name of the .so file.
    :param compiler: The toolchain used for compilation.
    :return: The loaded library.
    """
    return npct.load_library(basename, '.')
Пример #27
0
 def lib(self, compiler=GNUCompiler()):
     if self._lib is None:
         with open(self.src_file, 'w') as f:
             f.write(self.ccode)
         compiler.compile(self.src_file, self.lib_file, self.log_file)
         print("Compiled %s ==> %s" % ("random", self.lib_file))
         self._lib = npct.load_library(self.lib_file, '.')
     return self._lib
Пример #28
0
 def test_basic(self):
     try:
         cdll = load_library('multiarray',
                             np.core.multiarray.__file__)
     except ImportError as e:
         msg = "ctypes is not available on this python: skipping the test" \
               " (import error was: %s)" % str(e)
         print msg
Пример #29
0
 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")
Пример #30
0
 def loadlib(self,libp):
     
     self.libcd = npct.load_library("calkel2", ".")
     array_1d_double = npct.ndpointer(dtype=np.float32, ndim=2, flags='CONTIGUOUS')
     array_1d_double2 = npct.ndpointer(dtype=np.float32, ndim=1, flags='CONTIGUOUS')
     self.libcd.cal.argtypes=[array_1d_double,array_1d_double,array_1d_double,array_1d_double,array_1d_double2,array_1d_double2,c_int,c_int,c_int,c_int,c_int,c_int,c_float,c_int]
     self.libcd.cal.restype=c_int
     pass
Пример #31
0
def chi2_dist(X, Y=None, K=None):
    if X.dtype == c_float:
        datatype = c_float
    else:
        datatype = c_double

    X = ascontiguousarray(X, datatype) # make array continguous
    n, xdim = X.shape
    if Y == None:
        m, ydim = n, xdim
    else:
        Y = ascontiguousarray(Y, datatype)
        m, ydim = Y.shape

    if xdim != ydim:
        print "Input dimension mismatch: %d != %d", (xdim, ydim)
        raise RuntimeError
    dim = xdim

    if (K==None):
        K = empty( (n, m), datatype)
    elif (K.shape != (n, m)):
        K = empty( (n, m), datatype)

    try:
        chi2lib = ctypeslib.load_library("libchi2.so", os.path.realpath(os.path.abspath(os.path.split(inspect.getfile( inspect.currentframe() ))[0]))) # adapt path to library location
    except:
        print "Unable to load chi2-library"
        raise RuntimeError

    if Y == None:
        if datatype == c_float:
            chi2_routine = chi2lib.chi2sym_distance_float
        else:
            chi2_routine = chi2lib.chi2sym_distance_double

        chi2_routine.restype = datatype
        chi2_routine.argtypes = [c_int, \
            c_int, ctypeslib.ndpointer(dtype=datatype, ndim=2, flags='C_CONTIGUOUS'), \
                   ctypeslib.ndpointer(dtype=datatype, ndim=2, flags='C_CONTIGUOUS') ]
        # TODO: is this change correct? dim was undefined, so i guess this
        # should be fine
        #meanK = chi2_routine(dim, n, X, K)
        meanK = chi2_routine(xdim, n, X, K)
    else:
        if datatype == c_float:
            chi2_routine = chi2lib.chi2_distance_float
        else:
            chi2_routine = chi2lib.chi2_distance_double

        chi2_routine.restype = datatype
        chi2_routine.argtypes = [c_int, \
            c_int, ctypeslib.ndpointer(dtype=datatype, ndim=2, flags='C_CONTIGUOUS'), \
            c_int, ctypeslib.ndpointer(dtype=datatype, ndim=2, flags='C_CONTIGUOUS'), \
                   ctypeslib.ndpointer(dtype=datatype, ndim=2, flags='C_CONTIGUOUS') ]
        meanK = chi2_routine(dim, n, X, m, Y, K)

    return K, meanK
Пример #32
0
def load(soname):
    """
    Load a compiled shared object.

    :param soname: Name of the .so file (w/o the suffix).

    :return: The loaded shared object.
    """
    return npct.load_library(str(get_jit_dir().joinpath(soname)), '.')
Пример #33
0
def fitness():
    libdir = get_root_dir() + "lib"
    libpython = load_library("libpython", libdir)
    type_array1d = ndpointer(dtype=np.float64, ndim=1, flags="C")
    type_array2d = ndpointer(dtype=np.float64, ndim=2, flags="C")
    functor = libpython.fitness
    functor.argtypes = ([type_array2d, c_int, c_int, type_array1d, c_int])
    functor.restype = c_double

    return functor
Пример #34
0
    def __init__(self):
        # load the library using numpy
        libm = npct.load_library('saxpy', './')

        # set the arguments and retun types
        arr_f4 = npct.ndpointer(ndim=1, dtype='f4')
        libm.saxpy.argtypes = [c_int, c_float, arr_f4, arr_f4]
        libm.saxpy.rettype = None

        # set public
        self.libm = libm
Пример #35
0
def load_lib(lib_path, lib_fname):
    """
    Load a shared library.
    
    Parameters
    ----------
    lib_path : str
        Absolute path of the shared library.
    
    lib_fname : str
        File name of the shared library.
        
    Returns
    -------
    """
    if platform.system() == 'Linux':
        c_lib = load_library(lib_fname + ".so", lib_path)
    elif platform.system() == 'Windows':
        c_lib = load_library(lib_fname + ".dll", lib_path)
    return c_lib
Пример #36
0
def chi2_dist(X,Y=None,K=None):
    if X.dtype==c_float:
       datatype=c_float
    else:
       datatype=c_double
    
    X = ascontiguousarray(X,datatype) # make array continguous
    n,xdim = X.shape
    if Y==None:
        m,ydim = n,xdim
    else:
        Y = ascontiguousarray(Y,datatype)
        m,ydim = Y.shape

    if xdim != ydim:
        print "Input dimension mismatch: %d != %d", (xdim, ydim)
        raise RuntimeError
    
    if (K==None):
        K = empty( (n,m), datatype)
    elif (K.shape != (n,m)):
        K = empty( (n,m), datatype)

    try:
        chi2lib = ctypeslib.load_library("libchi2.so",".") # adapt path to library location
    except:
        print "Unable to load chi2-library"
        raise RuntimeError
        
    if Y == None:
        if datatype==c_float:
            chi2_routine = chi2lib.chi2sym_distance_float
        else:
            chi2_routine = chi2lib.chi2sym_distance_double
    
        chi2_routine.restype = datatype
        chi2_routine.argtypes = [c_int, \
            c_int, ctypeslib.ndpointer(dtype=datatype, ndim=2, flags='C_CONTIGUOUS'), \
                   ctypeslib.ndpointer(dtype=datatype, ndim=2, flags='C_CONTIGUOUS') ]
        meanK = chi2_routine(dim, n, X, K)
    else:
        if datatype==c_float:
            chi2_routine = chi2lib.chi2_distance_float
        else:
            chi2_routine = chi2lib.chi2_distance_double
    
        chi2_routine.restype = datatype
        chi2_routine.argtypes = [c_int, \
            c_int, ctypeslib.ndpointer(dtype=datatype, ndim=2, flags='C_CONTIGUOUS'), \
            c_int, ctypeslib.ndpointer(dtype=datatype, ndim=2, flags='C_CONTIGUOUS'), \
                   ctypeslib.ndpointer(dtype=datatype, ndim=2, flags='C_CONTIGUOUS') ]
        meanK = chi2_routine(dim, n, X, m, Y, K)
    
    return K,meanK
Пример #37
0
def calculate_c4y():
    libdir = get_root_dir() + "lib"
    libpython = load_library("libpython", libdir)
    type_array2d = ndpointer(dtype=np.float64, ndim=2, flags="C")
    functor = libpython.calculate_c4y
    functor.argtypes = ([
        type_array2d, c_int, c_int, c_int, c_int, type_array2d
    ])
    functor.restype = None

    return functor
Пример #38
0
def load_PathfindingDLL():
    lib = npct.load_library("PathFindingDllforPython", r"DLL")
    lib.Estimate.argtypes = [
        npct.ndpointer(dtype=np.float32, ndim=1, flags="C_CONTIGUOUS"),
        npct.ndpointer(dtype=np.int,
                       ndim=2,
                       flags="C_CONTIGUOUS",
                       shape=(9, 9))
    ]
    print("Pathfinding_DLL已加载!")
    return lib.Estimate
Пример #39
0
    def __init__(self):
        # load the library using numpy
        libm = npct.load_library('saxpy', './')
        cfunc = getattr(libm, 'saxpy')

        # set the arguments and retun types
        arr_f4 = npct.ndpointer(ndim=1, dtype='f4')
        cfunc.argtypes = [c_int, c_float, arr_f4, arr_f4]
        cfunc.restype = None

        # set public
        self.cfunc = cfunc
Пример #40
0
    def __init__(self):
        # Load the library using numpy
        libm = npct.load_library('my_math', './')
        my_cos = getattr(libm, 'my_cos_')

        # Set the argument and return type
        my_cos.argtypes = [POINTER(c_double)]
        my_cos.restype = c_double

        # Set to public
        self.libm = libm
        self.my_cos = my_cos
Пример #41
0
    def be_ctc_gpu(self, nout, inputs, labels, grads, label_lens, input_lens,
                   costs, max_s, max_t):
        """
        Calling Warp-CTC
        """
        libpath = os.path.join(os.path.dirname(__file__), "..", "src",
                               "transforms", "libwarpctc.so")
        assert os.path.isfile(libpath), "libwarpctc.so not found.  Run make"
        self.ctclib = npct.load_library(libpath, "")

        # map first function to get workspace size
        self.ctclib.get_workspace_size_gpu.restype = int
        self.ctclib.get_workspace_size_gpu.argtypes = [
            ct.c_int, ct.c_int, ct.c_int, ct.c_int
        ]

        scratch_size = self.ctclib.get_workspace_size_gpu(
            max_s, max_t, nout, self.be.bsz)
        self.be.set_scratch_size(scratch_size)
        workspace = self.be.scratch_buffer(scratch_size)

        # map ctc function
        self.ctclib.compute_ctc_gpu.restype = int
        self.ctclib.compute_ctc_gpu.argtypes = [
            ct.POINTER(ct.c_float),
            ct.POINTER(ct.c_float),
            npct.ndpointer(dtype=np.int32, ndim=1),
            npct.ndpointer(dtype=np.int32, ndim=1),
            npct.ndpointer(dtype=np.int32, ndim=1), ct.c_int, ct.c_int,
            ct.POINTER(ct.c_float), ct.c_void_p,
            ct.POINTER(ct.c_char)
        ]

        inputs_buf = ct.cast(int(inputs.gpudata), ct.POINTER(ct.c_float))
        grads_buf = ct.cast(int(grads.gpudata), ct.POINTER(ct.c_float))
        costs_buf = ct.cast(int(costs.gpudata), ct.POINTER(ct.c_float))
        workspace_buf = ct.cast(workspace, ct.POINTER(ct.c_char))

        if self.be.stream is None:
            stream_buf = ct.cast(self.be.stream, ct.c_void_p)
        else:
            stream_buf = ct.cast(id(self.be.stream),
                                 ct.POINTER(ct.c_void_p)).contents

        status = self.ctclib.compute_ctc_gpu(
            inputs_buf, grads_buf,
            np.array(labels.get().ravel(), dtype=np.int32),
            np.array(label_lens.get().ravel(), dtype=np.int32),
            np.array(input_lens.get().ravel(), dtype=np.int32), nout,
            self.be.bsz, costs_buf, stream_buf, workspace_buf)

        assert status is 0, "Warp-CTC run failed"
        return
Пример #42
0
def _load_tipsy():
    """Load the tipsy module. For internal use only """
    if _load_tipsy.lib is not None:
        return _load_tipsy.lib
    
    lib = npct.load_library("libtipsy", "")
    
    def decode_err(err):
        if int(err) != 0:
            raise IOError(lib.tipsy_strerror(err).decode('utf-8'))
    
    # Force parameter type-checking and return-value error checking
    lib.tipsy_strerror.restype = ctypes.c_char_p
    lib.tipsy_strerror.argtypes = [ctypes.c_int]
    
    lib.tipsy_py_init_reader_native.restype = decode_err
    lib.tipsy_py_init_reader_native.argtypes = [ctypes.c_char_p]
    
    lib.tipsy_py_init_writer_native.restype = decode_err
    lib.tipsy_py_init_writer_native.argtypes = [ctypes.c_char_p, ctypes.c_char_p]
    
    lib.tipsy_py_destroy_native.restype = None
    lib.tipsy_py_destroy_native.argtypes = []
    
    lib.tipsy_py_read_header_native.restype = decode_err
    lib.tipsy_py_read_header_native.argtypes = [ctypes.POINTER(tipsy_c.header.struct)]

    lib.tipsy_py_read_gas_native.restype = decode_err
    lib.tipsy_py_read_gas_native.argtypes = [ctypes.POINTER(tipsy_c.header.struct),
                                             ctypes.POINTER(tipsy_c.gas_data.struct)]

    lib.tipsy_py_read_dark_native.restype = decode_err
    lib.tipsy_py_read_dark_native.argtypes = [ctypes.POINTER(tipsy_c.header.struct),
                                              ctypes.POINTER(tipsy_c.dark_data.struct)]
             
    lib.tipsy_py_read_star_native.restype = decode_err
    lib.tipsy_py_read_star_native.argtypes = [ctypes.POINTER(tipsy_c.header.struct),
                                              ctypes.POINTER(tipsy_c.star_data.struct)]

    lib.tipsy_py_write_header_native.restype = decode_err
    lib.tipsy_py_write_header_native.argtypes = [ctypes.POINTER(tipsy_c.header.struct)]

    lib.tipsy_py_write_gas_native.restype = decode_err
    lib.tipsy_py_write_gas_native.argtypes = [ctypes.POINTER(tipsy_c.gas_data.struct)]

    lib.tipsy_py_write_dark_native.restype = decode_err
    lib.tipsy_py_write_dark_native.argtypes = [ctypes.POINTER(tipsy_c.dark_data.struct)]
    
    lib.tipsy_py_write_star_native.restype = decode_err
    lib.tipsy_py_write_star_native.argtypes = [ctypes.POINTER(tipsy_c.star_data.struct)]
     
    _load_tipsy.lib = lib
    return lib
Пример #43
0
def load_DLL(libname, path):
    """ 
    Loads a model from a DLL file and returns it.
    
    The filepath can be be both with or without file suffixes (as long as 
    standard file suffixes are used, that is).
    
    Example inputs that should work:
      >> lib = loadDLL('model')
      >> lib = loadDLL('model.dll')
      >> lib = loadDLL('model.so')
    . All of the above should work on the JModelica supported platforms.
    However, the first one is recommended as it is the most platform independent 
    syntax.
    
    Parameters::
    
        libname -- 
            Name of the library without prefix.
            
        path -- 
            The relative or absolute path to the library.
    
    See also http://docs.python.org/library/ct.html
    """
    if sys.platform == 'win32':
        # Temporarily add the value of 'path' to system library path in case the dll 
        # is dependent on other dlls. In that case they should be located in 'path'.
        libpath = 'PATH'
        if os.environ.has_key(libpath):
            oldpath = os.environ[libpath]
        else:
            oldpath = None
        
        if oldpath is not None:
            newpath = path + os.pathsep + oldpath
        else:
            newpath = path
        os.environ[libpath] = newpath
    
    # Don't catch this exception since it hides the actual source
    # of the error.
    dll = Nct.load_library(libname, path)
    
    if sys.platform == 'win32':
        # Set back to the old path
        if oldpath is not None:
            os.environ[libpath] = oldpath
        else:
            del os.environ[libpath]
            
    return dll
Пример #44
0
def chi2_dist(X,Y=None,K=None):
    if X.dtype==c_float:
       datatype=c_float
    else:
       datatype=c_double
    
    X = array(X,datatype).copy() # make array continguous
    if Y==None:
        Y=X
    else:
        Y = array(Y,datatype).copy()
    
    n,dim = X.shape
    m,dim = Y.shape
    if (K==None):
        K = empty( (n,m), datatype)
    elif (K.shape != (n,m)):
        K = empty( (n,m), datatype)

    try:
        chi2lib = ctypeslib.load_library("libchi2.so",".") # adapt path to library location
    except:
        print "Unable to load chi2-library"
        raise RuntimeError
        
    if X==Y:
        if datatype==c_float:
            chi2_routine = chi2lib.chi2_distance_float
        else:
            chi2_routine = chi2lib.chi2_distance_double
    
        chi2_routine.restype = datatype
        chi2_routine.argtypes = [c_int, \
            c_int, ctypeslib.ndpointer(dtype=datatype, ndim=2, flags='C_CONTIGUOUS'), \
            c_int, ctypeslib.ndpointer(dtype=datatype, ndim=2, flags='C_CONTIGUOUS'), \
        ctypeslib.ndpointer(dtype=datatype, ndim=2, flags='C_CONTIGUOUS') ]
        meanK = chi2_routine(dim, n, X, m, Y, K)
    else:
        if datatype==c_float:
            chi2_routine = chi2lib.chi2sym_distance_float
        else:
            chi2_routine = chi2lib.chi2sym_distance_double
    
        chi2_routine.restype = datatype
        chi2_routine.argtypes = [c_int, \
            c_int, ctypeslib.ndpointer(dtype=datatype, ndim=2, flags='C_CONTIGUOUS'), \
        ctypeslib.ndpointer(dtype=datatype, ndim=2, flags='C_CONTIGUOUS') ]
        meanK = chi2_routine(dim, n, X, K)
    
    return K,meanK
Пример #45
0
    def test_basic2(self):
        """Regression for #801: load_library with a full library name
        (including extension) does not work."""
        try:
            try:
                from distutils import sysconfig

                so = sysconfig.get_config_var("SO")
                cdll = load_library("multiarray%s" % so, np.core.multiarray.__file__)
            except ImportError:
                print "No distutils available, skipping test."
        except ImportError, e:
            msg = "ctypes is not available on this python: skipping the test" " (import error was: %s)" % str(e)
            print msg
Пример #46
0
 def test_basic2(self):
     """Regression for #801: load_library with a full library name
     (including extension) does not work."""
     try:
         try:
             so = get_shared_lib_extension(is_python_ext=True)
             cdll = load_library('multiarray%s' % so,
                                 np.core.multiarray.__file__)
         except ImportError:
             print "No distutils available, skipping test."
     except ImportError as e:
         msg = "ctypes is not available on this python: skipping the test" \
               " (import error was: %s)" % str(e)
         print msg
Пример #47
0
    def __init__(self):
        # Load the library using numpy
        libm = npct.load_library('saxpy', './')

        # Set the argument and return type
        c_int_p = POINTER(c_int)
        c_float_p = POINTER(c_float)

        arr_1d_f4 = npct.ndpointer(ndim=1, dtype='f4')
        libm.saxpy_.argtypes = (c_int_p, c_float_p, arr_1d_f4, arr_1d_f4)
        libm.saxpy_.restype = None

        # Set to public
        self.libm = libm
Пример #48
0
def _load_fast3tree_lib(dim):
    mytype = np.dtype([('idx', np.int64), ('pos', _float_dtype, dim)], align=True)
    mytype_ctype =  C.ndpointer(mytype, ndim=1, flags='C,A')
    center_ctype = C.ndpointer(dtype=_float_dtype, ndim=1, shape=(dim,), flags='C,A')
    box_ctype = C.ndpointer(dtype=_float_dtype, ndim=2, shape=(2,dim), flags='C,A')
    tree_ptr_ptr = C.ndpointer(dtype=_ptr_dtype, ndim=1, shape=(1,), flags='C,A')

    c_lib = C.load_library('fast3tree_%dd'%(dim), __path__[0])

    c_lib.fast3tree_init.restype = _ptr_ctype
    c_lib.fast3tree_init.argtypes = [C.ctypes.c_int64, mytype_ctype]

    c_lib.fast3tree_rebuild.restype = None
    c_lib.fast3tree_rebuild.argtypes = [_ptr_ctype, C.ctypes.c_int64, mytype_ctype]

    c_lib.fast3tree_maxmin_rebuild.restype = None
    c_lib.fast3tree_maxmin_rebuild.argtypes = [_ptr_ctype]

    c_lib.fast3tree_free.restype = None
    c_lib.fast3tree_free.argtypes = [tree_ptr_ptr]

    c_lib.fast3tree_results_init.restype = _ptr_ctype
    c_lib.fast3tree_results_init.argtypes = None

    c_lib.fast3tree_find_sphere.restype = None
    c_lib.fast3tree_find_sphere.argtypes = [_ptr_ctype, _ptr_ctype, center_ctype, _float_ctype]

    c_lib.fast3tree_find_sphere_periodic.restype = C.ctypes.c_int
    c_lib.fast3tree_find_sphere_periodic.argtypes = [_ptr_ctype, _ptr_ctype, center_ctype, _float_ctype]

    c_lib.fast3tree_find_inside_of_box.restype = None
    c_lib.fast3tree_find_inside_of_box.argtypes = [_ptr_ctype, _ptr_ctype, box_ctype]

    c_lib.fast3tree_find_outside_of_box.restype = None
    c_lib.fast3tree_find_outside_of_box.argtypes = [_ptr_ctype, _ptr_ctype, box_ctype]

    c_lib.fast3tree_results_clear.restype = None
    c_lib.fast3tree_results_clear.argtypes = [_ptr_ctype]

    c_lib.fast3tree_results_free.restype = None
    c_lib.fast3tree_results_free.argtypes = [_ptr_ctype]

    c_lib.fast3tree_set_minmax.restype = None
    c_lib.fast3tree_set_minmax.argtypes = [_ptr_ctype, _float_ctype, _float_ctype]

    c_lib.fast3tree_find_next_closest_distance.restype = _float_ctype
    c_lib.fast3tree_find_next_closest_distance.argtypes = [_ptr_ctype, _ptr_ctype, center_ctype]

    return c_lib, mytype
Пример #49
0
 def check_basic2(self):
     """Regression for #801: load_library with a full library name
     (including extension) does not work."""
     try:
         try:
             from distutils import sysconfig
             so = sysconfig.get_config_var('SO')
             cdll = load_library('multiarray%s' % so,
                                 np.core.multiarray.__file__)
         except ImportError:
             sys.stdout.write('S')
             sys.stdout.flush()
     except ImportError, e:
         sys.stdout.write('S')
         sys.stdout.flush()
Пример #50
0
def load(soname):
    """
    Load a compiled shared object.

    Parameters
    ----------
    soname : str
        Name of the .so file (w/o the suffix).

    Returns
    -------
    obj
        The loaded shared object.
    """
    return npct.load_library(str(get_jit_dir().joinpath(soname)), '.')
Пример #51
0
def subwindow_search_pyramid(numpoints, width, height, xpos, ypos, clstid, numbins, numlevels, weights):
    """Subwindow search for best box with bag-of-words histogram with a spatial 
       pyramid kernel."""
    pyramidlib = load_library("libess.so",".")

    pyramidlib.pyramid_search.restype = Box_struct
    pyramidlib.pyramid_search.argtypes = [c_int,c_int,c_int,        
            ndpointer(dtype=c_double, ndim=1, flags='C_CONTIGUOUS'),
            ndpointer(dtype=c_double, ndim=1, flags='C_CONTIGUOUS'),
            ndpointer(dtype=c_double, ndim=1, flags='C_CONTIGUOUS'),
            c_int, c_int,                                           
            ndpointer(dtype=c_double, ndim=1, flags='C_CONTIGUOUS')]

    box = pyramidlib.pyramid_search(numpoints, width, height, 
                      xpos, ypos, clstid, numbins, numlevels, weights)
    return box
Пример #52
0
def ratemap(x, fs, lowcf=50.0, highcf=3500.0, numchans=32, frameshift=10.0,
            ti=8.0, compression='cuberoot'):
    """
    Python wrapper for ratemap.c
    %  ratemap = ratemap(x,fs,lowcf,highcf,numchans,frameshift,ti,compression)
    %
    %  x           input signal
    %  fs          sampling frequency in Hz
    %  lowcf       centre frequency of lowest filter in Hz (50)
    %  highcf      centre frequency of highest filter in Hz (3500)
    %  numchans    number of channels in filterbank (32)
    %  frameshift  interval between successive frames in ms (10)
    %  ti          temporal integration in ms (8)
    %  compression type of compression ['cuberoot','log','none'] ('cuberoot')
    """

    numsamples = len(x)
    xarray_type = ndpointer(float, flags='aligned, contiguous')
    oarray_type = ndpointer(float, ndim=2, flags='aligned, contiguous, writeable')
    carray_type = ctypes.c_char * len(compression)

    frameshift_samples = get_round(frameshift * float(fs) / 1000)
    numframes = int(math.ceil(numsamples / float(frameshift_samples)))

    x = require(x, float, ['CONTIGUOUS', 'ALIGNED'])
    result = empty((numframes, numchans), dtype=float)

    program_dirname = os.path.dirname(os.path.realpath(__file__))
    _libratemap = load_library('libratemap', program_dirname)
    _libratemap.ratemap.argtypes = (
        xarray_type, ctypes.c_int, ctypes.c_int, ctypes.c_double, ctypes.c_double,
        ctypes.c_int, ctypes.c_double, ctypes.c_double, ctypes.POINTER(ctypes.c_char), oarray_type)

    _libratemap.ratemap.restype = None

    _libratemap.ratemap(x, ctypes.c_int(numsamples), ctypes.c_int(fs),
                        ctypes.c_double(lowcf), ctypes.c_double(highcf), ctypes.c_int(numchans),
                        ctypes.c_double(frameshift),
                        ctypes.c_double(ti), carray_type(*compression), result)

    return result
Пример #53
0
def gammatone(x, fs, cf, hrect=False):
    """
    Python wrapper for gammatone.c
    %  bm, env, instp, instf = gammatone_c(x, fs, cf, hrect)
    %
    %  x     - input signal
    %  fs    - sampling frequency (Hz)
    %  cf    - centre frequency of the filter (Hz)
    %  hrect - half-wave rectifying if hrect = True (default False)
    %
    %  bm    - basilar membrane displacement
    %  env   - instantaneous envelope
    %  instp - instantaneous phase (unwrapped radian)
    %  instf - instantaneous frequency (Hz)
    """

    numsamples = len(x)
    xarray_type = ndpointer(float, flags='aligned, contiguous')
    oarray_type = ndpointer(float, flags='aligned, contiguous, writeable')

    x = require(x, float, ['CONTIGUOUS', 'ALIGNED'])
    bm = empty_like(x)
    env = empty_like(x)
    instp = empty_like(x)
    instf = empty_like(x)

    program_dirname = os.path.dirname(os.path.realpath(__file__))
    _libratemap = load_library('libratemap', program_dirname)
    _libratemap.gammatone.argtypes = (
        xarray_type, ctypes.c_int,
        ctypes.c_int, ctypes.c_double, ctypes.c_int,
        oarray_type, oarray_type,
        oarray_type, oarray_type)

    _libratemap.gammatone.restype = None

    _libratemap.gammatone(x, ctypes.c_int(numsamples),
                          ctypes.c_int(fs), ctypes.c_double(cf), ctypes.c_int(hrect),
                          bm, env, instp, instf)

    return bm, env, instp, instf
Пример #54
0
    def __init__(self, nx, ny):
        self.nx = nx
        self.ny = ny

        # Load the library using numpy
        libm = npct.load_library('my_math', './')

        # Set the argument and return type
        f1d = npct.ndpointer(ndim=1, dtype='f8')
        libm.my_cos.argtypes = [c_int, f1d, f1d]
        libm.my_cos.restype = None

        libm.my_cos_2d.argtypes = [c_int, c_int, f1d, f1d]
        libm.my_cos_2d.restype = None

        pp = npct.ndpointer(ndim=1, dtype=np.uintp, flags='C')
        libm.my_cos_2d_2ptr.argtypes = [c_int, c_int, pp, pp]
        libm.my_cos_2d_2ptr.restype = None

        # Set public
        self.libm = libm
Пример #55
0
def static_symbol(module, method, lib, bindc=False):
    """Returns the symbol for the specified *fortran* module and subroutine/function
    that has been compiled into a shared library.

    :arg lib: the full path to the shared library *.so file.
    """
    from os import path
    from numpy.ctypeslib import load_library
    libpath = path.abspath(lib)
    libkey = libpath.lower()

    if libkey not in compilers:
        compilers[libkey] = detect_compiler(libpath)
        if compilers[libkey] == False:
            raise ValueError("Couldn't auto-detect the compiler for {}".format(libpath))
    compiler = compilers[libkey]

    if libkey not in libs:
        libs[libkey] = load_library(libpath, "")
        if not libs[libkey]:
            raise ValueError("Couldn't auto-load the shared library with ctypes.")
    slib = libs[libkey]
    
    identifier = "{}.{}".format(module, method)
    if bindc:
        symbol = method
    elif compiler == "gfortran":
        symbol = "__" + identifier.lower().replace(".", "_MOD_")
    else:
        #We assume the only other option is ifort.
        symbol = identifier.lower().replace(".", "_mp_") + "_"

    if hasattr(slib, symbol):
        return getattr(slib, symbol)
    else:
        return None
Пример #56
0
from __future__ import division, absolute_import, print_function

import sys

import numpy as np
from numpy.ctypeslib import ndpointer, load_library
from numpy.distutils.misc_util import get_shared_lib_extension
from numpy.testing import *

try:
    cdll = load_library('multiarray', np.core.multiarray.__file__)
    _HAS_CTYPE = True
except (ImportError, OSError):
    _HAS_CTYPE = False

class TestLoadLibrary(TestCase):
    @dec.skipif(not _HAS_CTYPE, "ctypes not available on this python installation")
    @dec.knownfailureif(sys.platform=='cygwin', "This test is known to fail on cygwin")
    def test_basic(self):
        try:
            cdll = load_library('multiarray',
                                np.core.multiarray.__file__)
        except ImportError as e:
            msg = "ctypes is not available on this python: skipping the test" \
                  " (import error was: %s)" % str(e)
            print(msg)

    @dec.skipif(not _HAS_CTYPE, "ctypes not available on this python installation")
    @dec.knownfailureif(sys.platform=='cygwin', "This test is known to fail on cygwin")
    def test_basic2(self):
        """Regression for #801: load_library with a full library name
""" Example of wrapping a C library function that accepts a C double array as
    input using the numpy.ctypeslib. """

import numpy as np
import numpy.ctypeslib as npct
from ctypes import c_int

# input type for the cos_doubles function
# must be a double array, with single dimension that is contiguous
array_1d_double = npct.ndpointer(dtype=np.double, ndim=1, flags='CONTIGUOUS')

# load the library, using numpy mechanisms
libcd = npct.load_library("libcos_doubles", ".")

# setup the return typs and argument types
libcd.cos_doubles.restype = None
libcd.cos_doubles.argtypes = [array_1d_double, array_1d_double, c_int]


def cos_doubles_func(in_array, out_array):
    return libcd.cos_doubles(in_array, out_array, len(in_array))
Пример #58
0
progress_func = ct.CFUNCTYPE(
    ct.c_int,                   # return value
    ct.c_voidp,                 # instance
    ct.POINTER(ct.c_double),    # *x
    ct.POINTER(ct.c_double),    # *g
    ct.c_double,                # fx
    ct.c_double,                # xnorm
    ct.c_double,                # gnorm
    ct.c_double,                # step
    ct.c_int,                   # n
    ct.c_int,                   # k
    ct.c_int                    # ls
)


liblbfgs = npct.load_library('liblbfgs', os.path.join(os.path.dirname(__file__), 'liblbfgs/lib/.libs'))
liblbfgs.lbfgs.restype = ct.c_int
liblbfgs.lbfgs.argtypes = [
    ct.c_int,                   # n
    array_1d_double,            # *x
    ct.POINTER(ct.c_double),    # *fx
    ct.c_voidp,                 # proc_evaluate
    ct.c_voidp,                 # proc_progress
    ct.c_voidp,                 # *instance
    ct.POINTER(LBFGSParameter)  # *param
]


liblbfgs.lbfgs_parameter_init.restype = ct.c_voidp
liblbfgs.lbfgs_parameter_init.argtypes = [
    ct.POINTER(LBFGSParameter)
Пример #59
0
import os.path
import numpy as np
from numpy.ctypeslib import load_library, ndpointer
import ctypes

# Type aliases
_float1d = ndpointer(ctypes.c_double, ndim=1, flags='CONTIGUOUS')
_float2d = ndpointer(ctypes.c_double, ndim=2, flags='CONTIGUOUS')
_uint2d = ndpointer(ctypes.c_size_t, ndim=2, flags='CONTIGUOUS')
_byte2d = ndpointer(ctypes.c_uint8, ndim=2, flags='CONTIGUOUS')

_visual_lib = load_library(
    'visual',
    os.path.dirname(__file__)
)

visualize = _visual_lib.visualize
visualize.restype = None
visualize.argtypes = [
    ctypes.c_size_t,
    ctypes.c_size_t,
    _float2d,
    _float2d,
    _uint2d,
    _float1d,
    _float1d,
    _byte2d,
    _byte2d,
    _byte2d,
    _byte2d,
    _byte2d,
Пример #60
0
import numpy.ctypeslib as npct
from ctypes import c_int
from ctypes import c_uint
from ctypes import c_double
from sys import platform as platform
import os
import hv
from hv import HyperVolume
##########################################################################
# define input/output type
array_1d_double = npct.ndpointer(dtype=np.double, flags='C_CONTIGUOUS')
array_1d_bool = npct.ndpointer(dtype=np.bool,  flags='C_CONTIGUOUS')
##########################################################################
# load the libraries, using numpy mechanisms : use the name *.so
if platform == "darwin":
	libeps = npct.load_library("libeps", ".")
	libpf  = npct.load_library("libpf",".")
	libhv  = npct.load_library("libhv",".")
	libgd  = npct.load_library("libgd",".")
else:
	libeps = npct.load_library("libeps.so", ".") 
	libpf  = npct.load_library("libpf.so",".")
	libhv  = npct.load_library("libhv.so",".")
	libgd  = npct.load_library("libgd.so",".")
##########################################################################	
# define the arg and res type for each of the functions:
# 1. epsilon library
libeps.eps.restype = c_double
libeps.eps.argtypes = [array_1d_double, array_1d_double, c_int, c_int, c_int]
libeps.incr_eps.restype = None
libeps.incr_eps.argtypes = [array_1d_double,array_1d_double, array_1d_double, c_int, c_int, c_int]