• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python numpy.promote_types函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中numpy.promote_types函数的典型用法代码示例。如果您正苦于以下问题:Python promote_types函数的具体用法?Python promote_types怎么用?Python promote_types使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了promote_types函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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)
开发者ID:JianfengYu,项目名称:arctic,代码行数:8,代码来源:_ndarray_store.py


示例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)
开发者ID:JuliaBru,项目名称:pymor,代码行数:52,代码来源:numpy.py


示例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
开发者ID:tfmartino,项目名称:STOcapstone-calibration,代码行数:31,代码来源:edgedetect.py


示例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
开发者ID:icometrix,项目名称:dicom2nifti,代码行数:25,代码来源:common.py


示例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
开发者ID:bblay,项目名称:iris,代码行数:28,代码来源:interpolate.py


示例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)
开发者ID:esc,项目名称:numba,代码行数:33,代码来源:npydecl.py


示例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)
开发者ID:genba,项目名称:numba,代码行数:34,代码来源:context.py


示例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)
开发者ID:Laeeth,项目名称:arctic,代码行数:7,代码来源:tickstore.py


示例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)
开发者ID:aburan28,项目名称:numba,代码行数:25,代码来源:context.py


示例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
开发者ID:TianlaiProject,项目名称:tlpipe,代码行数:33,代码来源:blockla.py


示例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
开发者ID:Lawrence-Moore,项目名称:NeuronTracing,代码行数:7,代码来源:czifile.py


示例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[:]
开发者ID:pymor,项目名称:pymor,代码行数:25,代码来源:numpy.py


示例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
开发者ID:fortizc,项目名称:dask,代码行数:33,代码来源:routines.py


示例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)
开发者ID:ev-br,项目名称:sparr,代码行数:7,代码来源:test_basic.py


示例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
开发者ID:all-umass,项目名称:graphs,代码行数:9,代码来源:adj.py


示例16: _update_edges

 def _update_edges(self, weights, copy=False):
   weights = np.asarray(weights)
   res_dtype = np.promote_types(weights.dtype, self._adj.dtype)
   adj = self._adj.astype(res_dtype, copy=copy)
   adj[adj != 0] = weights
   if copy:
     return DenseAdjacencyMatrixGraph(adj)
   self._adj = adj
   return self
开发者ID:all-umass,项目名称:graphs,代码行数:9,代码来源:adj.py


示例17: normalize_compare_value

 def normalize_compare_value(self, other):
     other_dtype = np.min_scalar_type(other)
     if other_dtype.kind in 'biuf':
         other_dtype = np.promote_types(self.dtype, other_dtype)
         ary = utils.scalar_broadcast_to(other, shape=len(self),
                                         dtype=other_dtype)
         return self.replace(data=Buffer(ary), dtype=ary.dtype)
     else:
         raise TypeError('cannot broadcast {}'.format(type(other)))
开发者ID:xennygrimmato,项目名称:pygdf,代码行数:9,代码来源:numerical.py


示例18: test_dense_sparse

 def test_dense_sparse(self):
     # dense @ sparse -> dense
     a, b = self.a.todense(), self.b
     x = eval("a @ b")
     assert_(isinstance(x, np.ndarray))
     assert_equal(x.dtype,
                  np.promote_types(a.dtype, b.dtype))
     assert_allclose(x,
                     np.dot(a, b.todense()), atol=1e-15)
开发者ID:ev-br,项目名称:sparr,代码行数:9,代码来源:test_basic.py


示例19: __isub__

 def __isub__(self, other):
     assert self.dim == other.dim
     if self._refcount[0] > 1:
         self._deep_copy()
     other_dtype = other.base._array.dtype if other.is_view else other._array.dtype
     common_dtype = np.promote_types(self._array.dtype, other_dtype)
     if self._array.dtype != common_dtype:
         self._array = self._array.astype(common_dtype)
     self._array[:self._len] -= other.base._array[other.ind] if other.is_view else other._array[:other._len]
     return self
开发者ID:pymor,项目名称:pymor,代码行数:10,代码来源:numpy.py


示例20: _promote_types

 def _promote_types(self, dtype, dtype_str):
     if dtype_str == str(dtype):
         return dtype
     prev_dtype = self._dtype(dtype_str)
     if dtype.names is None:
         rtn = np.promote_types(dtype, prev_dtype)
     else:
         rtn = _promote_struct_dtypes(dtype, prev_dtype)
     rtn = np.dtype(rtn, metadata=dict(dtype.metadata or {}))
     return rtn
开发者ID:JianfengYu,项目名称:arctic,代码行数:10,代码来源:_ndarray_store.py



注:本文中的numpy.promote_types函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python numpy.ptp函数代码示例发布时间:2022-05-27
下一篇:
Python numpy.product函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap