Python ctypes.c_double() Examples

The following are 30 code examples of ctypes.c_double(). 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 File: messages.py    From olympe with 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 #2
Source File: selected_ci.py    From pyscf with 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 #3
Source File: m_rsphar_libnao.py    From pyscf with 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 #4
Source File: test_libxc.py    From pyscf with 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 File: basic.py    From lambda-packs with 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 #6
Source File: utils.py    From contextualbandits with 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 #7
Source File: online.py    From contextualbandits with 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 #8
Source File: opencv.py    From dynamic-training-with-apache-mxnet-on-aws with 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 #9
Source File: basic.py    From lambda-packs with 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 #10
Source File: m_rsphar_libnao.py    From pyscf with 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 #11
Source File: m_rsphar_libnao.py    From pyscf with 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 #12
Source File: nao.py    From pyscf with 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 #13
Source File: m_comp_spatial_distributions.py    From pyscf with 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 #14
Source File: m_dens_libnao.py    From pyscf with 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 #15
Source File: basic.py    From lambda-packs with 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 #16
Source File: test_ecp.py    From pyscf with 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 #17
Source File: test_ecp.py    From pyscf with 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 #18
Source File: numpy_helper.py    From pyscf with 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 File: m_aos_libnao.py    From pyscf with 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 #20
Source File: m_comp_vext_tem.py    From pyscf with 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 #21
Source File: prod_basis.py    From pyscf with 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 #22
Source File: coordseq.py    From GTDWeb with 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 File: m_thrj.py    From pyscf with 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 #24
Source File: m_prod_basis_obsolete.py    From pyscf with 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 #25
Source File: m_blas_wrapper.py    From pyscf with 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 #26
Source File: geometry.py    From GTDWeb with GNU General Public License v2.0 5 votes vote down vote up
def area(self):
        "Returns the area of the Geometry."
        return capi.geos_area(self.ptr, byref(c_double())) 
Example #27
Source File: cpp32.py    From msl-loadlib with MIT License 5 votes vote down vote up
def distance_4_points(self, points):
        """Calculates the total distance connecting 4 :class:`~.Point`\'s.

        The corresponding C++ code is

        .. code-block:: cpp

            double distance_4_points(FourPoints p) {
                double d = distance(p.points[0], p.points[3]);
                for (int i = 1; i < 4; i++) {
                    d += distance(p.points[i], p.points[i-1]);
                }
                return d;
            }

        See the corresponding 64-bit :meth:`~.cpp64.Cpp64.distance_4_points` method.

        Parameters
        ----------
        points : :class:`.FourPoints`
            The points to use to calculate the total distance.

        Returns
        -------
        :class:`float`
            The total distance connecting the 4 :class:`~.Point`\'s.
        """
        self.lib.distance_4_points.restype = ctypes.c_double
        return self.lib.distance_4_points(points) 
Example #28
Source File: coordseq.py    From GTDWeb with GNU General Public License v2.0 5 votes vote down vote up
def getOrdinate(self, dimension, index):
        "Returns the value for the given dimension and index."
        self._checkindex(index)
        self._checkdim(dimension)
        return capi.cs_getordinate(self.ptr, index, dimension, byref(c_double())) 
Example #29
Source File: cpp32.py    From msl-loadlib with MIT License 5 votes vote down vote up
def scalar_multiply(self, a, xin):
        """Multiply each element in an array by a number.

        The corresponding C++ code is

        .. code-block:: cpp

            void scalar_multiply(double a, double* xin, int n, double* xout) {
                for (int i = 0; i < n; i++) {
                    xout[i] = a * xin[i];
                }
            }

        See the corresponding 64-bit :meth:`~.cpp64.Cpp64.scalar_multiply` method.

        Parameters
        ----------
        a : :class:`float`
            The scalar value.
        xin : :class:`list` of :class:`float`
            The array to modify.

        Returns
        -------
        :class:`list` of :class:`float`
            A new array with each element in `xin` multiplied by `a`.
        """
        n = len(xin)
        xout = (ctypes.c_double * n)()  # allocate memory

        self.lib.scalar_multiply.restype = None

        self.lib.scalar_multiply(ctypes.c_double(float(a)),
                                 (ctypes.c_double * n)(*xin),
                                 ctypes.c_int32(n),
                                 ctypes.byref(xout))
        return [value for value in xout] 
Example #30
Source File: geometry.py    From GTDWeb with GNU General Public License v2.0 5 votes vote down vote up
def distance(self, other):
        """
        Returns the distance between the closest points on this Geometry
        and the other. Units will be in those of the coordinate system of
        the Geometry.
        """
        if not isinstance(other, GEOSGeometry):
            raise TypeError('distance() works only on other GEOS Geometries.')
        return capi.geos_distance(self.ptr, other.ptr, byref(c_double()))