本文整理汇总了Python中numpy.promote_types函数的典型用法代码示例。如果您正苦于以下问题:Python promote_types函数的具体用法?Python promote_types怎么用?Python promote_types使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了promote_types函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _promote
def _promote(type1, type2):
if type2 is None:
return type1
if type1.shape is not None:
if not type1.shape == type2.shape:
raise Exception("We do not handle changes to dtypes that have shape")
return np.promote_types(type1.base, type2.base), type1.shape
return np.promote_types(type1, type2)
示例2: axpy
def axpy(self, alpha, x, ind=None, x_ind=None):
assert self.check_ind_unique(ind)
assert x.check_ind(x_ind)
assert self.dim == x.dim
assert self.len_ind(ind) == x.len_ind(x_ind) or x.len_ind(x_ind) == 1
assert isinstance(alpha, _INDEXTYPES) \
or isinstance(alpha, np.ndarray) and alpha.shape == (self.len_ind(ind),)
if self._refcount[0] > 1:
self._deep_copy()
if NUMPY_INDEX_QUIRK:
if self._len == 0 and hasattr(ind, '__len__'):
ind = None
if x._len == 0 and hasattr(x_ind, '__len__'):
x_ind = None
if np.all(alpha == 0):
return
B = x._array[:x._len] if x_ind is None else x._array[x_ind]
alpha_type = type(alpha)
alpha_dtype = alpha.dtype if alpha_type is np.ndarray else alpha_type
if self._array.dtype != alpha_dtype or self._array.dtype != B.dtype:
dtype = np.promote_types(self._array.dtype, alpha_dtype)
dtype = np.promote_types(dtype, B.dtype)
self._array = self._array.astype(dtype)
if np.all(alpha == 1):
if ind is None:
self._array[:self._len] += B
elif isinstance(ind, Number) and B.ndim == 2:
self._array[ind] += B.reshape((B.shape[1],))
else:
self._array[ind] += B
elif np.all(alpha == -1):
if ind is None:
self._array[:self._len] -= B
elif isinstance(ind, Number) and B.ndim == 2:
self._array[ind] -= B.reshape((B.shape[1],))
else:
self._array[ind] -= B
else:
if isinstance(alpha, np.ndarray):
alpha = alpha[:, np.newaxis]
if ind is None:
self._array[:self._len] += (B * alpha)
elif isinstance(ind, Number):
self._array[ind] += (B * alpha).reshape((-1,))
else:
self._array[ind] += (B * alpha)
示例3: full_cumsum
def full_cumsum(data, axis=None, dtype=None):
"""
A version of `numpy.cumsum` that includes the sum of the empty slice (zero). This
makes it satisfy the invariant::
cumsum(a)[i] == sum(a[:i])
which is a useful property to simplify the formula for the moving average. The result
will be one entry longer than *data* along *axis*.
"""
# All we need to do is construct a result array with the appropriate type and
# dimensions, and then feed a slice of it to cumsum, setting the rest to zero.
shape = list(data.shape)
if axis is None:
shape[0] += 1
else:
shape[axis] += 1
# Mimic cumsum's behavior with the dtype argument: use the original data type or
# the system's native word, whichever has the greater width. (This prevents us from
# attempting a cumulative sum using an 8-bit integer, for instance.)
if dtype is None:
dtype = np.promote_types(data.dtype, np.min_scalar_type(-sys.maxint))
out = np.zeros(shape, dtype)
s = axis_slice(axis)
np.cumsum(data, axis, dtype, out[s[1:]])
return out
示例4: get_volume_pixeldata
def get_volume_pixeldata(sorted_slices):
"""
the slice and intercept calculation can cause the slices to have different dtypes
we should get the correct dtype that can cover all of them
:type sorted_slices: list of slices
:param sorted_slices: sliced sored in the correct order to create volume
"""
slices = []
combined_dtype = None
for slice_ in sorted_slices:
slice_data = _get_slice_pixeldata(slice_)
slice_data = slice_data[numpy.newaxis, :, :]
slices.append(slice_data)
if combined_dtype is None:
combined_dtype = slice_data.dtype
else:
combined_dtype = numpy.promote_types(combined_dtype, slice_data.dtype)
# create the new volume with with the correct data
vol = numpy.concatenate(slices, axis=0)
# Done
vol = numpy.transpose(vol, (2, 1, 0))
return vol
示例5: _resample_coord
def _resample_coord(coord, src_coord, direction, target_points, interpolate):
if coord.ndim != 1:
raise iris.exceptions.NotYetImplementedError(
'Linear interpolation of multi-dimensional coordinates.')
coord_points = coord.points
if coord is src_coord:
dtype = coord_points.dtype
if dtype.kind == 'i':
dtype = np.promote_types(dtype, np.float16)
new_points = np.array(target_points, dtype=dtype)
else:
if getattr(src_coord, 'circular', False):
coord_points = np.append(coord_points, coord_points[0])
# If the source coordinate was monotonic decreasing, we need to
# flip this coordinate's values.
if direction == -1:
coord_points = iris.util.reverse(coord_points, axes=0)
new_points = interpolate(coord_points, target_points)
# Watch out for DimCoord instances that are no longer monotonic
# after the resampling.
try:
new_coord = coord.copy(new_points)
except ValueError:
new_coord = iris.coords.AuxCoord.from_coord(coord).copy(new_points)
return new_coord
示例6: generic
def generic(self, args, kws):
assert not kws
if len(args) == 1:
# 0-dim arrays return one result array
ary = args[0]
ndim = max(ary.ndim, 1)
retty = types.UniTuple(types.Array(types.intp, 1, 'C'), ndim)
return signature(retty, ary)
elif len(args) == 3:
cond, x, y = args
retdty = from_dtype(np.promote_types(
as_dtype(getattr(args[1], 'dtype', args[1])),
as_dtype(getattr(args[2], 'dtype', args[2]))))
if isinstance(cond, types.Array):
# array where()
if isinstance(x, types.Array) and isinstance(y, types.Array):
if (cond.ndim == x.ndim == y.ndim):
if x.layout == y.layout == cond.layout:
retty = types.Array(retdty, x.ndim, x.layout)
else:
retty = types.Array(retdty, x.ndim, 'C')
return signature(retty, *args)
else:
# x and y both scalar
retty = types.Array(retdty, cond.ndim, cond.layout)
return signature(retty, *args)
else:
# scalar where()
if not isinstance(x, types.Array):
retty = types.Array(retdty, 0, 'C')
return signature(retty, *args)
示例7: unify_pairs
def unify_pairs(self, first, second):
"""
Choose PyObject type as the abstract if we fail to determine a concrete
type.
"""
# TODO: should add an option to reject unsafe type conversion
d = self.type_compatibility(fromty=first, toty=second)
if d is None:
# Complex is not allowed to downcast implicitly.
# Need to try the other direction of implicit cast to find the
# most general type of the two.
first, second = second, first # swap operand order
d = self.type_compatibility(fromty=first, toty=second)
if d is None:
return types.pyobject
elif d == 'exact':
# Same type
return first
elif d == 'promote':
return second
elif d in ('safe', 'unsafe'):
assert first in types.number_domain
assert second in types.number_domain
a = numpy.dtype(str(first))
b = numpy.dtype(str(second))
# Just use NumPy coercion rules
sel = numpy.promote_types(a, b)
# Convert NumPy dtype back to Numba types
return getattr(types, str(sel))
elif d in 'int-tuple-coerce':
return types.UniTuple(dtype=types.intp, count=len(first))
else:
raise Exception("type_compatibility returned %s" % d)
示例8: _set_or_promote_dtype
def _set_or_promote_dtype(self, column_dtypes, c, dtype):
existing_dtype = column_dtypes.get(c)
if existing_dtype is None or existing_dtype != dtype:
# Promote ints to floats - as we can't easily represent NaNs
if np.issubdtype(dtype, int):
dtype = np.dtype('f8')
column_dtypes[c] = np.promote_types(column_dtypes.get(c, dtype), dtype)
示例9: unify_pairs
def unify_pairs(self, first, second):
"""
Choose PyObject type as the abstract if we fail to determine a concrete
type.
"""
# TODO: should add an option to reject unsafe type conversion
d = self.type_compatibility(fromty=first, toty=second)
if d is None:
return types.pyobject
elif d == 'exact':
# Same type
return first
elif d == 'promote':
return second
elif d in ('safe', 'unsafe'):
assert first in types.number_domain
assert second in types.number_domain
a = numpy.dtype(str(first))
b = numpy.dtype(str(second))
# Just use NumPy coercion rules
sel = numpy.promote_types(a, b)
# Convert NumPy dtype back to Numba types
return getattr(types, str(sel))
else:
raise Exception("type_compatibility returned %s" % d)
示例10: multiply_dm_dm
def multiply_dm_dm(matrix1, matrix2):
"""Multiply a block diagonal matrix by another diagonal matrix.
Parameters
----------
matrix1 : (nblocks, n, m) np.ndarray
An array containing `nblocks` diagonal blocks of size (`n`, `m`).
matrix2 : (nblocks, m, k) np.ndarray
An array containing `nblocks` diagonal blocks of size (`m`, `k`).
Returns
-------
nmatrix : (nblocks, n, k) np.ndarray
An array containing `nblocks` diagonal blocks of size (`n`, `k`).
"""
nblocks, n, m = matrix1.shape
k = matrix2.shape[2]
if matrix2.shape[:2] != (nblocks, m):
raise Exception("Shapes not compatible.")
# Check dtype
dt = np.promote_types(matrix1.dtype, matrix2.dtype)
nmatrix = np.empty((nblocks, n, k), dtype=dt)
for i in range(nblocks):
nmatrix[i] = np.dot(matrix1[i], matrix2[i])
return nmatrix
示例11: dtype
def dtype(self):
"""Return dtype of image data in file."""
# subblock data can be of different pixel type
dtype = self.filtered_subblock_directory[0].dtype[-2:]
for directory_entry in self.filtered_subblock_directory:
dtype = numpy.promote_types(dtype, directory_entry.dtype[-2:])
return dtype
示例12: append
def append(self, other, remove_from_other=False):
assert self.dim == other.dim
assert not remove_from_other or (other is not self and getattr(other, 'base', None) is not self)
if self._refcount[0] > 1:
self._deep_copy()
other_array = other.to_numpy()
len_other = len(other_array)
if len_other == 0:
return
if len_other <= self._array.shape[0] - self._len:
if self._array.dtype != other_array.dtype:
self._array = self._array.astype(np.promote_types(self._array.dtype, other_array.dtype))
self._array[self._len:self._len + len_other] = other_array
else:
self._array = np.append(self._array[:self._len], other_array, axis=0)
self._len += len_other
if remove_from_other:
if other.is_view:
del other.base[other.ind]
else:
del other[:]
示例13: tensordot
def tensordot(lhs, rhs, axes=2):
if isinstance(axes, Iterable):
left_axes, right_axes = axes
else:
left_axes = tuple(range(lhs.ndim - 1, lhs.ndim - axes - 1, -1))
right_axes = tuple(range(0, axes))
if isinstance(left_axes, int):
left_axes = (left_axes,)
if isinstance(right_axes, int):
right_axes = (right_axes,)
if isinstance(left_axes, list):
left_axes = tuple(left_axes)
if isinstance(right_axes, list):
right_axes = tuple(right_axes)
dt = np.promote_types(lhs.dtype, rhs.dtype)
left_index = list(alphabet[:lhs.ndim])
right_index = list(ALPHABET[:rhs.ndim])
out_index = left_index + right_index
for l, r in zip(left_axes, right_axes):
out_index.remove(right_index[r])
right_index[r] = left_index[l]
intermediate = atop(_tensordot, out_index,
lhs, left_index,
rhs, right_index, dtype=dt,
axes=(left_axes, right_axes))
result = intermediate.sum(axis=left_axes)
return result
示例14: test_basic
def test_basic(self):
a, b = self.a, self.b
x = eval("a @ b")
assert_equal(x.dtype,
np.promote_types(a.dtype, b.dtype))
assert_allclose(x.todense(),
np.dot(a.todense(), b.todense()), atol=1e-15)
示例15: _weightable_adj
def _weightable_adj(self, weight, copy):
weight = np.atleast_1d(weight)
adj = self._adj
res_dtype = np.promote_types(weight.dtype, adj.dtype)
if copy:
adj = adj.copy()
if res_dtype is not adj.dtype:
adj.data = adj.data.astype(res_dtype)
return adj