Python源码示例:ctypes.c_void_p()
示例1
def c_handle_array(objs):
"""Create ctypes const void ** from a list of MXNet objects with handles.
Parameters
----------
objs : list of NDArray/Symbol.
MXNet objects.
Returns
-------
(ctypes.c_void_p * len(objs))
A void ** pointer that can be passed to C API.
"""
arr = (ctypes.c_void_p * len(objs))()
arr[:] = [o.handle for o in objs]
return arr
示例2
def asnumpy(self):
"""Returns a ``numpy.ndarray`` object with value copied from this array.
Examples
--------
>>> x = mx.nd.ones((2,3))
>>> y = x.asnumpy()
>>> type(y)
<type 'numpy.ndarray'>
>>> y
array([[ 1., 1., 1.],
[ 1., 1., 1.]], dtype=float32)
>>> z = mx.nd.ones((2,3), dtype='int32')
>>> z.asnumpy()
array([[1, 1, 1],
[1, 1, 1]], dtype=int32)
"""
data = np.empty(self.shape, dtype=self.dtype)
check_call(_LIB.MXNDArraySyncCopyToCPU(
self.handle,
data.ctypes.data_as(ctypes.c_void_p),
ctypes.c_size_t(data.size)))
return data
示例3
def set_monitor_callback(self, callback):
"""Install callback for monitor.
Parameters
----------
callback : function
Takes a string and an NDArrayHandle.
Examples
--------
>>> def mon_callback(*args, **kwargs):
>>> print("Do your stuff here.")
>>>
>>> texe.set_monitor_callback(mon_callback)
"""
cb_type = ctypes.CFUNCTYPE(None, ctypes.c_char_p, NDArrayHandle, ctypes.c_void_p)
self._monitor_callback = cb_type(_monitor_callback_wrapper(callback))
check_call(_LIB.MXExecutorSetMonitorCallback(
self.handle,
self._monitor_callback,
None))
示例4
def backward(heads, head_grads=None, retain_graph=False, train_mode=True): #pylint: disable=redefined-outer-name
"""Compute the gradients of heads w.r.t previously marked variables.
Parameters
----------
heads: NDArray or list of NDArray
Output NDArray(s)
head_grads: NDArray or list of NDArray or None
Gradients with respect to heads.
train_mode: bool, optional
Whether to do backward for training or predicting.
"""
head_handles, hgrad_handles = _parse_head(heads, head_grads)
check_call(_LIB.MXAutogradBackwardEx(
len(head_handles),
head_handles,
hgrad_handles,
0,
ctypes.c_void_p(0),
ctypes.c_int(retain_graph),
ctypes.c_int(0),
ctypes.c_int(train_mode),
ctypes.c_void_p(0),
ctypes.c_void_p(0)))
示例5
def _symbol_creator(handle, args, kwargs, keys, vals, name):
sym_handle = SymbolHandle()
check_call(_LIB.MXSymbolCreateAtomicSymbol(
ctypes.c_void_p(handle),
mx_uint(len(keys)),
c_str_array(keys),
c_str_array([str(v) for v in vals]),
ctypes.byref(sym_handle)))
if args and kwargs:
raise TypeError(
'Operators with variable length input can only accept input'
'Symbols either as positional or keyword arguments, not both')
s = _symbol_cls(sym_handle)
if args:
s._compose(*args, name=name)
elif kwargs:
s._compose(name=name, **kwargs)
else:
s._compose(name=name)
return s
示例6
def load_default_object(self):
v = np.array([[0.0, 0.5, 0.0, 1.0, 1.0, 0.0, 1.0],
[-0.5, -0.5, 0.0, 1.0, 0.0, 1.0, 1.0],
[0.5, -0.5, 0.0, 1.0, 1.0, 1.0, 1.0]], dtype=np.float32)
v = np.concatenate((v,v+0.1), axis=0)
v = np.ascontiguousarray(v, dtype=np.float32)
vbo = glGenBuffers(1)
glBindBuffer (GL_ARRAY_BUFFER, vbo)
glBufferData (GL_ARRAY_BUFFER, v.dtype.itemsize*v.size, v, GL_STATIC_DRAW)
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 28, ctypes.c_void_p(0))
glVertexAttribPointer(1, 4, GL_FLOAT, GL_FALSE, 28, ctypes.c_void_p(12))
glEnableVertexAttribArray(0);
glEnableVertexAttribArray(1);
self.num_to_render = 6;
示例7
def _actual_render(self):
for entity_id, entity in self.entities.iteritems():
if entity['visible']:
vbo = entity['vbo']
tbo = entity['tbo']
num = entity['num']
glBindBuffer(GL_ARRAY_BUFFER, vbo)
glVertexAttribPointer(self.egl_mapping['vertexs'], 3, GL_FLOAT, GL_FALSE,
20, ctypes.c_void_p(0))
glVertexAttribPointer(self.egl_mapping['vertexs_tc'], 2, GL_FLOAT,
GL_FALSE, 20, ctypes.c_void_p(12))
glEnableVertexAttribArray(self.egl_mapping['vertexs']);
glEnableVertexAttribArray(self.egl_mapping['vertexs_tc']);
glBindTexture(GL_TEXTURE_2D, tbo)
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glDrawArrays(GL_TRIANGLES, 0, num)
示例8
def ConfigureIOKit():
"""Sets up IOKit.
We use ctypes to call functions in shared libraries to create, access and
manipulate C data types in Python. For more information about ctypes, see:
http://python.net/crew/theller/ctypes/
http://code.rancidbacon.com/LearningAboutMacOSXNativePythonProgramming
Returns:
io_lib: IOKit library
"""
io_lib = ctypes.cdll.LoadLibrary(
'/System/Library/Frameworks/IOKit.framework/IOKit')
io_lib.IOPMAssertionCreateWithName.argtypes = [
ctypes.c_void_p,
ctypes.c_uint32,
ctypes.c_void_p,
ctypes.POINTER(ctypes.c_uint32)]
io_lib.IOPMAssertionRelease.argtypes = [ctypes.c_uint32]
return io_lib
示例9
def get(self, key, verify_checksums=False, fill_cache=True):
error = ctypes.POINTER(ctypes.c_char)()
options = _ldb.leveldb_readoptions_create()
_ldb.leveldb_readoptions_set_verify_checksums(options,
verify_checksums)
_ldb.leveldb_readoptions_set_fill_cache(options, fill_cache)
if self._snapshot is not None:
_ldb.leveldb_readoptions_set_snapshot(options, self._snapshot.ref)
size = ctypes.c_size_t(0)
val_p = _ldb.leveldb_get(self._db.ref, options, key, len(key),
ctypes.byref(size), ctypes.byref(error))
if bool(val_p):
val = ctypes.string_at(val_p, size.value)
_ldb.leveldb_free(ctypes.cast(val_p, ctypes.c_void_p))
else:
val = None
_ldb.leveldb_readoptions_destroy(options)
_checkError(error)
return val
# pylint: disable=W0212
示例10
def approximateDiskSizes(self, *ranges):
if self._snapshot is not None:
raise TypeError("cannot calculate disk sizes on leveldb snapshot")
assert len(ranges) > 0
key_type = ctypes.c_void_p * len(ranges)
len_type = ctypes.c_size_t * len(ranges)
start_keys, start_lens = key_type(), len_type()
end_keys, end_lens = key_type(), len_type()
sizes = (ctypes.c_uint64 * len(ranges))()
for i, range_ in enumerate(ranges):
assert isinstance(range_, tuple) and len(range_) == 2
assert isinstance(range_[0], str) and isinstance(range_[1], str)
start_keys[i] = ctypes.cast(range_[0], ctypes.c_void_p)
end_keys[i] = ctypes.cast(range_[1], ctypes.c_void_p)
start_lens[i], end_lens[i] = len(range_[0]), len(range_[1])
_ldb.leveldb_approximate_sizes(self._db.ref, len(ranges), start_keys,
start_lens, end_keys, end_lens, sizes)
return list(sizes)
示例11
def _contract_rho(bra, ket):
#:rho = numpy.einsum('pi,pi->p', bra.real, ket.real)
#:rho += numpy.einsum('pi,pi->p', bra.imag, ket.imag)
bra = bra.T
ket = ket.T
nao, ngrids = bra.shape
rho = numpy.empty(ngrids)
if not (bra.flags.c_contiguous and ket.flags.c_contiguous):
rho = numpy.einsum('ip,ip->p', bra.real, ket.real)
rho += numpy.einsum('ip,ip->p', bra.imag, ket.imag)
elif bra.dtype == numpy.double and ket.dtype == numpy.double:
libdft.VXC_dcontract_rho(rho.ctypes.data_as(ctypes.c_void_p),
bra.ctypes.data_as(ctypes.c_void_p),
ket.ctypes.data_as(ctypes.c_void_p),
ctypes.c_int(nao), ctypes.c_int(ngrids))
elif bra.dtype == numpy.complex128 and ket.dtype == numpy.complex128:
libdft.VXC_zcontract_rho(rho.ctypes.data_as(ctypes.c_void_p),
bra.ctypes.data_as(ctypes.c_void_p),
ket.ctypes.data_as(ctypes.c_void_p),
ctypes.c_int(nao), ctypes.c_int(ngrids))
else:
rho = numpy.einsum('ip,ip->p', bra.real, ket.real)
rho += numpy.einsum('ip,ip->p', bra.imag, ket.imag)
return rho
示例12
def __init__(self, mol, intor,
prescreen='CVHFnoscreen', qcondname=None, dmcondname=None):
'''If function "qcondname" is presented, the qcond (sqrt(integrals))
and will be initialized in __init__.
'''
intor = mol._add_suffix(intor)
self._this = ctypes.POINTER(_CVHFOpt)()
#print self._this.contents, expect ValueError: NULL pointer access
self._intor = intor
self._cintopt = make_cintopt(mol._atm, mol._bas, mol._env, intor)
self._dmcondname = dmcondname
natm = ctypes.c_int(mol.natm)
nbas = ctypes.c_int(mol.nbas)
libcvhf.CVHFinit_optimizer(ctypes.byref(self._this),
mol._atm.ctypes.data_as(ctypes.c_void_p), natm,
mol._bas.ctypes.data_as(ctypes.c_void_p), nbas,
mol._env.ctypes.data_as(ctypes.c_void_p))
self.prescreen = prescreen
if qcondname is not None:
self.init_cvhf_direct(mol, intor, qcondname)
示例13
def set_dm(self, dm, atm, bas, env):
if self._dmcondname is not None:
c_atm = numpy.asarray(atm, dtype=numpy.int32, order='C')
c_bas = numpy.asarray(bas, dtype=numpy.int32, order='C')
c_env = numpy.asarray(env, dtype=numpy.double, order='C')
natm = ctypes.c_int(c_atm.shape[0])
nbas = ctypes.c_int(c_bas.shape[0])
if isinstance(dm, numpy.ndarray) and dm.ndim == 2:
n_dm = 1
else:
n_dm = len(dm)
dm = numpy.asarray(dm, order='C')
ao_loc = make_loc(c_bas, self._intor)
fsetdm = getattr(libcvhf, self._dmcondname)
fsetdm(self._this,
dm.ctypes.data_as(ctypes.c_void_p), ctypes.c_int(n_dm),
ao_loc.ctypes.data_as(ctypes.c_void_p),
c_atm.ctypes.data_as(ctypes.c_void_p), natm,
c_bas.ctypes.data_as(ctypes.c_void_p), nbas,
c_env.ctypes.data_as(ctypes.c_void_p))
示例14
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)
示例15
def gen_cre_linkstr(strs, norb, nelec):
'''Given intermediates, the link table to generate input strs
'''
if nelec == norb:
return None
strs = numpy.asarray(strs, dtype=numpy.int64)
nvir = norb - nelec
nstrs = len(strs)
inter = numpy.empty((nstrs*nvir), dtype=numpy.int64)
libfci.SCIcre_uniq_strs.restype = ctypes.c_int
ninter = libfci.SCIcre_uniq_strs(inter.ctypes.data_as(ctypes.c_void_p),
strs.ctypes.data_as(ctypes.c_void_p),
ctypes.c_int(norb), ctypes.c_int(nelec),
ctypes.c_int(nstrs))
inter = numpy.asarray(sorted(set(inter[:ninter])), dtype=numpy.int64)
ninter = len(inter)
link_index = numpy.zeros((ninter,nelec+1,4), dtype=numpy.int32)
libfci.SCIcre_linkstr(link_index.ctypes.data_as(ctypes.c_void_p),
ctypes.c_int(norb), ctypes.c_int(nelec),
ctypes.c_int(nstrs), ctypes.c_int(ninter),
strs.ctypes.data_as(ctypes.c_void_p),
inter.ctypes.data_as(ctypes.c_void_p))
return link_index
示例16
def make_hdiag(h1e, eri, ci_strs, norb, nelec):
ci_coeff, nelec, ci_strs = _unpack(None, nelec, ci_strs)
na = len(ci_strs[0])
nb = len(ci_strs[1])
hdiag = numpy.empty(na*nb)
h1e = numpy.asarray(h1e, order='C')
eri = ao2mo.restore(1, eri, norb)
jdiag = numpy.asarray(numpy.einsum('iijj->ij',eri), order='C')
kdiag = numpy.asarray(numpy.einsum('ijji->ij',eri), order='C')
c_h1e = h1e.ctypes.data_as(ctypes.c_void_p)
c_jdiag = jdiag.ctypes.data_as(ctypes.c_void_p)
c_kdiag = kdiag.ctypes.data_as(ctypes.c_void_p)
occslsta = cistring._strs2occslst(ci_strs[0], norb)
occslstb = cistring._strs2occslst(ci_strs[1], norb)
libfci.FCImake_hdiag_uhf(hdiag.ctypes.data_as(ctypes.c_void_p),
c_h1e, c_h1e, c_jdiag, c_jdiag, c_jdiag, c_kdiag, c_kdiag,
ctypes.c_int(norb),
ctypes.c_int(na), ctypes.c_int(nb),
ctypes.c_int(nelec[0]), ctypes.c_int(nelec[1]),
occslsta.ctypes.data_as(ctypes.c_void_p),
occslstb.ctypes.data_as(ctypes.c_void_p))
return hdiag
示例17
def gen_cre_str_index_o1(orb_list, nelec):
'''C implementation of gen_cre_str_index function'''
norb = len(orb_list)
assert(nelec < norb)
strs = make_strings(orb_list, nelec)
if isinstance(strs, OIndexList):
raise NotImplementedError('System with 64 orbitals or more')
strs = numpy.array(strs, dtype=numpy.int64)
na = strs.shape[0]
link_index = numpy.empty((len(strs),norb-nelec,4), dtype=numpy.int32)
libfci.FCIcre_str_index(link_index.ctypes.data_as(ctypes.c_void_p),
ctypes.c_int(norb), ctypes.c_int(na),
ctypes.c_int(nelec),
strs.ctypes.data_as(ctypes.c_void_p))
return link_index
示例18
def gen_des_str_index_o1(orb_list, nelec):
'''C implementation of gen_des_str_index function'''
assert(nelec > 0)
strs = make_strings(orb_list, nelec)
if isinstance(strs, OIndexList):
raise NotImplementedError('System with 64 orbitals or more')
strs = numpy.array(strs, dtype=numpy.int64)
norb = len(orb_list)
na = strs.shape[0]
link_index = numpy.empty((len(strs),nelec,4), dtype=numpy.int32)
libfci.FCIdes_str_index(link_index.ctypes.data_as(ctypes.c_void_p),
ctypes.c_int(norb), ctypes.c_int(na),
ctypes.c_int(nelec),
strs.ctypes.data_as(ctypes.c_void_p))
return link_index
示例19
def contract_1e(f1e, fcivec, norb, nelec, link_index=None):
fcivec = numpy.asarray(fcivec, order='C')
link_index = _unpack(norb, nelec, link_index)
na, nlink = link_index.shape[:2]
assert(fcivec.size == na**2)
ci1 = numpy.empty_like(fcivec)
f1e_tril = lib.pack_tril(f1e)
libfci.FCIcontract_1e_spin0(f1e_tril.ctypes.data_as(ctypes.c_void_p),
fcivec.ctypes.data_as(ctypes.c_void_p),
ci1.ctypes.data_as(ctypes.c_void_p),
ctypes.c_int(norb), ctypes.c_int(na),
ctypes.c_int(nlink),
link_index.ctypes.data_as(ctypes.c_void_p))
# no *.5 because FCIcontract_2e_spin0 only compute half of the contraction
return lib.transpose_sum(ci1, inplace=True).reshape(fcivec.shape)
# Note eri is NOT the 2e hamiltonian matrix, the 2e hamiltonian is
# h2e = eri_{pq,rs} p^+ q r^+ s
# = (pq|rs) p^+ r^+ s q - (pq|rs) \delta_{qr} p^+ s
# so eri is defined as
# eri_{pq,rs} = (pq|rs) - (1/Nelec) \sum_q (pq|qs)
# to restore the symmetry between pq and rs,
# eri_{pq,rs} = (pq|rs) - (.5/Nelec) [\sum_q (pq|qs) + \sum_p (pq|rp)]
# Please refer to the treatment in direct_spin1.absorb_h1e
# the input fcivec should be symmetrized
示例20
def contract_2e(eri, fcivec, norb, nelec, link_index=None):
fcivec = numpy.asarray(fcivec, order='C')
eri = ao2mo.restore(4, eri, norb)
lib.transpose_sum(eri, inplace=True)
eri *= .5
link_index = _unpack(norb, nelec, link_index)
na, nlink = link_index.shape[:2]
assert(fcivec.size == na**2)
ci1 = numpy.empty((na,na))
libfci.FCIcontract_2e_spin0(eri.ctypes.data_as(ctypes.c_void_p),
fcivec.ctypes.data_as(ctypes.c_void_p),
ci1.ctypes.data_as(ctypes.c_void_p),
ctypes.c_int(norb), ctypes.c_int(na),
ctypes.c_int(nlink),
link_index.ctypes.data_as(ctypes.c_void_p))
# no *.5 because FCIcontract_2e_spin0 only compute half of the contraction
return lib.transpose_sum(ci1, inplace=True).reshape(fcivec.shape)
示例21
def contract_2e(eri, fcivec, norb, nelec, link_index=None):
fcivec = numpy.asarray(fcivec, order='C')
g2e_aa = ao2mo.restore(4, eri[0], norb)
g2e_ab = ao2mo.restore(4, eri[1], norb)
g2e_bb = ao2mo.restore(4, eri[2], norb)
link_indexa, link_indexb = direct_spin1._unpack(norb, nelec, link_index)
na, nlinka = link_indexa.shape[:2]
nb, nlinkb = link_indexb.shape[:2]
assert(fcivec.size == na*nb)
ci1 = numpy.empty_like(fcivec)
libfci.FCIcontract_uhf2e(g2e_aa.ctypes.data_as(ctypes.c_void_p),
g2e_ab.ctypes.data_as(ctypes.c_void_p),
g2e_bb.ctypes.data_as(ctypes.c_void_p),
fcivec.ctypes.data_as(ctypes.c_void_p),
ci1.ctypes.data_as(ctypes.c_void_p),
ctypes.c_int(norb),
ctypes.c_int(na), ctypes.c_int(nb),
ctypes.c_int(nlinka), ctypes.c_int(nlinkb),
link_indexa.ctypes.data_as(ctypes.c_void_p),
link_indexb.ctypes.data_as(ctypes.c_void_p))
return ci1
示例22
def type1_by_shell(mol, shls, cart=False):
li = mol.bas_angular(shls[0])
lj = mol.bas_angular(shls[1])
if cart:
fn = libecp.ECPtype1_cart
di = (li+1)*(li+2)//2 * mol.bas_nctr(shls[0])
dj = (lj+1)*(lj+2)//2 * mol.bas_nctr(shls[1])
else:
fn = libecp.ECPtype1_sph
di = (li*2+1) * mol.bas_nctr(shls[0])
dj = (lj*2+1) * mol.bas_nctr(shls[1])
buf = numpy.empty((di,dj), order='F')
cache = numpy.empty(buf.size*5)
fn(buf.ctypes.data_as(ctypes.c_void_p),
(ctypes.c_int*2)(*shls),
mol._ecpbas.ctypes.data_as(ctypes.c_void_p),
ctypes.c_int(len(mol._ecpbas)),
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), lib.c_null_ptr(),
cache.ctypes.data_as(ctypes.c_void_p))
return buf
示例23
def type2_by_shell(mol, shls, cart=False):
li = mol.bas_angular(shls[0])
lj = mol.bas_angular(shls[1])
if cart:
fn = libecp.ECPtype2_cart
di = (li+1)*(li+2)//2 * mol.bas_nctr(shls[0])
dj = (lj+1)*(lj+2)//2 * mol.bas_nctr(shls[1])
else:
fn = libecp.ECPtype2_sph
di = (li*2+1) * mol.bas_nctr(shls[0])
dj = (lj*2+1) * mol.bas_nctr(shls[1])
buf = numpy.empty((di,dj), order='F')
cache = numpy.empty(buf.size*5)
fn(buf.ctypes.data_as(ctypes.c_void_p),
(ctypes.c_int*2)(*shls),
mol._ecpbas.ctypes.data_as(ctypes.c_void_p),
ctypes.c_int(len(mol._ecpbas)),
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), lib.c_null_ptr(),
cache.ctypes.data_as(ctypes.c_void_p))
return buf
示例24
def so_by_shell(mol, shls):
'''Spin-orbit coupling ECP in spinor basis
i/2 <Pauli_matrix dot l U(r)>
'''
li = mol.bas_angular(shls[0])
lj = mol.bas_angular(shls[1])
di = (li*4+2) * mol.bas_nctr(shls[0])
dj = (lj*4+2) * mol.bas_nctr(shls[1])
bas = numpy.vstack((mol._bas, mol._ecpbas))
mol._env[AS_ECPBAS_OFFSET] = len(mol._bas)
mol._env[AS_NECPBAS] = len(mol._ecpbas)
buf = numpy.empty((di,dj), order='F', dtype=numpy.complex128)
cache = numpy.empty(buf.size*48)
fn = libecp.ECPso_spinor
fn(buf.ctypes.data_as(ctypes.c_void_p),
(ctypes.c_int*2)(di, dj),
(ctypes.c_int*2)(*shls),
mol._atm.ctypes.data_as(ctypes.c_void_p), ctypes.c_int(mol.natm),
bas.ctypes.data_as(ctypes.c_void_p), ctypes.c_int(mol.nbas),
mol._env.ctypes.data_as(ctypes.c_void_p), lib.c_null_ptr(),
cache.ctypes.data_as(ctypes.c_void_p))
return buf
示例25
def make_cintopt(atm, bas, env, intor):
intor = intor.replace('_sph','').replace('_cart','').replace('_spinor','')
c_atm = numpy.asarray(atm, dtype=numpy.int32, order='C')
c_bas = numpy.asarray(bas, dtype=numpy.int32, order='C')
c_env = numpy.asarray(env, dtype=numpy.double, order='C')
natm = c_atm.shape[0]
nbas = c_bas.shape[0]
cintopt = lib.c_null_ptr()
# TODO: call specific ECP optimizers for each intor.
if intor[:3] == 'ECP':
foptinit = libcgto.ECPscalar_optimizer
foptinit(ctypes.byref(cintopt),
c_atm.ctypes.data_as(ctypes.c_void_p), ctypes.c_int(natm),
c_bas.ctypes.data_as(ctypes.c_void_p), ctypes.c_int(nbas),
c_env.ctypes.data_as(ctypes.c_void_p))
return ctypes.cast(cintopt, _ecpoptHandler)
else:
foptinit = getattr(libcgto, intor+'_optimizer')
foptinit(ctypes.byref(cintopt),
c_atm.ctypes.data_as(ctypes.c_void_p), ctypes.c_int(natm),
c_bas.ctypes.data_as(ctypes.c_void_p), ctypes.c_int(nbas),
c_env.ctypes.data_as(ctypes.c_void_p))
return ctypes.cast(cintopt, _cintoptHandler)
示例26
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
示例27
def run(self):
"""Run the server, whose behavior is like.
>>> while receive(x):
... if is_command x: controller(x)
... else if is_key_value x: updater(x)
"""
_ctrl_proto = ctypes.CFUNCTYPE(None, ctypes.c_int, ctypes.c_char_p, ctypes.c_void_p)
check_call(_LIB.MXKVStoreRunServer(self.handle, _ctrl_proto(self._controller()), None))
示例28
def _sync_copyfrom(self, source_array):
"""Performs a synchronized copy from the `source_array` to the current array.
This is called through ``x[:] = source_array``, where the `source_array`
is a `numpy.ndarray` or array-like object.
This function blocks until all the pending read/write operations with respect
to the current `NDArray` are finished and carry out the copy operation to the
current NDArray.
Parameters
----------
source_array : array_like
The data source we would like to copy from.
Example
-------
>>> a = mx.nd.array([1, 2])
>>> a.asnumpy()
array([ 1., 2.], dtype=float32)
>>> a[:] = np.array([3, 4])
>> a.asnumpy()
array([ 3., 4.], dtype=float32)
"""
if not isinstance(source_array, np.ndarray):
try:
source_array = np.array(source_array, dtype=self.dtype)
except:
raise TypeError('array must consist of array-like data,' +
'type %s is not supported' % str(type(array)))
source_array = np.asarray(source_array, dtype=self.dtype, order='C')
if source_array.shape != self.shape:
raise ValueError('Shape inconsistent: expected %s vs got %s'%(
str(source_array.shape), str(self.shape)))
check_call(_LIB.MXNDArraySyncCopyFromCPU(
self.handle,
source_array.ctypes.data_as(ctypes.c_void_p),
ctypes.c_size_t(source_array.size)))
示例29
def _dlpack_deleter(pycapsule):
pycapsule = ctypes.c_void_p(pycapsule)
if ctypes.pythonapi.PyCapsule_IsValid(pycapsule, _c_str_dltensor):
ptr = ctypes.c_void_p(
ctypes.pythonapi.PyCapsule_GetPointer(pycapsule, _c_str_dltensor))
check_call(_LIB.MXNDArrayCallDLPackDeleter(ptr))
示例30
def _ctype_key_value(keys, vals):
"""
Returns ctype arrays for the key-value args, and the whether string keys are used.
For internal use only.
"""
if isinstance(keys, (tuple, list)):
assert(len(keys) == len(vals))
c_keys = []
c_vals = []
use_str_keys = None
for key, val in zip(keys, vals):
c_key_i, c_val_i, str_keys_i = _ctype_key_value(key, val)
c_keys += c_key_i
c_vals += c_val_i
use_str_keys = str_keys_i if use_str_keys is None else use_str_keys
assert(use_str_keys == str_keys_i), "inconsistent types of keys detected."
c_keys_arr = c_array(ctypes.c_char_p, c_keys) if use_str_keys \
else c_array(ctypes.c_int, c_keys)
c_vals_arr = c_array(ctypes.c_void_p, c_vals)
return (c_keys_arr, c_vals_arr, use_str_keys)
assert(isinstance(keys, (int,) + string_types)), \
"unexpected type for keys: " + str(type(keys))
use_str_keys = isinstance(keys, string_types)
if isinstance(vals, NDArray):
c_keys = c_str_array([keys]) if use_str_keys \
else c_array_buf(ctypes.c_int, array('i', [keys]))
return (c_keys, c_handle_array([vals]), use_str_keys)
else:
for value in vals:
assert(isinstance(value, NDArray))
c_keys = c_str_array([keys] * len(vals)) if use_str_keys \
else c_array_buf(ctypes.c_int, array('i', [keys] * len(vals)))
return (c_keys, c_handle_array(vals), use_str_keys)