本文整理汇总了Python中numba.numpy_support.as_dtype函数的典型用法代码示例。如果您正苦于以下问题:Python as_dtype函数的具体用法?Python as_dtype怎么用?Python as_dtype使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了as_dtype函数的18个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: _build_element_wise_ufunc_wrapper
def _build_element_wise_ufunc_wrapper(cres, signature):
'''Build a wrapper for the ufunc loop entry point given by the
compilation result object, using the element-wise signature.
'''
ctx = cres.target_context
library = cres.library
llvm_func = library.get_function(cres.fndesc.llvm_func_name)
env = None
if cres.objectmode:
# Get env
env = cres.environment
assert env is not None
ll_intp = cres.target_context.get_value_type(types.intp)
ll_pyobj = cres.target_context.get_value_type(types.pyobject)
envptr = lc.Constant.int(ll_intp, id(env)).inttoptr(ll_pyobj)
else:
envptr = None
wrapper = build_ufunc_wrapper(library, ctx, llvm_func, signature,
cres.objectmode, envptr, env)
ptr = library.get_pointer_to_function(wrapper.name)
# Get dtypes
dtypenums = [as_dtype(a).num for a in signature.args]
dtypenums.append(as_dtype(signature.return_type).num)
return dtypenums, ptr, env
开发者ID:Alexhuszagh,项目名称:numba,代码行数:27,代码来源:ufuncbuilder.py
示例2: build
def build(self, cres, signature):
# Buider wrapper for ufunc entry point
ctx = cres.target_context
library = cres.library
llvm_func = library.get_function(cres.fndesc.llvm_func_name)
env = None
if cres.objectmode:
# Get env
env = cres.environment
assert env is not None
ll_intp = cres.target_context.get_value_type(types.intp)
ll_pyobj = cres.target_context.get_value_type(types.pyobject)
envptr = lc.Constant.int(ll_intp, id(env)).inttoptr(ll_pyobj)
else:
envptr = None
wrapper = build_ufunc_wrapper(library, ctx, llvm_func, signature,
cres.objectmode, envptr)
ptr = library.get_pointer_to_function(wrapper.name)
# Get dtypes
dtypenums = [as_dtype(a).num for a in signature.args]
dtypenums.append(as_dtype(signature.return_type).num)
return dtypenums, ptr, env
开发者ID:molodiuc,项目名称:numba,代码行数:25,代码来源:ufuncbuilder.py
示例3: kernel_wrapper
def kernel_wrapper(values):
n = len(values)
inputs = [np.empty(n, dtype=numpy_support.as_dtype(tp))
for tp in argtypes]
output = np.empty(n, dtype=numpy_support.as_dtype(restype))
for i, vs in enumerate(values):
for v, inp in zip(vs, inputs):
inp[i] = v
args = [output] + inputs
kernel[int(math.ceil(n / 256)), 256](*args)
return list(output)
开发者ID:cpcloud,项目名称:numba,代码行数:11,代码来源:test_complex.py
示例4: check_round
def check_round(cfunc, values, inty, outty, decimals):
# Create input and output arrays of the right type
arr = values.astype(as_dtype(inty))
out = np.zeros_like(arr).astype(as_dtype(outty))
pyout = out.copy()
_fixed_np_round(arr, decimals, pyout)
cfunc(arr, decimals, out)
np.testing.assert_allclose(out, pyout)
# Output shape mismatch
with self.assertRaises(ValueError) as raises:
cfunc(arr, decimals, out[1:])
self.assertEqual(str(raises.exception),
"invalid output shape")
开发者ID:dboyliao,项目名称:numba,代码行数:13,代码来源:test_array_methods.py
示例5: _build_element_wise_ufunc_wrapper
def _build_element_wise_ufunc_wrapper(cres, signature):
'''Build a wrapper for the ufunc loop entry point given by the
compilation result object, using the element-wise signature.
'''
ctx = cres.target_context
library = cres.library
fname = cres.fndesc.llvm_func_name
with global_compiler_lock:
ptr = build_ufunc_wrapper(library, ctx, fname, signature,
cres.objectmode, cres)
# Get dtypes
dtypenums = [as_dtype(a).num for a in signature.args]
dtypenums.append(as_dtype(signature.return_type).num)
return dtypenums, ptr, cres.environment
开发者ID:numba,项目名称:numba,代码行数:16,代码来源:ufuncbuilder.py
示例6: test_hypot
def test_hypot(self, flags=enable_pyobj_flags):
pyfunc = hypot
x_types = [types.int64, types.uint64,
types.float32, types.float64]
x_values = [1, 2, 3, 4, 5, 6, .21, .34]
y_values = [x + 2 for x in x_values]
# Issue #563: precision issues with math.hypot() under Windows.
prec = 'single' if sys.platform == 'win32' else 'exact'
self.run_binary(pyfunc, x_types, x_values, y_values, flags, prec)
# Check that values that overflow in naive implementations do not
# in the numba impl
def naive_hypot(x, y):
return math.sqrt(x * x + y * y)
for fltty in (types.float32, types.float64):
cr = self.ccache.compile(pyfunc, (fltty, fltty), flags=flags)
cfunc = cr.entry_point
dt = numpy_support.as_dtype(fltty).type
val = dt(np.finfo(dt).max / 30.)
nb_ans = cfunc(val, val)
self.assertPreciseEqual(nb_ans, pyfunc(val, val), prec='single')
self.assertTrue(np.isfinite(nb_ans))
with warnings.catch_warnings():
warnings.simplefilter("error", RuntimeWarning)
self.assertRaisesRegexp(RuntimeWarning,
'overflow encountered in .*_scalars',
naive_hypot, val, val)
开发者ID:FedericoStra,项目名称:numba,代码行数:28,代码来源:test_mathlib.py
示例7: build
def build(self, cres):
"""
Returns (dtype numbers, function ptr, EnvironmentObject)
"""
_launch_threads()
_init()
# Build wrapper for ufunc entry point
ctx = cres.target_context
library = cres.library
signature = cres.signature
ptr, env = build_gufunc_wrapper(library, ctx, signature, self.sin,
self.sout, fndesc=cres.fndesc,
env=cres.environment)
# Get dtypes
dtypenums = []
for a in signature.args:
if isinstance(a, types.Array):
ty = a.dtype
else:
ty = a
dtypenums.append(as_dtype(ty).num)
return dtypenums, ptr, env
开发者ID:stuartarchibald,项目名称:numba,代码行数:25,代码来源:parallel.py
示例8: build
def build(self, cres):
"""
Returns (dtype numbers, function ptr, EnvironmentObject)
"""
# Buider wrapper for ufunc entry point
ctx = cres.target_context
library = cres.library
signature = cres.signature
llvm_func = library.get_function(cres.fndesc.llvm_func_name)
wrapper, env = build_gufunc_wrapper(library, ctx, llvm_func,
signature, self.sin, self.sout,
fndesc=cres.fndesc,
env=cres.environment)
ptr = library.get_pointer_to_function(wrapper.name)
# Get dtypes
dtypenums = []
for a in signature.args:
if isinstance(a, types.Array):
ty = a.dtype
else:
ty = a
dtypenums.append(as_dtype(ty).num)
return dtypenums, ptr, env
开发者ID:Alexhuszagh,项目名称:numba,代码行数:25,代码来源:ufuncbuilder.py
示例9: test_record_dtype_with_titles_roundtrip
def test_record_dtype_with_titles_roundtrip(self):
recdtype = np.dtype([(("title a", 'a'), np.float), ('b', np.float)])
nbtype = numpy_support.from_dtype(recdtype)
self.assertTrue(nbtype.is_title('title a'))
self.assertFalse(nbtype.is_title('a'))
self.assertFalse(nbtype.is_title('b'))
got = numpy_support.as_dtype(nbtype)
self.assertTrue(got, recdtype)
开发者ID:seibert,项目名称:numba,代码行数:8,代码来源:test_record_dtype.py
示例10: array_cumprod
def array_cumprod(context, builder, sig, args):
scalar_dtype = sig.return_type.dtype
dtype = as_dtype(scalar_dtype)
def array_cumprod_impl(arr):
size = 1
for i in arr.shape:
size = size * i
out = numpy.empty(size, dtype)
c = 1
for idx, v in enumerate(arr.flat):
c *= v
out[idx] = c
return out
res = context.compile_internal(builder, array_cumprod_impl, sig, args, locals=dict(c=scalar_dtype))
return impl_ret_new_ref(context, builder, sig.return_type, res)
开发者ID:MatthieuDartiailh,项目名称:numba,代码行数:17,代码来源:arraymath.py
示例11: roots_impl
def roots_impl(p):
# cast int vectors to float cf. numpy, this is a bit dicey as
# the roots could be complex which will fail anyway
ty = getattr(p, 'dtype', p)
if isinstance(ty, types.Integer):
cast_t = np.float64
else:
cast_t = np_support.as_dtype(ty)
def roots_impl(p):
# impl based on numpy:
# https://github.com/numpy/numpy/blob/master/numpy/lib/polynomial.py
if len(p.shape) != 1:
raise ValueError("Input must be a 1d array.")
non_zero = np.nonzero(p)[0]
if len(non_zero) == 0:
return np.zeros(0, dtype=cast_t)
tz = len(p) - non_zero[-1] - 1
# pull out the coeffs selecting between possible zero pads
p = p[int(non_zero[0]):int(non_zero[-1]) + 1]
n = len(p)
if n > 1:
# construct companion matrix, ensure fortran order
# to give to eigvals, write to upper diag and then
# transpose.
A = np.diag(np.ones((n - 2,), cast_t), 1).T
A[0, :] = -p[1:] / p[0] # normalize
roots = np.linalg.eigvals(A)
else:
roots = np.zeros(0, dtype=cast_t)
# add in additional zeros on the end if needed
if tz > 0:
return np.hstack((roots, np.zeros(tz, dtype=cast_t)))
else:
return roots
return roots_impl
开发者ID:FedericoStra,项目名称:numba,代码行数:45,代码来源:polynomial.py
示例12: build
def build(self, cres):
"""
Returns (dtype numbers, function ptr, EnvironmentObject)
"""
# Buider wrapper for ufunc entry point
signature = cres.signature
ptr, env = build_gufunc_wrapper(self.py_func, cres, self.sin, self.sout,
cache=self.cache)
# Get dtypes
dtypenums = []
for a in signature.args:
if isinstance(a, types.Array):
ty = a.dtype
else:
ty = a
dtypenums.append(as_dtype(ty).num)
return dtypenums, ptr, env
开发者ID:FedericoStra,项目名称:numba,代码行数:18,代码来源:ufuncbuilder.py
示例13: array
def array(self, shape, dtype):
dtype = numpy_support.as_dtype(dtype)
# Dynamic shared memory is requested with size 0 - this all shares the
# same underlying memory
if shape == 0:
# Count must be the maximum number of whole elements that fit in the
# buffer (Numpy complains if the buffer is not a multiple of the
# element size)
count = self._dynshared_size // dtype.itemsize
return np.frombuffer(self._dynshared.data, dtype=dtype, count=count)
# Otherwise, identify allocations by source file and line number
caller = traceback.extract_stack()[-2][0:2]
res = self._allocations.get(caller)
if res is None:
res = np.empty(shape, dtype)
self._allocations[caller] = res
return res
开发者ID:CaptainAL,项目名称:Spyder,代码行数:18,代码来源:kernelapi.py
示例14: test_pickling_vectorize
def test_pickling_vectorize(self):
@vectorize(['intp(intp)', 'float64(float64)'], target='cuda')
def cuda_vect(x):
return x * 2
# accommodate int representations in np.arange
npty = numpy_support.as_dtype(types.intp)
# get expected result
ary = np.arange(10, dtype=npty)
expected = cuda_vect(ary)
# first pickle
foo1 = pickle.loads(pickle.dumps(cuda_vect))
del cuda_vect
got1 = foo1(ary)
np.testing.assert_equal(expected, got1)
# second pickle
foo2 = pickle.loads(pickle.dumps(foo1))
del foo1
got2 = foo2(ary)
np.testing.assert_equal(expected, got2)
开发者ID:cpcloud,项目名称:numba,代码行数:20,代码来源:test_serialize.py
示例15: array
def array(self, shape, dtype):
dtype = numpy_support.as_dtype(dtype)
return np.empty(shape, dtype)
开发者ID:yuguen,项目名称:numba,代码行数:3,代码来源:kernelapi.py
示例16: check
def check(dtype, numba_type, code):
tp = numpy_support.from_dtype(dtype)
self.assertEqual(tp, numba_type)
self.assertEqual(tp.unit_code, code)
self.assertEqual(numpy_support.as_dtype(numba_type), dtype)
self.assertEqual(numpy_support.as_dtype(tp), dtype)
开发者ID:cpcloud,项目名称:numba,代码行数:6,代码来源:test_numpy_support.py
示例17: lstsq_impl
def lstsq_impl(a, b, rcond=-1.0):
ensure_lapack()
_check_linalg_matrix(a, "lstsq")
# B can be 1D or 2D.
_check_linalg_1_or_2d_matrix(b, "lstsq")
a_F_layout = a.layout == 'F'
b_F_layout = b.layout == 'F'
# the typing context is not easily accessible in `@overload` mode
# so type unification etc. is done manually below
a_np_dt = np_support.as_dtype(a.dtype)
b_np_dt = np_support.as_dtype(b.dtype)
np_shared_dt = np.promote_types(a_np_dt, b_np_dt)
nb_shared_dt = np_support.from_dtype(np_shared_dt)
# convert typing floats to np floats for use in the impl
r_type = getattr(nb_shared_dt, "underlying_float", nb_shared_dt)
if r_type.bitwidth == 32:
real_dtype = np.float32
else:
real_dtype = np.float64
# the lapack wrapper signature
numba_ez_gelsd_sig = types.intc(
types.char, # kind
types.intp, # m
types.intp, # n
types.intp, # nrhs
types.CPointer(nb_shared_dt), # a
types.intp, # lda
types.CPointer(nb_shared_dt), # b
types.intp, # ldb
types.CPointer(r_type), # S
types.float64, # rcond
types.CPointer(types.intc) # rank
)
# the lapack wrapper function
numba_ez_gelsd = types.ExternalFunction("numba_ez_gelsd",
numba_ez_gelsd_sig)
kind = ord(get_blas_kind(nb_shared_dt, "lstsq"))
# The following functions select specialisations based on
# information around 'b', a lot of this effort is required
# as 'b' can be either 1D or 2D, and then there are
# some optimisations available depending on real or complex
# space.
# get a specialisation for computing the number of RHS
b_nrhs = _get_compute_nrhs(b)
# get a specialised residual computation based on the dtype
compute_res = _get_res_impl(nb_shared_dt, real_dtype, b)
# b copy function
b_copy_in = _get_copy_in_b_impl(b)
# return blob function
b_ret = _get_compute_return_impl(b)
# check system is dimensionally valid function
check_dimensionally_valid = _get_check_lstsq_dimensionally_valid_impl(a, b)
def lstsq_impl(a, b, rcond=-1.0):
n = a.shape[-1]
m = a.shape[-2]
nrhs = b_nrhs(b)
# check the systems have no inf or NaN
_check_finite_matrix(a)
_check_finite_matrix(b)
# check the systems is dimensionally valid
check_dimensionally_valid(a, b)
minmn = min(m, n)
maxmn = max(m, n)
# a is destroyed on exit, copy it
acpy = a.astype(np_shared_dt)
if a_F_layout:
acpy = np.copy(acpy)
else:
acpy = np.asfortranarray(acpy)
# b is overwritten on exit with the solution, copy allocate
bcpy = np.empty((nrhs, maxmn), dtype=np_shared_dt).T
# specialised copy in due to b being 1 or 2D
b_copy_in(bcpy, b, nrhs)
# Allocate returns
s = np.empty(minmn, dtype=real_dtype)
rank_ptr = np.empty(1, dtype=np.int32)
r = numba_ez_gelsd(
#.........这里部分代码省略.........
开发者ID:MPOWER4RU,项目名称:numba,代码行数:101,代码来源:linalg.py
示例18: _stencil_wrapper
#.........这里部分代码省略.........
# Get loop ranges for each dimension, which could be either int
# or variable. In the latter case we'll use the extra neighborhood
# argument to the function.
ranges = []
for i in range(the_array.ndim):
if isinstance(kernel_size[i][0], int):
lo = kernel_size[i][0]
hi = kernel_size[i][1]
else:
lo = "{}[{}][0]".format(neighborhood_name, i)
hi = "{}[{}][1]".format(neighborhood_name, i)
ranges.append((lo, hi))
# If there are more than one relatively indexed arrays, add a call to
# a function that will raise an error if any of the relatively indexed
# arrays are of different size than the first input array.
if len(relatively_indexed) > 1:
func_text += " raise_if_incompatible_array_sizes(" + first_arg
for other_array in relatively_indexed:
if other_array != first_arg:
func_text += "," + other_array
func_text += ")\n"
# Get the shape of the first input array.
shape_name = ir_utils.get_unused_var_name("full_shape", name_var_table)
func_text += " {} = {}.shape\n".format(shape_name, first_arg)
# If we have to allocate the output array (the out argument was not used)
# then us numpy.full if the user specified a cval stencil decorator option
# or np.zeros if they didn't to allocate the array.
if result is None:
return_type_name = numpy_support.as_dtype(
return_type.dtype).type.__name__
if "cval" in self.options:
cval = self.options["cval"]
if return_type.dtype != typing.typeof.typeof(cval):
raise ValueError(
"cval type does not match stencil return type.")
out_init ="{} = np.full({}, {}, dtype=np.{})\n".format(
out_name, shape_name, cval, return_type_name)
else:
out_init ="{} = np.zeros({}, dtype=np.{})\n".format(
out_name, shape_name, return_type_name)
func_text += " " + out_init
else: # result is present, if cval is set then use it
if "cval" in self.options:
cval = self.options["cval"]
cval_ty = typing.typeof.typeof(cval)
if not self._typingctx.can_convert(cval_ty, return_type.dtype):
msg = "cval type does not match stencil return type."
raise ValueError(msg)
out_init = "{}[:] = {}\n".format(out_name, cval)
func_text += " " + out_init
offset = 1
# Add the loop nests to the new function.
for i in range(the_array.ndim):
for j in range(offset):
func_text += " "
# ranges[i][0] is the minimum index used in the i'th dimension
# but minimum's greater than 0 don't preclude any entry in the array.
# So, take the minimum of 0 and the minimum index found in the kernel
# and this will be a negative number (potentially -0). Then, we do
# unary - on that to get the positive offset in this dimension whose
开发者ID:numba,项目名称:numba,代码行数:67,代码来源:stencil.py
注:本文中的numba.numpy_support.as_dtype函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论