本文整理汇总了Python中numpy.ctypeslib.as_array函数的典型用法代码示例。如果您正苦于以下问题:Python as_array函数的具体用法?Python as_array怎么用?Python as_array使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了as_array函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: K2y
def K2y(self, X, X2, y):
res = zeros(X.shape[0])
if len(X.shape) == 1:
X = X.reshape((X.shape[0], 1))
if len(X2.shape) == 1:
X2 = X2.reshape((X2.shape[0], 1))
share_base = Array(ctypes.c_double, X.shape[0]*X.shape[1], lock=False)
share = as_array(share_base)
share = share.reshape(X.shape)
share[:, :] = X
share2_base = Array(ctypes.c_double, X2.shape[0]*X2.shape[1], lock=False)
share2 = as_array(share2_base)
share2 = share2.reshape(X2.shape)
share2[:, :] = X2
pool = Pool(self.num_proc, maxtasksperchild=50, initializer=initShared2, initargs=[share2, share])
cs = pool.imap(para_func2, ((i, X2.shape, X.shape, self.d, self.cnum) for i in xrange(self.m)), 10)
for c, c2 in cs:
for cls in unique(c):
if cls > -1:
res[c.flatten() == cls] += y[c2.flatten() == cls].sum()
res /= self.m
pool.close()
pool.join()
return res
开发者ID:mellorjc,项目名称:partition_kernel_gp,代码行数:26,代码来源:part_kernel.py
示例2: run
def run(self):
print "CameraStreamer.run(): [pid: {}, OS pid: {}]".format(self.pid, os.getpid())
# * Interpret shared objects properly (NOTE this needs to happen in the child process)
self.image = ctypeslib.as_array(self.imageObj.get_obj()) # get flattened image array
self.image.shape = ctypeslib.as_array(self.imageShapeObj.get_obj()) # restore original shape
# * Open camera and set desired capture properties
self.camera = cv2.VideoCapture(0)
if self.camera.isOpened():
result_width = self.camera.set(cv.CV_CAP_PROP_FRAME_WIDTH, camera_frame_width)
result_height = self.camera.set(cv.CV_CAP_PROP_FRAME_HEIGHT, camera_frame_height)
print "CameraStreamer.run(): Camera frame size set to {width}x{height} (result: {result_width}, {result_height})".format(width=camera_frame_width, height=camera_frame_height, result_width=result_width, result_height=result_height)
else:
print "CameraStreamer.run(): Unable to open camera; aborting..."
self.stayAliveObj.value = False
return
# * Keep reading frames into shared image until stopped or read error occurs
while self.stayAliveObj.value:
try:
#print "CameraStreamer.run(): Frame # {}, stay alive? {}".format(self.frameCountObj.value, self.stayAliveObj.value) # [debug]
isOkay, frame = self.camera.read()
if not isOkay:
self.stayAliveObj.value = False
self.frameCountObj.value = self.frameCountObj.value + 1
self.image[:] = frame
except KeyboardInterrupt:
self.stayAliveObj.value = False
# * Clean-up
self.camera.release()
开发者ID:napratin,项目名称:lumos,代码行数:31,代码来源:camstream.py
示例3: setup_stage
def setup_stage():
"""docstring for setup_stage
"""
import ctypes
e7xx = ctypes.windll.LoadLibrary('E7XX_GCS_DLL.dll')
try:
print "Connecting to stage"
id = e7xx.E7XX_ConnectRS232(1, 57600)
print "Initializing axes"
e7xx.E7XX_INI(id, '134')
print "initializing servos"
err = e7xx.E7XX_SVO(id, '134', ctl.as_ctypes(ones(4, dtype=int32)))
if err:
print "Servos initialized OK"
else:
import sys
sys.exit(e7xx.E7XX_GetError(id))
svo = ctl.as_ctypes(ones(4, dtype=int32))
err = e7xx.E7XX_qSVO(id, '134', svo)
if err:
print "Read servos OK"
else:
print e7xx.E7XX_GetError(id)
time.sleep(5)
while not(all(ctl.as_array(svo))):
e7xx.E7XX_qSVO(id, '134', svo)
print "Servo status: ", ctl.as_array(svo), ctl.as_array(svo).all()
time.sleep(1)
finally:
return e7xx, id
开发者ID:rflrob,项目名称:YildizLabCode,代码行数:35,代码来源:Imager.py
示例4: test_struct_array_pointer
def test_struct_array_pointer(self):
from ctypes import c_int16, Structure, pointer
class Struct(Structure):
_fields_ = [('a', c_int16)]
Struct3 = 3 * Struct
c_array = (2 * Struct3)(
Struct3(Struct(a=1), Struct(a=2), Struct(a=3)),
Struct3(Struct(a=4), Struct(a=5), Struct(a=6))
)
expected = np.array([
[(1,), (2,), (3,)],
[(4,), (5,), (6,)],
], dtype=[('a', np.int16)])
def check(x):
assert_equal(x.dtype, expected.dtype)
assert_equal(x, expected)
# all of these should be equivalent
check(as_array(c_array))
check(as_array(pointer(c_array), shape=()))
check(as_array(pointer(c_array[0]), shape=(2,)))
check(as_array(pointer(c_array[0][0]), shape=(2, 3)))
开发者ID:imshenny,项目名称:numpy,代码行数:27,代码来源:test_ctypeslib.py
示例5: test_populate_z_shells
def test_populate_z_shells(clib, formal_integral_model, p):
'''
Test the case where p > r[0]
'''
func = clib.populate_z
func.restype = ctypes.c_int64
func.argtypes = [
ctypes.POINTER(StorageModel), # storage
c_double, # p
ndpointer(dtype=np.float64), # oz
ndpointer(dtype=np.int64) # oshell_id
]
size = formal_integral_model.no_of_shells_i
r_inner = as_array(formal_integral_model.r_inner_i, (size,))
r_outer = as_array(formal_integral_model.r_outer_i, (size,))
p = r_inner[0] + (r_outer[-1] - r_inner[0]) * p
idx = np.searchsorted(r_outer, p, side='right')
oz = np.zeros(size * 2)
oshell_id = np.zeros_like(oz, dtype=np.int64)
offset = size - idx
expected_N = (offset) * 2
expected_oz = np.zeros_like(oz)
expected_oshell_id = np.zeros_like(oshell_id)
# Calculated way to determine which shells get hit
expected_oshell_id[:expected_N] = np.abs(
np.arange(0.5, expected_N, 1) - offset) - 0.5 + idx
expected_oz[0:offset] = 1 + calculate_z(
r_outer[np.arange(size, idx, -1) - 1],
p)
expected_oz[offset:expected_N] = 1 - calculate_z(
r_outer[np.arange(idx, size, 1)],
p)
N = func(
formal_integral_model,
p,
oz,
oshell_id
)
assert N == expected_N
ntest.assert_allclose(
oshell_id,
expected_oshell_id
)
ntest.assert_allclose(
oz,
expected_oz,
atol=1e-5
)
开发者ID:rcthomas,项目名称:tardis,代码行数:59,代码来源:test_formal_integral.py
示例6: test_array
def test_array(self):
from ctypes import c_int
pair_t = c_int * 2
a = as_array(pair_t(1, 2))
assert_equal(a.shape, (2,))
assert_array_equal(a, np.array([1, 2]))
a = as_array((pair_t * 3)(pair_t(1, 2), pair_t(3, 4), pair_t(5, 6)))
assert_equal(a.shape, (3, 2))
assert_array_equal(a, np.array([[1, 2], [3, 4], [5, 6]]))
开发者ID:imshenny,项目名称:numpy,代码行数:10,代码来源:test_ctypeslib.py
示例7: eval_wrapper
def eval_wrapper(instance, x, g, n, step):
"""Wrapper function to handle converting to numpy data structures"""
x = npct.as_array(x, (n,))
g = npct.as_array(g, (n,))
if instance:
instance = instance.contents
else:
instance = None
fx, gret = evaluate(instance, x, n, step)
g[:] = gret
return fx
开发者ID:sseemayer,项目名称:PyLBFGS,代码行数:13,代码来源:__init__.py
示例8: dumper
def dumper(nSamples,nlive,nPar,
physLive,posterior,paramConstr,
maxLogLike,logZ,logZerr,nullcontext):
if dump_callback:
# It's not clear what the desired MultiNest dumper callback
# syntax is... but this should pass back the right numpy arrays,
# without copies. Untested!
pc = as_array(paramConstr,shape=(nPar,4))
dump_callback(nSamples,nlive,nPar,
as_array(physLive,shape=(nPar+1,nlive)).T,
as_array(posterior,shape=(nPar+2,nSamples)).T,
(pc[0,:],pc[1,:],pc[2,:],pc[3,:]), # (mean,std,bestfit,map)
maxLogLike,logZ,logZerr)
开发者ID:PascalSteger,项目名称:darcoda,代码行数:14,代码来源:multinest.py
示例9: test_pointer
def test_pointer(self):
from ctypes import c_int, cast, POINTER
p = cast((c_int * 10)(*range(10)), POINTER(c_int))
a = as_array(p, shape=(10,))
assert_equal(a.shape, (10,))
assert_array_equal(a, np.arange(10))
a = as_array(p, shape=(2, 5))
assert_equal(a.shape, (2, 5))
assert_array_equal(a, np.arange(10).reshape((2, 5)))
# shape argument is required
assert_raises(TypeError, as_array, p)
开发者ID:imshenny,项目名称:numpy,代码行数:15,代码来源:test_ctypeslib.py
示例10: cMatrixToNumpy
def cMatrixToNumpy(x):
"""
Convert a ctypes 2d array (or matrix) into a numpy array for python use
:param x: thing to convert
:return: numpy.ndarray
"""
return numpc.as_array(x).copy()
开发者ID:AndrewAnnex,项目名称:SpiceyPy,代码行数:7,代码来源:support_types.py
示例11: global_tallies
def global_tallies():
"""Mean and standard deviation of the mean for each global tally.
Returns
-------
list of tuple
For each global tally, a tuple of (mean, standard deviation)
"""
ptr = POINTER(c_double)()
_dll.openmc_global_tallies(ptr)
array = as_array(ptr, (4, 3))
# Get sum, sum-of-squares, and number of realizations
sum_ = array[:, 1]
sum_sq = array[:, 2]
n = num_realizations()
# Determine mean
if n > 0:
mean = sum_ / n
else:
mean = sum_.copy()
# Determine standard deviation
nonzero = np.abs(mean) > 0
stdev = np.empty_like(mean)
stdev.fill(np.inf)
if n > 1:
stdev[nonzero] = np.sqrt((sum_sq[nonzero]/n - mean[nonzero]**2)/(n - 1))
return list(zip(mean, stdev))
开发者ID:mit-crpg,项目名称:openmc,代码行数:32,代码来源:tally.py
示例12: read
def read(filename):
'''
IIO: numpyarray = read(filename)
'''
from numpy import array, zeros, ctypeslib
from ctypes import c_int, c_float, c_void_p, POINTER, cast, byref
iioread = libiio.iio_read_image_float_vec
w=c_int()
h=c_int()
nch=c_int()
iioread.restype = c_void_p # it's like this
tptr = iioread(str(filename),byref(w),byref(h),byref(nch))
c_float_p = POINTER(c_float) # define a new type of pointer
ptr = cast(tptr, c_float_p)
#print w,h,nch
#nasty read data into array using buffer copy
#http://stackoverflow.com/questions/4355524/getting-data-from-ctypes-array-into-numpy
#http://docs.scipy.org/doc/numpy/reference/generated/numpy.frombuffer.html
# this numpy array uses the memory provided by the c library, which will be freed
data_tmp = ctypeslib.as_array( ptr, (h.value,w.value,nch.value) )
# so we copy it to the definitive array before the free
data = data_tmp.copy()
# free the memory
iiofreemem = libiio.freemem
iiofreemem(ptr)
return data
开发者ID:carlodef,项目名称:iio,代码行数:32,代码来源:piio.py
示例13: make_numpy_item
def make_numpy_item((v, shape)):
try:
v = ctypeslib.as_array(v)
v.shape = shape
except:
pass
return v
开发者ID:SKKx,项目名称:playdoh,代码行数:7,代码来源:shared.py
示例14: get_dm_list
def get_dm_list(self):
ndms = self.get_dm_count()
func = lib.dedisp_get_dm_list
c_float_p = C.POINTER(C.c_float)
func.restype = c_float_p
array_pointer = C.cast(func(self.plan),c_float_p)
return as_array(array_pointer,shape=(ndms,)).copy()
开发者ID:lgspitler,项目名称:psrgpude,代码行数:7,代码来源:dedisp.py
示例15: borrow_memory
def borrow_memory(param, memory):
"""
Spawn different processes with the shared memory
of your theano model's variables.
Inputs:
-------
param TensorSharedVariable : the Theano shared variable where
shared memory should be used instead.
memory multiprocessing.sharedctypes : the memory shared across processes (e.g.
from `wrap_params`)
Outputs:
--------
None
Usage
-----
For each process in the target function run the theano_borrow_memory
method on the parameters you want to have share memory across processes.
In this example we have a model called "mymodel" with parameters stored in
a list called "params". We loop through each theano shared variable and
call `theano_borrow_memory` on it to share memory across processes.
def spawn_model(path, wrapped_params):
# prevent recompilation and arbitrary locks
theano.config.reoptimize_unpickled_function = False
theano.gof.compilelock.set_lock_status(False)
# load your model from its pickled instance (from path)
mymodel = MyModel.load(path)
# for each parameter in your model
# apply the borrow memory strategy to replace
# the internal parameter's memory with the
# across-process memory
for param, memory in zip(mymodel.params, wrapped_params):
borrow_memory(param, memory)
# acquire your dataset (either through some smart shared memory
# or by reloading it for each process)
dataset, dataset_labels = acquire_dataset()
# then run your model forward in this process
epochs = 20
for epoch in range(epochs):
model.update_fun(dataset, dataset_labels)
See `borrow_all_memories` for list usage.
"""
param_value = ctypeslib.as_array(memory)
param_value.shape = param.get_value(True,True).shape
param.set_value(param_value, borrow=True)
开发者ID:BK-Yoo,项目名称:ee532-BrainIT-LSTM,代码行数:59,代码来源:shared_memory.py
示例16: mat_rowrange_mul
def mat_rowrange_mul(args):
# a little ugly, but allows running with a Pool
# which accept only 1 argument
a_row_domain, a_shape, b_shape, shared_a, shared_b, shared_c = args
# access shared memory object as numpy array, set dimensions
nd_c = ctypeslib.as_array(shared_c).reshape((a_shape[0],b_shape[1]))
nd_a = ctypeslib.as_array(shared_a).reshape(a_shape)
nd_b = ctypeslib.as_array(shared_b).reshape(b_shape)
# write answer to shared memory
# it would be better if numpy.dot could write "in-place"
nd_c[a_row_domain[0]:a_row_domain[1],:] = \
numpy.dot(nd_a[a_row_domain[0]:a_row_domain[1],:],nd_b)
return None
开发者ID:DaoHai,项目名称:parallel-python,代码行数:17,代码来源:mp_matmul_shared.py
示例17: K2
def K2(self, X, X2):
#if X.ndim == 0:
# X = X.reshape((1, 1))
#if X2.ndim == 0:
# X2 = X2.reshape((1, 1))
if X.ndim == 1:
X = X.reshape((X.shape[0], 1))
if X2.ndim == 1:
X2 = X2.reshape((X2.shape[0], 1))
if X.ndim == 0:
Xsh = 1
Xsh2 = 1
else:
Xsh = X.shape[0]
Xsh2 = X.shape[1]
if X2.ndim == 0:
X2sh = 1
X2sh2 = 1
else:
X2sh = X2.shape[0]
X2sh2 = X2.shape[1]
res = zeros((Xsh, X2sh))
share_base = Array(ctypes.c_double, Xsh*Xsh2, lock=False)
share = as_array(share_base)
share = share.reshape((Xsh, Xsh2))
share[:, :] = X
share2_base = Array(ctypes.c_double, X2sh*X2sh2, lock=False)
share2 = as_array(share2_base)
share2 = share2.reshape(X2.shape)
share2[:, :] = X2
pool = Pool(self.num_proc, maxtasksperchild=50, initializer=initShared2, initargs=[share2, share])
cs = pool.imap(para_func2, ((i, X2.shape, X.shape, self.d, self.cnum) for i in xrange(self.m)), 10)
for c, c2 in cs:
for i, c_v in enumerate(c):
for j, c_v2 in enumerate(c2):
if c_v == c_v2 and c_v != -1:
res[i, j] += 1.
res /= self.m
pool.close()
pool.join()
if X.ndim == 0:
res = res.flatten()
return res
开发者ID:mellorjc,项目名称:partition_kernel_gp,代码行数:44,代码来源:part_kernel.py
示例18: as_numpy
def as_numpy( data ):
'''maps data content as a numpy array'''
ptr, shape, typename = data.getValueVoidPtr()
type = ctypeFromName.get(typename,None)
if not type: raise Exception("can't map data of type " + typename)
array = ctypes.cast( ctypes.c_void_p(ptr), ctypes.POINTER(type))
return ctypeslib.as_array(array, shape )
开发者ID:151706061,项目名称:sofa,代码行数:10,代码来源:tool.py
示例19: make_numpy_item
def make_numpy_item((v, shape)):
if shape is not None:
try:
v = ctypeslib.as_array(v)
v.shape = shape
log_debug('converting common array to numpy array')
except:
log_debug('NOT converting common array to numpy array')
pass
return v
开发者ID:jpzk,项目名称:evopy,代码行数:10,代码来源:pool.py
示例20: main
def main():
ra = sharedctypes.RawArray("i", 4)
arr = ctypeslib.as_array(ra)
arr.shape = (2, 2)
p1 = Process(target=fill_arr, args=(arr[:1, :], 1))
p2 = Process(target=fill_arr, args=(arr[1:, :], 2))
p1.start()
p2.start()
p1.join()
p2.join()
print(arr)
开发者ID:PlamenStilyianov,项目名称:Python,代码行数:11,代码来源:m-process.py
注:本文中的numpy.ctypeslib.as_array函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论