Python ctypes.c_double() Examples

The following are 30 code examples of ctypes.c_double(). These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module ctypes , or try the search function .
Example #1
Source Project: dynamic-training-with-apache-mxnet-on-aws   Author: awslabs   File: opencv.py    License: Apache License 2.0 6 votes vote down vote up
def copyMakeBorder(src, top, bot, left, right, border_type=cv2.BORDER_CONSTANT, value=0):
    """Pad image border
    Wrapper for cv2.copyMakeBorder that uses mx.nd.NDArray

    Parameters
    ----------
    src : NDArray
        Image in (width, height, channels).
        Others are the same with cv2.copyMakeBorder

    Returns
    -------
    img : NDArray
        padded image
    """
    hdl = NDArrayHandle()
    check_call(_LIB.MXCVcopyMakeBorder(src.handle, ctypes.c_int(top), ctypes.c_int(bot),
                                       ctypes.c_int(left), ctypes.c_int(right),
                                       ctypes.c_int(border_type), ctypes.c_double(value),
                                       ctypes.byref(hdl)))
    return mx.nd.NDArray(hdl) 
Example #2
Source Project: contextualbandits   Author: david-cortes   File: online.py    License: BSD 2-Clause "Simplified" License 6 votes vote down vote up
def _score_matrix(self, X):
        if self.explore_cnt < self.explore_rounds:
            self.explore_cnt += X.shape[0]

            # case 1: all predictions are within allowance
            if self.explore_cnt <= self.explore_rounds:
                scores = self.random_state.random(size=(X.shape[0], self.nchoices))
                self._choose_active(X, scores, choose=False)
            
            # case 2: some predictions are within allowance, others are not
            else:
                scores = np.empty((X.shape[0], self.nchoices), type = ctypes.c_double)
                scores[:n_explore] = self.random_state.random(size=(n_explore, self.nchoices))
                self._choose_active(X[:n_explore], scores[:n_explore], choose=False)
                scores[n_explore:] = self._oracles.decision_function(X[n_explore:])
            
        else:
            scores = self._oracles.decision_function(X)

        return scores 
Example #3
Source Project: contextualbandits   Author: david-cortes   File: utils.py    License: BSD 2-Clause "Simplified" License 6 votes vote down vote up
def fit(self, X, y):
        if X.shape[0] == 0:
            return self
        elif np.unique(y).shape[0] <= 1:
            self.update_aux(y)
            return self

        seed = self.random_state.integers(np.iinfo(np.int32).max)
        self.model.set_params(random_state = seed)
        self.model.fit(X, y)
        n_nodes = self.model.tree_.node_count
        self.pos = np.zeros(n_nodes, dtype=ctypes.c_long)
        self.neg = np.zeros(n_nodes, dtype=ctypes.c_long)
        pred_node = self.model.apply(X).astype(ctypes.c_long)
        _create_node_counters(self.pos, self.neg, pred_node, y.astype(ctypes.c_double))
        self.pos = self.pos.astype(ctypes.c_double) + self.beta_prior[0]
        self.neg = self.neg.astype(ctypes.c_double) + self.beta_prior[1]

        self.is_fitted = True
        return self 
Example #4
Source Project: pyscf   Author: pyscf   File: test_libxc.py    License: Apache License 2.0 6 votes vote down vote up
def test_libxc_cam_beta_bug(self):
        '''As a detector for libxc-3.0.0. libxc-3.0.1 fixed this bug
        '''
        import ctypes
        rsh_tmp = (ctypes.c_double*3)()
        dft.libxc._itrf.LIBXC_rsh_coeff(1, rsh_tmp)
        beta = rsh_tmp[2]
        self.assertEqual(beta, 0)

        dft.libxc._itrf.LIBXC_rsh_coeff(433, rsh_tmp)
        dft.libxc._itrf.LIBXC_rsh_coeff(1, rsh_tmp)
        beta = rsh_tmp[2]
        self.assertEqual(beta, 0) # libxc-3.0.0 produces -0.46

        dft.libxc._itrf.LIBXC_is_hybrid(1)
        dft.libxc._itrf.LIBXC_rsh_coeff(1, rsh_tmp)
        beta = rsh_tmp[2]
        self.assertEqual(beta, 0) 
