Python ctypes.c_int64() Examples

The following are 30 code examples of ctypes.c_int64(). 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: basic.py    From lambda-packs with MIT License 6 votes vote down vote up
def __init_from_csc(self, csc, params_str, ref_dataset):
        """Initialize data from a CSC matrix."""
        if len(csc.indices) != len(csc.data):
            raise ValueError('Length mismatch: {} vs {}'.format(len(csc.indices), len(csc.data)))
        self.handle = ctypes.c_void_p()

        ptr_indptr, type_ptr_indptr, __ = c_int_array(csc.indptr)
        ptr_data, type_ptr_data, _ = c_float_array(csc.data)

        assert csc.shape[0] <= MAX_INT32
        csc.indices = csc.indices.astype(np.int32, copy=False)

        _safe_call(_LIB.LGBM_DatasetCreateFromCSC(
            ptr_indptr,
            ctypes.c_int(type_ptr_indptr),
            csc.indices.ctypes.data_as(ctypes.POINTER(ctypes.c_int32)),
            ptr_data,
            ctypes.c_int(type_ptr_data),
            ctypes.c_int64(len(csc.indptr)),
            ctypes.c_int64(len(csc.data)),
            ctypes.c_int64(csc.shape[0]),
            c_str(params_str),
            ref_dataset,
            ctypes.byref(self.handle)))
        return self 
Example #2
Source File: RHINE.py    From OpenHINE with MIT License 6 votes vote down vote up
def __init__(self):
        self.lib_IRs = ctypes.cdll.LoadLibrary("./src/release/Sample_IRs.so")
        self.lib_IRs.sampling.argtypes = [ctypes.c_void_p, ctypes.c_void_p, ctypes.c_void_p, ctypes.c_void_p,
                                          ctypes.c_int64, ctypes.c_int64, ctypes.c_int64]
        self.lib_IRs.getHeadBatch.argtypes = [
            ctypes.c_void_p, ctypes.c_void_p, ctypes.c_void_p]
        self.lib_IRs.getTailBatch.argtypes = [
            ctypes.c_void_p, ctypes.c_void_p, ctypes.c_void_p]

        self.lib_ARs = ctypes.cdll.LoadLibrary("./src/release/Sample_ARs.so")
        self.lib_ARs.sampling.argtypes = [ctypes.c_void_p, ctypes.c_void_p, ctypes.c_void_p, ctypes.c_void_p,
                                          ctypes.c_int64, ctypes.c_int64, ctypes.c_int64]
        self.lib_ARs.getHeadBatch.argtypes = [
            ctypes.c_void_p, ctypes.c_void_p, ctypes.c_void_p]
        self.lib_ARs.getTailBatch.argtypes = [
            ctypes.c_void_p, ctypes.c_void_p, ctypes.c_void_p] 
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_pooling.py    From zerodb with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_forking(db):
    id_conn_parent = id(db._connection)
    id_conn_child = multiprocessing.Value(ctypes.c_int64)

    def f():
        assert len(db[Page]) > 0  # Check that DB is functional in the subprocess
        id_conn_child.value = id(db._connection)

    p = multiprocessing.Process(target=f)
    p.daemon = True
    p.start()
    p.join(10)

    # Test that child used connection other than parent
    assert id_conn_child.value != 0
    assert id_conn_child.value != id_conn_parent 
Example #5
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 #6
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 #7
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 #8
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 #9
Source File: tecio_szl.py    From handyscripts with MIT License 6 votes vote down vote up
def zone_write_int16_values(file_handle, zone, var, values):
    tecio.tecZoneVarWriteInt16Values.restype=ctypes.c_int32
    tecio.tecZoneVarWriteInt16Values.argtypes=(
            ctypes.c_void_p, #file_handle
            ctypes.c_int32,  #zone
            ctypes.c_int32,  #var
            ctypes.c_int32,  #partition
            ctypes.c_int64,  #count
            ctypes.POINTER(ctypes.c_int16)) #values

    values_ptr = (ctypes.c_int16*len(values))(*values)
    ret = tecio.tecZoneVarWriteInt16Values(file_handle,
            zone,
            var,
            0,
            len(values),
            values_ptr)
    if ret != 0:
        raise Exception("zone_write_int16_values Error") 
Example #10
Source File: tf.py    From deep500 with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def _custom_cpp_op(op: CompilableOp, stateful, name):
    """ Compiles and registers a custom C++ Tensorflow operator """
    # Compile the .so file
    tf_path = os.path.abspath(os.path.dirname(tf.__file__))
    
    so_file = TFCompiler().compile_op(op.name, op.files, 
        op.inputs, op.outputs,
        any([f.endswith('.cu') for f in op.files]), op.live_output,  
        additional_cmake_options=['-DTENSORFLOW_PATH=' + tf_path] + op.cmake_options,
        additional_definitions=op.defs, output_folder=op.output_folder)

    # Load the compiled library into Tensorflow
    op_module = tf.load_op_library(so_file)
    op_func = getattr(op_module, 'tf_op' + op.name)
    op_grad_func = getattr(op_module, 'tf_op_grad' + op.name)
    
    # Create the deep500 custom op object
    lib = ctypes.CDLL(so_file)
    if not getattr(lib, 'create_new_op', False):
        raise ValueError('Invalid custom operator library file')
    lib.create_new_op.restype = ctypes.c_int64
    lib.is_cuda_supported.restype = ctypes.c_bool
    lib.report.restype = ctypes.c_int64

    return TFCompiledOp(op, op_func, op_grad_func, lib) 
Example #11
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 #12
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 #13
Source File: tecio_szl.py    From handyscripts with MIT License 6 votes vote down vote up
def zone_write_int32_values(file_handle, zone, var, values):
    tecio.tecZoneVarWriteInt32Values.restype=ctypes.c_int32
    tecio.tecZoneVarWriteInt32Values.argtypes=(
            ctypes.c_void_p, #file_handle
            ctypes.c_int32,  #zone
            ctypes.c_int32,  #var
            ctypes.c_int32,  #partition
            ctypes.c_int64,  #count
            ctypes.POINTER(ctypes.c_int32)) #values

    values_ptr = (ctypes.c_int32*len(values))(*values)
    ret = tecio.tecZoneVarWriteInt32Values(file_handle,
            zone,
            var,
            0,
            len(values),
            values_ptr)
    if ret != 0:
        raise Exception("zone_write_int32_values Error") 
Example #14
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 #15
Source File: tecio_szl.py    From handyscripts with MIT License 6 votes vote down vote up
def zone_write_float_values(file_handle, zone, var, values):
    tecio.tecZoneVarWriteFloatValues.restype=ctypes.c_int32
    tecio.tecZoneVarWriteFloatValues.argtypes=(
            ctypes.c_void_p, #file_handle
            ctypes.c_int32,  #zone
            ctypes.c_int32,  #var
            ctypes.c_int32,  #partition
            ctypes.c_int64,  #count
            ctypes.POINTER(ctypes.c_float)) #values

    values_ptr = (ctypes.c_float*len(values))(*values)
    ret = tecio.tecZoneVarWriteFloatValues(file_handle,
            zone,
            var,
            0,
            len(values),
            values_ptr)
    if ret != 0:
        raise Exception("zone_write_float_values Error") 
Example #16
Source File: tecio_szl.py    From handyscripts with MIT License 6 votes vote down vote up
def zone_write_double_values(file_handle, zone, var, values):
    tecio.tecZoneVarWriteDoubleValues.restype=ctypes.c_int32
    tecio.tecZoneVarWriteDoubleValues.argtypes=(
            ctypes.c_void_p, #file_handle
            ctypes.c_int32,  #zone
            ctypes.c_int32,  #var
            ctypes.c_int32,  #partition
            ctypes.c_int64,  #count
            ctypes.POINTER(ctypes.c_double)) #values

    values_ptr = (ctypes.c_double*len(values))(*values)
    ret = tecio.tecZoneVarWriteDoubleValues(file_handle,
            zone,
            var,
            0,
            len(values),
            values_ptr)
    if ret != 0:
        raise Exception("zone_write_double_values Error") 