Example #5
Source Project: pyscf   Author: pyscf   File: selected_ci.py    License: Apache License 2.0 6 votes vote down vote up
def select_strs(myci, eri, eri_pq_max, civec_max, strs, norb, nelec):
    strs = numpy.asarray(strs, dtype=numpy.int64)
    nstrs = len(strs)
    nvir = norb - nelec
    strs_add = numpy.empty((nstrs*(nelec*nvir)**2//4), dtype=numpy.int64)
    libfci.SCIselect_strs.restype = ctypes.c_int
    nadd = libfci.SCIselect_strs(strs_add.ctypes.data_as(ctypes.c_void_p),
                                 strs.ctypes.data_as(ctypes.c_void_p),
                                 eri.ctypes.data_as(ctypes.c_void_p),
                                 eri_pq_max.ctypes.data_as(ctypes.c_void_p),
                                 civec_max.ctypes.data_as(ctypes.c_void_p),
                                 ctypes.c_double(myci.select_cutoff),
                                 ctypes.c_int(norb), ctypes.c_int(nelec),
                                 ctypes.c_int(nstrs))
    strs_add = sorted(set(strs_add[:nadd]) - set(strs))
    return numpy.asarray(strs_add, dtype=numpy.int64) 
Example #6
Source Project: pyscf   Author: pyscf   File: m_rsphar_libnao.py    License: Apache License 2.0 6 votes vote down vote up
def rsphar(r,lmax,res):
  """
    Computes (all) real spherical harmonics up to the angular momentum lmax
    Args:
      r : Cartesian coordinates defining correct theta and phi angles for spherical harmonic
      lmax : Integer, maximal angular momentum
    Result:
      1-d numpy array of float64 elements with all spherical harmonics stored in order 0,0; 1,-1; 1,0; 1,+1 ... lmax,lmax, althogether 0 : (lmax+1)**2 elements.
  """
  assert r.shape[-1]==3
  
  r_cp = np.require(r,  dtype=float, requirements='C')
  res = np.require(res,  dtype=float, requirements='CW')
  
  libnao.rsphar(r_cp.ctypes.data_as(POINTER(c_double)), c_int64(lmax), res.ctypes.data_as(POINTER(c_double)))
  return 0

#
#
# 
Example #7
Source Project: pyscf   Author: pyscf   File: m_rsphar_libnao.py    License: Apache License 2.0 6 votes vote down vote up
def rsphar_vec(rvs,lmax):
  """
    Computes (all) real spherical harmonics up to the angular momentum lmax
    Args:
      rvs : Cartesian coordinates defining correct theta and phi angles for spherical harmonic
      lmax : Integer, maximal angular momentum
    Result:
      1-d numpy array of float64 elements with all spherical harmonics stored in order 0,0; 1,-1; 1,0; 1,+1 ... lmax,lmax, althogether 0 : (lmax+1)**2 elements.
  """
  assert rvs.shape[-1]==3
  r_cp = np.require(rvs,  dtype=float, requirements='C')
  nc = len(rvs)
  res = np.require( np.zeros((nc, (lmax+1)**2)), dtype=float, requirements='CW')
  libnao.rsphar_vec(r_cp.ctypes.data_as(POINTER(c_double)), c_int64(nc), c_int64(lmax), res.ctypes.data_as(POINTER(c_double)))
  
  #for irv,rvec in enumerate(rvs): rsphar(rvec,lmax,res[irv,:])
  return res

#
#
# 
Example #8
Source Project: pyscf   Author: pyscf   File: m_rsphar_libnao.py    License: Apache License 2.0 6 votes vote down vote up
def rsphar_exp_vec(rvs,lmax):
  """
    Computes (all) real spherical harmonics up to the angular momentum lmax
    Args:
      rvs : Cartesian coordinates defining correct theta and phi angles for spherical harmonic
      lmax : Integer, maximal angular momentum
    Result:
      1-d numpy array of float64 elements with all spherical harmonics stored in order 0,0; 1,-1; 1,0; 1,+1 ... lmax,lmax, althogether 0 : (lmax+1)**2 elements.
  """  
  assert rvs.shape[0]==3
  r_cp = np.require(rvs,  dtype=np.float64, requirements='C')
  nc = rvs[0,...].size
  res = np.require( np.zeros(((lmax+1)**2,nc)), dtype=np.float64, requirements='CW')
  libnao.rsphar_exp_vec(r_cp.ctypes.data_as(POINTER(c_double)), c_int64(nc), c_int64(lmax), res.ctypes.data_as(POINTER(c_double)))
  
  #for irv,rvec in enumerate(rvs): rsphar(rvec,lmax,res[irv,:])
  return res 
Example #9
Source Project: pyscf   Author: pyscf   File: nao.py    License: Apache License 2.0 6 votes vote down vote up
def init_libnao_orbs(self):
    """ Initialization of data on libnao site """
    from pyscf.nao.m_libnao import libnao
    from pyscf.nao.m_sv_chain_data import sv_chain_data
    from ctypes import POINTER, c_double, c_int64, c_int32, byref
    data = sv_chain_data(self)
    size_x = np.array([1,self.nspin,self.norbs,self.norbs,1], dtype=np.int32)
    libnao.init_sv_libnao_orbs.argtypes = (POINTER(c_double), POINTER(c_int64), POINTER(c_int32))
    libnao.init_sv_libnao_orbs(data.ctypes.data_as(POINTER(c_double)), c_int64(len(data)), size_x.ctypes.data_as(POINTER(c_int32)))
    self.init_sv_libnao_orbs = True

    libnao.init_aos_libnao.argtypes = (POINTER(c_int64), POINTER(c_int64))
    info = c_int64(-999)
    libnao.init_aos_libnao(c_int64(self.norbs), byref(info))
    if info.value!=0: raise RuntimeError("info!=0")
    return self 
Example #10
Source Project: pyscf   Author: pyscf   File: m_comp_spatial_distributions.py    License: Apache License 2.0 6 votes vote down vote up
def comp_induce_potential(self):
        """
            Compute the induce potential corresponding to the density change
            calculated in get_spatial_density
        """

        from scipy.signal import convolve

        Nx, Ny, Nz = self.mesh[0].size, self.mesh[1].size, self.mesh[2].size

        grid = np.zeros((Nx, Ny, Nz), dtype = np.float64)
        factor = self.dr[0]*self.dr[1]*self.dr[2]/(np.sqrt(2*np.pi)**3)

        libnao.comp_spatial_grid_pot(
            self.dr.ctypes.data_as(POINTER(c_double)), 
            self.mesh[0].ctypes.data_as(POINTER(c_double)),
            self.mesh[1].ctypes.data_as(POINTER(c_double)),
            self.mesh[2].ctypes.data_as(POINTER(c_double)),
            grid.ctypes.data_as(POINTER(c_double)),
            c_int(Nx), c_int(Ny), c_int(Nz))

        return convolve(grid, self.dn_spatial, mode="same", method="fft")*factor 
Example #11
Source Project: pyscf   Author: pyscf   File: m_blas_wrapper.py    License: Apache License 2.0 6 votes vote down vote up
def spmv_wrapper(n, alpha, ap, x, beta = 0.0, incx = 1, incy = 1, lower=0):
  """ Small blas wrapper that is missing in scipy.linalg.blas in scipy.version<=1 """

  if ap.size != n*(n+1)//2:
    raise ValueError("simple wrapper, you MUST provide x.size = n, ap.size = n*(n+1)/2")
    
  if ap.dtype == np.float32:
    y = np.zeros((n), dtype=np.float32)
    libsparsetools.SSPMV_wrapper(c_int(lower), c_int(n), c_float(alpha),
                ap.ctypes.data_as(POINTER(c_float)),
                x.ctypes.data_as(POINTER(c_float)), c_int(incx), c_float(beta),
                y.ctypes.data_as(POINTER(c_float)), c_int(incy))
  elif ap.dtype == np.float64:
    y = np.zeros((n), dtype=np.float64)
    libsparsetools.DSPMV_wrapper(c_int(lower), c_int(n), c_double(alpha),
                ap.ctypes.data_as(POINTER(c_double)),
                x.ctypes.data_as(POINTER(c_double)), c_int(incx), c_double(beta),
                y.ctypes.data_as(POINTER(c_double)), c_int(incy))
  else:
    raise ValueError("dtype error, only np.float32 and np.float64 implemented")

  return y 
Example #12
Source Project: pyscf   Author: pyscf   File: m_dens_libnao.py    License: Apache License 2.0 6 votes vote down vote up
def dens_libnao(crds, nspin):
  """  Compute the electronic density using library call """
  assert crds.ndim==2  
  assert crds.shape[-1]==3
  
  nc = crds.shape[0]
  crds_cp = require(crds, dtype=c_double, requirements='C')
  dens = require( zeros((nc, nspin)), dtype=c_double, requirements='CW')

  libnao.dens_libnao(
    crds_cp.ctypes.data_as(POINTER(c_double)),
    c_int64(nc),
    dens.ctypes.data_as(POINTER(c_double)),
    c_int64(nspin))

  return dens 
Example #13
Source Project: pyscf   Author: pyscf   File: m_prod_basis_obsolete.py    License: Apache License 2.0 6 votes vote down vote up
def init_prod_basis_pp(self, sv, **kvargs):
    """ Talman's procedure should be working well with Pseudo-Potential starting point."""
    from pyscf.nao.m_prod_biloc import prod_biloc_c

    #t1 = timer()    
    self.init_inp_param_prod_log_dp(sv, **kvargs)
    data = self.chain_data()
    libnao.init_vrtx_cc_apair(data.ctypes.data_as(POINTER(c_double)), c_int64(len(data)))
    self.sv_pbloc_data = True
    
    #t2 = timer(); print(t2-t1); t1=timer();
    self.bp2info = [] # going to be some information including indices of atoms, list of contributing centres, conversion coefficients
    for ia1 in range(sv.natoms):
      rc1 = sv.ao_log.sp2rcut[sv.atom2sp[ia1]]
      for ia2 in range(ia1+1,sv.natoms):
        rc2,dist = sv.ao_log.sp2rcut[sv.atom2sp[ia2]], sqrt(((sv.atom2coord[ia1]-sv.atom2coord[ia2])**2).sum())
        if dist>rc1+rc2 : continue
        pbiloc = self.comp_apair_pp_libint(ia1,ia2)
        if pbiloc is not None : self.bp2info.append(pbiloc)
    
    self.dpc2s,self.dpc2t,self.dpc2sp = self.init_c2s_domiprod() # dominant product's counting
    self.npdp = self.dpc2s[-1]
    self.norbs = self.sv.norbs
    return self 
Example #14
Source Project: pyscf   Author: pyscf   File: m_thrj.py    License: Apache License 2.0 6 votes vote down vote up
def thrj_nobuf(l1,l2,l3,m1,m2,m3):
  """ Wigner3j symbol without buffer. Written by James Talman. """
  from pyscf.nao.m_libnao import libnao
  from ctypes import POINTER, c_double, c_int, byref

  libnao.thrj_subr.argtypes = (
    POINTER(c_int),  # l1
    POINTER(c_int),  # l2
    POINTER(c_int),  # l3
    POINTER(c_int),  # m1
    POINTER(c_int),  # m2
    POINTER(c_int),  # m3 
   POINTER(c_double))  # thrj

  aa = c_double()
  libnao.thrj_subr( c_int(l1),c_int(l2),c_int(l3),c_int(m1),c_int(m2),c_int(m3), byref(aa)) # call library function
  return aa.value 
Example #15
Source Project: pyscf   Author: pyscf   File: prod_basis.py    License: Apache License 2.0 6 votes vote down vote up
def init_prod_basis_pp(self, sv, **kvargs):
    """ Talman's procedure should be working well with Pseudo-Potential starting point."""
    from pyscf.nao.m_prod_biloc import prod_biloc_c

    #t1 = timer()    
    self.init_inp_param_prod_log_dp(sv, **kvargs)
    data = self.chain_data()
    libnao.init_vrtx_cc_apair(data.ctypes.data_as(POINTER(c_double)), c_int64(len(data)))
    self.sv_pbloc_data = True
    
    #t2 = timer(); print(t2-t1); t1=timer();
    self.bp2info = [] # going to be some information including indices of atoms, list of contributing centres, conversion coefficients
    for ia1 in range(sv.natoms):
      rc1 = sv.ao_log.sp2rcut[sv.atom2sp[ia1]]
      for ia2 in range(ia1+1,sv.natoms):
        rc2,dist = sv.ao_log.sp2rcut[sv.atom2sp[ia2]], sqrt(((sv.atom2coord[ia1]-sv.atom2coord[ia2])**2).sum())
        if dist>rc1+rc2 : continue
        pbiloc = self.comp_apair_pp_libint(ia1,ia2)
        if pbiloc is not None : self.bp2info.append(pbiloc)
    
    self.dpc2s,self.dpc2t,self.dpc2sp = self.init_c2s_domiprod() # dominant product's counting
    self.npdp = self.dpc2s[-1]
    self.norbs = self.sv.norbs
    return self 
Example #16
Source Project: pyscf   Author: pyscf   File: m_comp_vext_tem.py    License: Apache License 2.0 6 votes vote down vote up
def comp_vext_tem(self, ao_log=None, numba_parallel=True):
    """
        Compute the external potential created by a moving charge
        using the fortran routine
    """

    Vfreq_real = np.zeros((self.freq.size, self.nprod), dtype=np.float64)
    Vfreq_imag = np.zeros((self.freq.size, self.nprod), dtype=np.float64)
    ub = find_nearrest_index(self.freq_symm, self.freq[0])

    libnao.comp_vext_tem(self.time.ctypes.data_as(POINTER(c_double)),
                        self.freq_symm.ctypes.data_as(POINTER(c_double)),
                        c_int(self.time.size), c_int(self.freq.size), 
                        c_int(ub), c_int(self.nprod), 
                        c_double(self.vnorm),
                        self.vdir.ctypes.data_as(POINTER(c_double)),
                        self.beam_offset.ctypes.data_as(POINTER(c_double)),
                        Vfreq_real.ctypes.data_as(POINTER(c_double)),
                        Vfreq_imag.ctypes.data_as(POINTER(c_double)),
                        )

    return Vfreq_real + 1.0j*Vfreq_imag 
Example #17
Source Project: pyscf   Author: pyscf   File: m_aos_libnao.py    License: Apache License 2.0 6 votes vote down vote up
def aos_libnao(coords, norbs):
  assert len(coords.shape) == 2
  assert coords.shape[1] == 3
  assert norbs>0

  ncoords = coords.shape[0]
  co2val = np.require( np.zeros((ncoords,norbs)), dtype=c_double, requirements='CW')
  crd_copy = np.require(coords, dtype=c_double, requirements='C')

  libnao.aos_libnao(
    c_int64(ncoords),
    crd_copy.ctypes.data_as(POINTER(c_double)),
    c_int64(norbs),
    co2val.ctypes.data_as(POINTER(c_double)),
    c_int64(norbs))

  return co2val 
Example #18
Source Project: pyscf   Author: pyscf   File: numpy_helper.py    License: Apache License 2.0 6 votes vote down vote up
def _dgemm(trans_a, trans_b, m, n, k, a, b, c, alpha=1, beta=0,
           offseta=0, offsetb=0, offsetc=0):
    if a.size == 0 or b.size == 0:
        if beta == 0:
            c[:] = 0
        else:
            c[:] *= beta
        return c

    assert(a.flags.c_contiguous)
    assert(b.flags.c_contiguous)
    assert(c.flags.c_contiguous)

    _np_helper.NPdgemm(ctypes.c_char(trans_b.encode('ascii')),
                       ctypes.c_char(trans_a.encode('ascii')),
                       ctypes.c_int(n), ctypes.c_int(m), ctypes.c_int(k),
                       ctypes.c_int(b.shape[1]), ctypes.c_int(a.shape[1]),
                       ctypes.c_int(c.shape[1]),
                       ctypes.c_int(offsetb), ctypes.c_int(offseta),
                       ctypes.c_int(offsetc),
                       b.ctypes.data_as(ctypes.c_void_p),
                       a.ctypes.data_as(ctypes.c_void_p),
                       c.ctypes.data_as(ctypes.c_void_p),
                       ctypes.c_double(alpha), ctypes.c_double(beta))
    return c 
Example #19
Source Project: pyscf   Author: pyscf   File: test_ecp.py    License: Apache License 2.0 6 votes vote down vote up
def test_type2_rad_part(self):
        rc = .8712
        rs, ws = radi.gauss_chebyshev(99)
        def type2_facs_rad(ish, lc):
            facs0 = facs_rad(mol, ish, lc, rc, rs).transpose(0,2,1).copy()
            facs1 = numpy.empty_like(facs0)
            libecp.type2_facs_rad(facs1.ctypes.data_as(ctypes.c_void_p),
                                  ctypes.c_int(ish), ctypes.c_int(lc),
                                  ctypes.c_double(rc),
                                  rs.ctypes.data_as(ctypes.c_void_p),
                                  ctypes.c_int(len(rs)), ctypes.c_int(1),
                                  mol._atm.ctypes.data_as(ctypes.c_void_p), ctypes.c_int(mol.natm),
                                  mol._bas.ctypes.data_as(ctypes.c_void_p), ctypes.c_int(mol.nbas),
                                  mol._env.ctypes.data_as(ctypes.c_void_p))
            self.assertTrue(numpy.allclose(facs0, facs1))
        for ish in range(mol.nbas):
            for lc in range(5):
                type2_facs_rad(ish, lc) 
Example #20
Source Project: pyscf   Author: pyscf   File: test_ecp.py    License: Apache License 2.0 6 votes vote down vote up
def test_type1_rad(self):
        k = 1.621
        aij = .792
        rs, ws = radi.gauss_chebyshev(99)
        ur = rad_part(mol, mol._ecpbas, rs) * ws
        def gen_type1_rad(li):
            rad_all0 = type1_rad_part(li, k, aij, ur, rs)
            rad_all1 = numpy.zeros_like(rad_all0)
            libecp.type1_rad_part(rad_all1.ctypes.data_as(ctypes.c_void_p),
                                  ctypes.c_int(li),
                                  ctypes.c_double(k), ctypes.c_double(aij),
                                  ur.ctypes.data_as(ctypes.c_void_p),
                                  rs.ctypes.data_as(ctypes.c_void_p),
                                  ctypes.c_int(len(rs)), ctypes.c_int(1))
            self.assertTrue(numpy.allclose(rad_all0, rad_all1))
        for l in range(13):
            gen_type1_rad(l) 
Example #21
Source Project: olympe   Author: Parrot-Developers   File: messages.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def _ar_arsdk_encode_type_info(cls, ar_argtype):
        arsdk_encode_type_info_map = {
            arsdkparser.ArArgType.I8: (od.ARSDK_ARG_TYPE_I8, "i8", ctypes.c_int8),
            arsdkparser.ArArgType.U8: (od.ARSDK_ARG_TYPE_U8, "u8", ctypes.c_uint8),
            arsdkparser.ArArgType.I16: (od.ARSDK_ARG_TYPE_I16, "i16", ctypes.c_int16),
            arsdkparser.ArArgType.U16: (od.ARSDK_ARG_TYPE_U16, "u16", ctypes.c_uint16),
            arsdkparser.ArArgType.I32: (od.ARSDK_ARG_TYPE_I32, "i32", ctypes.c_int32),
            arsdkparser.ArArgType.U32: (od.ARSDK_ARG_TYPE_U32, "u32", ctypes.c_uint32),
            arsdkparser.ArArgType.I64: (od.ARSDK_ARG_TYPE_I64, "i64", ctypes.c_int64),
            arsdkparser.ArArgType.U64: (od.ARSDK_ARG_TYPE_U64, "u64", ctypes.c_uint64),
            arsdkparser.ArArgType.FLOAT: (od.ARSDK_ARG_TYPE_FLOAT, "f32", ctypes.c_float),
            arsdkparser.ArArgType.DOUBLE: (od.ARSDK_ARG_TYPE_DOUBLE, "f64", ctypes.c_double),
            arsdkparser.ArArgType.STRING: (od.ARSDK_ARG_TYPE_STRING, "cstr", od.char_pointer_cast),
            arsdkparser.ArArgType.ENUM: (od.ARSDK_ARG_TYPE_ENUM, "i32", ctypes.c_int32),
        }
        return arsdk_encode_type_info_map[ar_argtype] 
Example #22
Source Project: GTDWeb   Author: lanbing510   File: coordseq.py    License: GNU General Public License v2.0 6 votes vote down vote up
def cs_operation(func, ordinate=False, get=False):
    "For coordinate sequence operations."
    if get:
        # Get routines get double parameter passed-in by reference.
        func.errcheck = check_cs_get
        dbl_param = POINTER(c_double)
    else:
        func.errcheck = check_cs_op
        dbl_param = c_double

    if ordinate:
        # Get/Set ordinate routines have an extra uint parameter.
        func.argtypes = [CS_PTR, c_uint, c_uint, dbl_param]
    else:
        func.argtypes = [CS_PTR, c_uint, dbl_param]

    func.restype = c_int
    return func 
Example #23
Source Project: lambda-packs   Author: ryfeus   File: basic.py    License: MIT License 6 votes vote down vote up
def c_float_array(data):
    """Get pointer of float numpy array / list."""
    if is_1d_list(data):
        data = np.array(data, copy=False)
    if is_numpy_1d_array(data):
        data = convert_from_sliced_object(data)
        assert data.flags.c_contiguous
        if data.dtype == np.float32:
            ptr_data = data.ctypes.data_as(ctypes.POINTER(ctypes.c_float))
            type_data = C_API_DTYPE_FLOAT32
        elif data.dtype == np.float64:
            ptr_data = data.ctypes.data_as(ctypes.POINTER(ctypes.c_double))
            type_data = C_API_DTYPE_FLOAT64
        else:
            raise TypeError("Expected np.float32 or np.float64, met type({})"
                            .format(data.dtype))
    else:
        raise TypeError("Unknown type({})".format(type(data).__name__))
    return (ptr_data, type_data, data)  # return `data` to avoid the temporary copy is freed 
Example #24
Source Project: lambda-packs   Author: ryfeus   File: basic.py    License: MIT License 6 votes vote down vote up
def get_leaf_output(self, tree_id, leaf_id):
        """Get the output of a leaf.

        Parameters
        ----------
        tree_id : int
            The index of the tree.
        leaf_id : int
            The index of the leaf in the tree.

        Returns
        -------
        result : float
            The output of the leaf.
        """
        ret = ctypes.c_double(0)
        _safe_call(_LIB.LGBM_BoosterGetLeafValue(
            self.handle,
            ctypes.c_int(tree_id),
            ctypes.c_int(leaf_id),
            ctypes.byref(ret)))
        return ret.value 
Example #25
Source Project: lambda-packs   Author: ryfeus   File: basic.py    License: MIT License 6 votes vote down vote up
def __inner_predict(self, data_idx):
        """Predict for training and validation dataset."""
        if data_idx >= self.__num_dataset:
            raise ValueError("Data_idx should be smaller than number of dataset")
        if self.__inner_predict_buffer[data_idx] is None:
            if data_idx == 0:
                n_preds = self.train_set.num_data() * self.__num_class
            else:
                n_preds = self.valid_sets[data_idx - 1].num_data() * self.__num_class
            self.__inner_predict_buffer[data_idx] = np.zeros(n_preds, dtype=np.float64)
        # avoid to predict many time in one iteration
        if not self.__is_predicted_cur_iter[data_idx]:
            tmp_out_len = ctypes.c_int64(0)
            data_ptr = self.__inner_predict_buffer[data_idx].ctypes.data_as(ctypes.POINTER(ctypes.c_double))
            _safe_call(_LIB.LGBM_BoosterGetPredict(
                self.handle,
                ctypes.c_int(data_idx),
                ctypes.byref(tmp_out_len),
                data_ptr))
            if tmp_out_len.value != len(self.__inner_predict_buffer[data_idx]):
                raise ValueError("Wrong length of predict results for data %d" % (data_idx))
            self.__is_predicted_cur_iter[data_idx] = True
        return self.__inner_predict_buffer[data_idx] 
Example #26
Source Project: contextualbandits   Author: david-cortes   File: __init__.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def _set_dtype(self, force_cast=False):
        self._dtype = ctypes.c_float if self._use_float else ctypes.c_double

        if force_cast:
            if self.coef_.dtype != self._dtype:
                self.coef_ = self.coef_.astype(self._dtype)
            if self._XtX.dtype != self._dtype:
                self._XtX = self._XtX.astype(self._dtype)
            if self._invXtX.dtype != self._dtype:
                self._invXtX = self._invXtX.astype(self._dtype)
            if self._XtY.dtype != self._dtype:
                self._XtY = self._XtY.astype(self._dtype)
            if self._bufferX.dtype != self._dtype:
                self._bufferX = self._bufferX.astype(self._dtype) 
Example #27
Source Project: contextualbandits   Author: david-cortes   File: online.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def _predict(self, X, exploit = False):
        X = _check_X_input(X)
        
        if X.shape[0] == 0:
            return np.array([])
        
        if exploit:
            return self._oracles.predict(X)
        
        if self.explore_cnt < self.explore_rounds:
            self.explore_cnt += X.shape[0]
            
            # case 1: all predictions are within allowance
            if self.explore_cnt <= self.explore_rounds:
                pred = self.random_state.integers(self.nchoices, size = X.shape[0])
                self._choose_active(X, pred)
                return pred
            
            # case 2: some predictions are within allowance, others are not
            else:
                n_explore = self.explore_rounds - self.explore_cnt + X.shape[0]
                pred = np.empty(X.shape[0], type = ctypes.c_double)
                pred[:n_explore] = self.random_state.integers(self.nchoices, n_explore)
                self._choose_active(X[:n_explore], pred[:n_explore])
                pred[n_explore:] = self._oracles.predict(X[n_explore:])
                return pred
        else:
            return self._oracles.predict(X) 
Example #28
Source Project: contextualbandits   Author: david-cortes   File: utils.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def _process_X(self, X):
        if X.dtype != ctypes.c_double:
            X = X.astype(ctypes.c_double)
        if issparse(X):
            Xcsr = X
            X = np.empty((0,0), dtype=ctypes.c_double)
        else:
            Xcsr = None
        return X, Xcsr 
Example #29
Source Project: contextualbandits   Author: david-cortes   File: utils.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def partial_fit(self, X, y):
        if X.shape[0] == 0:
            return self
        elif not self.is_fitted:
            self.update_aux(y)
            return self

        new_pos = np.zeros(n_nodes, dtype=ctypes.c_long)
        new_neg = np.zeros(n_nodes, dtype=ctypes.c_long)
        pred_node = self.model.apply(X).astype(ctypes.c_long)
        _create_node_counters(new_pos, new_neg, pred_node, y.astype(ctypes.c_double))
        self.pos[:] += new_pos
        self.neg[:] += new_neg
        return self 
Example #30
Source Project: oscrypto   Author: wbond   File: _core_foundation_ctypes.py    License: MIT License 5 votes vote down vote up
def cf_number_to_number(value):
        """
        Converts a CFNumber object to a python float or integer

        :param value:
            The CFNumber object

        :return:
            A python number (float or integer)
        """

        type_ = CoreFoundation.CFNumberGetType(_cast_pointer_p(value))
        c_type = {
            1: c_byte,              # kCFNumberSInt8Type
            2: ctypes.c_short,      # kCFNumberSInt16Type
            3: ctypes.c_int32,      # kCFNumberSInt32Type
            4: ctypes.c_int64,      # kCFNumberSInt64Type
            5: ctypes.c_float,      # kCFNumberFloat32Type
            6: ctypes.c_double,     # kCFNumberFloat64Type
            7: c_byte,              # kCFNumberCharType
            8: ctypes.c_short,      # kCFNumberShortType
            9: ctypes.c_int,        # kCFNumberIntType
            10: c_long,             # kCFNumberLongType
            11: ctypes.c_longlong,  # kCFNumberLongLongType
            12: ctypes.c_float,     # kCFNumberFloatType
            13: ctypes.c_double,    # kCFNumberDoubleType
            14: c_long,             # kCFNumberCFIndexType
            15: ctypes.c_int,       # kCFNumberNSIntegerType
            16: ctypes.c_double,    # kCFNumberCGFloatType
        }[type_]
        output = c_type(0)
        CoreFoundation.CFNumberGetValue(_cast_pointer_p(value), type_, byref(output))
        return output.value