Example #17
Source File: utils.py    From debin with Apache License 2.0 6 votes vote down vote up
def adapt_int_width(n, width, signed=True):
    n = int(n)

    if width == 1:
        result = n
    elif width == 2:
        result = n
    elif width == 4:
        result = ctypes.c_int8(n).value if signed else ctypes.c_uint8(n).value
    elif width == 8:
        result = ctypes.c_int8(n).value if signed else ctypes.c_uint8(n).value
    elif width == 16:
        result = ctypes.c_int16(n).value if signed else ctypes.c_uint16(n).value
    elif width == 32:
        result = ctypes.c_int32(n).value if signed else ctypes.c_uint32(n).value
    elif width == 64:
        result = ctypes.c_int64(n).value if signed else ctypes.c_uint64(n).value
    else:
        result = n
    return result 
Example #18
Source File: basic.py    From lambda-packs with MIT License 6 votes vote down vote up
def c_int_array(data):
    """Get pointer of int 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.int32:
            ptr_data = data.ctypes.data_as(ctypes.POINTER(ctypes.c_int32))
            type_data = C_API_DTYPE_INT32
        elif data.dtype == np.int64:
            ptr_data = data.ctypes.data_as(ctypes.POINTER(ctypes.c_int64))
            type_data = C_API_DTYPE_INT64
        else:
            raise TypeError("Expected np.int32 or np.int64, 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 #19
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 #20
Source File: wsm_storage_manager.py    From cloudbase-init with Apache License 2.0 5 votes vote down vote up
def set_san_policy(self, san_policy):
        if san_policy != base.SAN_POLICY_ONLINE:
            raise exception.CloudbaseInitException(
                "Only SAN_POLICY_ONLINE is currently supported")
        handle = kernel32.CreateFileW(
            u"\\\\.\\PartmgrControl",
            kernel32.GENERIC_READ | kernel32.GENERIC_WRITE,
            kernel32.FILE_SHARE_READ | kernel32.FILE_SHARE_WRITE,
            None, kernel32.OPEN_EXISTING, 0, None)

        if handle == kernel32.INVALID_HANDLE_VALUE:
            raise exception.WindowsCloudbaseInitException(
                "Cannot access PartmgrControl: %r")

        try:
            input_data_online = ctypes.c_int64(0x100000008)
            input_data_size = 8
            control_code = 0x7C204

            if not kernel32.DeviceIoControl(
                    handle, control_code, ctypes.addressof(input_data_online),
                    input_data_size, None, 0, None, None):
                raise exception.WindowsCloudbaseInitException(
                    "DeviceIoControl failed: %r")
        finally:
            kernel32.CloseHandle(handle) 
Example #21
Source File: debuginfo.py    From debin with Apache License 2.0 5 votes vote down vote up
def get_array_upper_bound(self, die):
        for child in die.iter_children():
            if child.tag == 'DW_TAG_subrange_type':
                upper_bound_attr = child.attributes.get('DW_AT_upper_bound', None)
                if upper_bound_attr is None:
                    return None
                else:
                    if upper_bound_attr.form in ('DW_FORM_data1',
                                                 'DW_FORM_data2',
                                                 'DW_FORM_data4',
                                                 'DW_FORM_data8'):
                        return upper_bound_attr.value
                    elif upper_bound_attr.form == 'DW_FORM_exprloc':
                        loc = upper_bound_attr.value
                        if loc[0] == ENUM_DW_FORM_exprloc['DW_OP_const1u']:
                            return ctypes.c_uint8(loc[1]).value
                        elif loc[0] == ENUM_DW_FORM_exprloc['DW_OP_const1s']:
                            return ctypes.c_int8(loc[1]).value
                        elif loc[0] == ENUM_DW_FORM_exprloc['DW_OP_const2u']:
                            return ctypes.c_uint16(utils.decode_kbytes(loc[1:], 2)).value
                        elif loc[0] == ENUM_DW_FORM_exprloc['DW_OP_const2s']:
                            return ctypes.c_int16(utils.decode_kbytes(loc[1:], 2)).value
                        elif loc[0] == ENUM_DW_FORM_exprloc['DW_OP_const4u']:
                            return ctypes.c_uint32(utils.decode_kbytes(loc[1:], 2)).value
                        elif loc[0] == ENUM_DW_FORM_exprloc['DW_OP_const4s']:
                            return ctypes.c_int32(utils.decode_kbytes(loc[1:], 2)).value
                        elif loc[0] == ENUM_DW_FORM_exprloc['DW_OP_const8u']:
                            return ctypes.c_uint64(utils.decode_kbytes(loc[1:], 2)).value
                        elif loc[0] == ENUM_DW_FORM_exprloc['DW_OP_const8s']:
                            return ctypes.c_int64(utils.decode_kbytes(loc[1:], 2)).value
                        elif loc[0] == ENUM_DW_FORM_exprloc['DW_OP_constu']:
                            return utils.decode_uleb128(loc[1:])
                        elif loc[0] == ENUM_DW_FORM_exprloc['DW_OP_consts']:
                            return utils.decode_sleb128(loc[1:])
                        else:
                            return None
                    else:
                        return None 
Example #22
Source File: linux.py    From manticore with GNU Affero General Public License v3.0 5 votes vote down vote up
def _to_signed_dword(self, dword: int):
        arch_width = self.current.address_bit_size
        if arch_width == 32:
            sdword = ctypes.c_int32(dword).value
        elif arch_width == 64:
            sdword = ctypes.c_int64(dword).value
        else:
            raise EnvironmentError(f"Corrupted internal CPU state (arch width is {arch_width})")
        return sdword 
Example #23
Source File: common.py    From MobulaOP with MIT License 5 votes vote down vote up
def _get_numpy_type():
        name2ctype = dict()
        pairs = [
            (np.dtype('int8'), ctypes.c_int8),
            (np.dtype('int16'), ctypes.c_int16),
            (np.dtype('int32'), ctypes.c_int32),
            (np.dtype('int64'), ctypes.c_int64),  # alias: np.int
            (np.dtype('float32'), ctypes.c_float),
            (np.dtype('float64'), ctypes.c_double),  # alias: np.float
        ]
        for dtype, ctype in pairs:
            name2ctype[dtype.name] = ctype
        return name2ctype 
Example #24
Source File: bruker_tims.py    From ms_deisotope with Apache License 2.0 5 votes vote down vote up
def _load_library(lib_path):
    dll = cdll.LoadLibrary(os.path.realpath(lib_path))
    dll.tims_open.argtypes = [c_char_p, c_uint32]
    dll.tims_open.restype = c_uint64

    dll.tims_close.argtypes = [c_uint64]
    dll.tims_close.restype = None

    dll.tims_get_last_error_string.argtypes = [c_char_p, c_uint32]
    dll.tims_get_last_error_string.restype = c_uint32

    dll.tims_has_recalibrated_state.argtypes = [c_uint64]
    dll.tims_has_recalibrated_state.restype = c_uint32

    dll.tims_read_scans_v2.argtypes = [
        c_uint64, c_int64, c_uint32, c_uint32, c_void_p, c_uint32]
    dll.tims_read_scans_v2.restype = c_uint32

    dll.tims_oneoverk0_to_ccs_for_mz.argtypes = [c_double, c_int32, c_double]
    dll.tims_oneoverk0_to_ccs_for_mz.restype = c_double

    dll.tims_ccs_to_oneoverk0_for_mz.argtypes = [c_double, c_int32, c_double]
    dll.tims_ccs_to_oneoverk0_for_mz.restype = c_double


    convfunc_argtypes = [c_uint64, c_int64, POINTER(
        c_double), POINTER(c_double), c_uint32]

    for fn in [dll.tims_index_to_mz, dll.tims_mz_to_index, dll.tims_scannum_to_oneoverk0,
               dll.tims_oneoverk0_to_scannum, dll.tims_scannum_to_voltage, dll.tims_voltage_to_scannum]:
        fn.argtypes = convfunc_argtypes
        fn.restype = c_uint32
    return dll 
Example #25
Source File: parentpoller.py    From Computable with MIT License 5 votes vote down vote up
def run(self):
        """ Run the poll loop. This method never returns.
        """
        try:
            from _winapi import WAIT_OBJECT_0, INFINITE
        except ImportError:
            from _subprocess import WAIT_OBJECT_0, INFINITE

        # Build the list of handle to listen on.
        handles = []
        if self.interrupt_handle:
            handles.append(self.interrupt_handle)
        if self.parent_handle:
            handles.append(self.parent_handle)
        arch = platform.architecture()[0]
        c_int = ctypes.c_int64 if arch.startswith('64') else ctypes.c_int

        # Listen forever.
        while True:
            result = ctypes.windll.kernel32.WaitForMultipleObjects(
                len(handles),                            # nCount
                (c_int * len(handles))(*handles),        # lpHandles
                False,                                   # bWaitAll
                INFINITE)                                # dwMilliseconds

            if WAIT_OBJECT_0 <= result < len(handles):
                handle = handles[result - WAIT_OBJECT_0]

                if handle == self.interrupt_handle:
                    interrupt_main()

                elif handle == self.parent_handle:
                    os._exit(1)
            elif result < 0:
                # wait failed, just give up and stop polling.
                warn("""Parent poll failed.  If the frontend dies,
                the kernel may be left running.  Please let us know
                about your system (bitness, Python, etc.) at
                ipython-dev@scipy.org""")
                return 
Example #26
Source File: parallel.py    From tmtoolkit with Apache License 2.0 5 votes vote down vote up
def _prepare_data(data):
        """
        Prepare 2D array/matrix `data` for parallel processing by converting it to COO sparse matrix (if necessary)
        and creating shared data pointers for direct access for worker processes.
        """
        if hasattr(data, 'dtype'):
            if not hasattr(data, 'shape') or len(data.shape) != 2:
                raise ValueError('`data` must be a NumPy array/matrix or SciPy sparse matrix of two dimensions')

            if data.dtype == np.int:
                arr_ctype = ctypes.c_int
            elif data.dtype == np.int32:
                arr_ctype = ctypes.c_int32
            elif data.dtype == np.int64:
                arr_ctype = ctypes.c_int64
            else:
                raise ValueError('dtype of `data` is not supported: `%s`' % data.dtype)

            if not hasattr(data, 'format'):  # dense matrix -> convert to sparse matrix in coo format
                data = coo_matrix(data)
            elif data.format != 'coo':
                data = data.tocoo()

            sparse_data_base = mp.Array(arr_ctype, data.data)
            sparse_rows_base = mp.Array(ctypes.c_int, data.row)  # TODO: datatype correct?
            sparse_cols_base = mp.Array(ctypes.c_int, data.col)  # TODO: datatype correct?

            logger.info('initializing evaluation with sparse matrix of format `%s` and shape %dx%d'
                        % (data.format, data.shape[0], data.shape[1]))

            return sparse_data_base, sparse_rows_base, sparse_cols_base
        else:
            return data 
Example #27
Source File: fortran32.py    From msl-loadlib with MIT License 5 votes vote down vote up
def sum_64bit(self, a, b):
        """Add two 64-bit signed integers. 
        
        Python only has one :class:`int` data type to represent integer values.
        The :meth:`~.fortran32.Fortran32.sum_64bit` method converts the data types 
        of `a` and `b` to be :class:`ctypes.c_int64`.

        The corresponding FORTRAN code is

        .. code-block:: fortran

            function sum_64bit(a, b) result(value)
                !DEC$ ATTRIBUTES DLLEXPORT, ALIAS:'sum_64bit' :: sum_64bit
                implicit none
                integer(8) :: a, b, value
                value = a + b
            end function sum_64bit

        See the corresponding 64-bit :meth:`~.fortran64.Fortran64.sum_64bit` method.

        Parameters
        ----------
        a : :class:`int`
            The first 64-bit signed integer.
        b : :class:`int`
            The second 64-bit signed integer.

        Returns
        -------
        :class:`int`
            The sum of `a` and `b`.
        """
        ac = ctypes.c_int64(a)
        bc = ctypes.c_int64(b)
        self.lib.sum_64bit.restype = ctypes.c_int64
        return self.lib.sum_64bit(ctypes.byref(ac), ctypes.byref(bc)) 
Example #28
Source File: Config.py    From NeuralTripleTranslation with Apache License 2.0 5 votes vote down vote up
def __init__(self):
        self.lib = ctypes.cdll.LoadLibrary("./release/Base.so")
        self.lib.sampling.argtypes = [ctypes.c_void_p, ctypes.c_void_p, ctypes.c_void_p, ctypes.c_void_p, ctypes.c_int64, ctypes.c_int64, ctypes.c_int64]
        self.lib.getHeadBatch.argtypes = [ctypes.c_void_p, ctypes.c_void_p, ctypes.c_void_p]
        self.lib.getTailBatch.argtypes = [ctypes.c_void_p, ctypes.c_void_p, ctypes.c_void_p]
        self.lib.testHead.argtypes = [ctypes.c_void_p]
        self.lib.testTail.argtypes = [ctypes.c_void_p]
        self.lib.getTestBatch.argtypes = [ctypes.c_void_p, ctypes.c_void_p, ctypes.c_void_p, ctypes.c_void_p, ctypes.c_void_p, ctypes.c_void_p]
        self.lib.getValidBatch.argtypes = [ctypes.c_void_p, ctypes.c_void_p, ctypes.c_void_p, ctypes.c_void_p, ctypes.c_void_p, ctypes.c_void_p]
        self.lib.getBestThreshold.argtypes = [ctypes.c_void_p, ctypes.c_void_p]
        self.lib.test_triple_classification.argtypes = [ctypes.c_void_p, ctypes.c_void_p]
        self.test_flag = False
        self.in_path = "./"
        self.out_path = "./"
        self.bern = 0
        self.hidden_size = 100
        self.ent_size = self.hidden_size
        self.rel_size = self.hidden_size
        self.train_times = 0
        self.margin = 1.0
        self.nbatches = 100
        self.negative_ent = 1
        self.negative_rel = 0
        self.workThreads = 1
        self.alpha = 0.001
        self.lmbda = 0.000
        self.log_on = 1
        self.lr_decay=0.000
        self.weight_decay=0.000
        self.exportName = None
        self.importName = None
        self.export_steps = 0
        self.opt_method = "SGD"
        self.optimizer = None
        self.test_link_prediction = False
        self.test_triple_classification = False
        self.use_cuda = torch.cuda.is_available()
        self.trainModel = None 
Example #29
Source File: _core_foundation_ctypes.py    From oscrypto with 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 
Example #30
Source File: instruction.py    From Zvm with Apache License 2.0 5 votes vote down vote up
def execute(self, frame):
        val2 = frame.operand_stack.pop_long()
        val1 = frame.operand_stack.pop_long()
        s = val2 & 0x3f
        val = ctypes.c_uint64(val1).value
        res = ctypes.c_int64(val >> s).value
        frame.operand_stack.push_int(res)