本文整理汇总了Python中numpy.promote_types方法的典型用法代码示例。如果您正苦于以下问题:Python numpy.promote_types方法的具体用法?Python numpy.promote_types怎么用?Python numpy.promote_types使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类numpy
的用法示例。
在下文中一共展示了numpy.promote_types方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_promote_types_endian
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import promote_types [as 别名]
def test_promote_types_endian(self):
# promote_types should always return native-endian types
assert_equal(np.promote_types('<i8', '<i8'), np.dtype('i8'))
assert_equal(np.promote_types('>i8', '>i8'), np.dtype('i8'))
assert_equal(np.promote_types('>i8', '>U16'), np.dtype('U21'))
assert_equal(np.promote_types('<i8', '<U16'), np.dtype('U21'))
assert_equal(np.promote_types('>U16', '>i8'), np.dtype('U21'))
assert_equal(np.promote_types('<U16', '<i8'), np.dtype('U21'))
assert_equal(np.promote_types('<S5', '<U8'), np.dtype('U8'))
assert_equal(np.promote_types('>S5', '>U8'), np.dtype('U8'))
assert_equal(np.promote_types('<U8', '<S5'), np.dtype('U8'))
assert_equal(np.promote_types('>U8', '>S5'), np.dtype('U8'))
assert_equal(np.promote_types('<U5', '<U8'), np.dtype('U8'))
assert_equal(np.promote_types('>U8', '>U5'), np.dtype('U8'))
assert_equal(np.promote_types('<M8', '<M8'), np.dtype('M8'))
assert_equal(np.promote_types('>M8', '>M8'), np.dtype('M8'))
assert_equal(np.promote_types('<m8', '<m8'), np.dtype('m8'))
assert_equal(np.promote_types('>m8', '>m8'), np.dtype('m8'))
示例2: __init__
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import promote_types [as 别名]
def __init__(self, endog, exog, offset=None, exposure=None, missing='none',
**kwargs):
super(CountModel, self).__init__(endog, exog, missing=missing,
offset=offset,
exposure=exposure, **kwargs)
if exposure is not None:
self.exposure = np.log(self.exposure)
self._check_inputs(self.offset, self.exposure, self.endog)
if offset is None:
delattr(self, 'offset')
if exposure is None:
delattr(self, 'exposure')
# promote dtype to float64 if needed
dt = np.promote_types(self.endog.dtype, np.float64)
self.endog = np.asarray(self.endog, dt)
dt = np.promote_types(self.exog.dtype, np.float64)
self.exog = np.asarray(self.exog, dt)
示例3: test_promote_types_endian
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import promote_types [as 别名]
def test_promote_types_endian(self):
# promote_types should always return native-endian types
assert_equal(np.promote_types('<i8', '<i8'), np.dtype('i8'))
assert_equal(np.promote_types('>i8', '>i8'), np.dtype('i8'))
assert_equal(np.promote_types('>i8', '>U16'), np.dtype('U16'))
assert_equal(np.promote_types('<i8', '<U16'), np.dtype('U16'))
assert_equal(np.promote_types('>U16', '>i8'), np.dtype('U16'))
assert_equal(np.promote_types('<U16', '<i8'), np.dtype('U16'))
assert_equal(np.promote_types('<S5', '<U8'), np.dtype('U8'))
assert_equal(np.promote_types('>S5', '>U8'), np.dtype('U8'))
assert_equal(np.promote_types('<U8', '<S5'), np.dtype('U8'))
assert_equal(np.promote_types('>U8', '>S5'), np.dtype('U8'))
assert_equal(np.promote_types('<U5', '<U8'), np.dtype('U8'))
assert_equal(np.promote_types('>U8', '>U5'), np.dtype('U8'))
assert_equal(np.promote_types('<M8', '<M8'), np.dtype('M8'))
assert_equal(np.promote_types('>M8', '>M8'), np.dtype('M8'))
assert_equal(np.promote_types('<m8', '<m8'), np.dtype('m8'))
assert_equal(np.promote_types('>m8', '>m8'), np.dtype('m8'))
示例4: common_type
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import promote_types [as 别名]
def common_type(*arrays):
"""Return a scalar type which is common to the input arrays.
.. seealso:: :func:`numpy.common_type`
"""
if len(arrays) == 0:
return numpy.float16
default_float_dtype = numpy.dtype('float64')
dtypes = []
for a in arrays:
if a.dtype.kind == 'b':
raise TypeError('can\'t get common type for non-numeric array')
elif a.dtype.kind in 'iu':
dtypes.append(default_float_dtype)
else:
dtypes.append(a.dtype)
return functools.reduce(numpy.promote_types, dtypes).type
示例5: promote_types
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import promote_types [as 别名]
def promote_types(dtype1, dtype2):
"""
Get the smallest type to which the given scalar types can be cast.
Args:
dtype1 (builtin):
dtype2 (builtin):
Returns:
A builtin datatype or None.
"""
nptype1 = nptype_from_builtin(dtype1)
nptype2 = nptype_from_builtin(dtype2)
# Circumvent the undesirable np type promotion:
# >> np.promote_types(np.float32, np.int)
# dtype('float64')
if np.issubdtype(nptype1, np.floating) and np.issubdtype(nptype2, np.signedinteger):
nppromoted = nptype1
elif np.issubdtype(nptype2, np.floating) and np.issubdtype(
nptype1, np.signedinteger
):
nppromoted = nptype2
else:
nppromoted = np.promote_types(nptype1, nptype2)
return numpy_type_to_builtin_type(nppromoted)
示例6: get_volume_pixeldata
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import promote_types [as 别名]
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
示例7: dot
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import promote_types [as 别名]
def dot(self, other):
"""Matrix/vector multiplication with another LookupArray"""
if not isinstance(other, LookupArray):
assert(self.shape[-1] == other.shape[0])
new_lookup = self.lookup[:-1]+[None,]*(other.ndim-1)
new_shape = self.shape[:-1]+other.shape[1:]
elif compatible_quantity_part(self.lookup[-2:], other.lookup[:2]):
new_lookup = self.lookup[:-2]+other.lookup[2:]
new_shape = self.shape[:-2]+other.shape[2:]
other = other.simple_view()
else:
raise NotImplementedError
if len(new_shape) == 0:
# handle the case of a scalar result
new_array = np.dot(self.simple_view(), other)
else:
new_array = LookupArray(lookup=new_lookup, shape=new_shape,
dtype=np.promote_types(self.dtype, other.dtype))
new_array.simple_view()[:] = np.dot(self.simple_view(), other)
return new_array
示例8: _set_or_promote_dtype
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import promote_types [as 别名]
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: _promote_struct_dtypes
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import promote_types [as 别名]
def _promote_struct_dtypes(dtype1, dtype2):
if not set(dtype1.names).issuperset(set(dtype2.names)):
raise Exception("Removing columns from dtype not handled")
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)
return np.dtype([(n, _promote(dtype1.fields[n][0], dtype2.fields.get(n, (None,))[0])) for n in dtype1.names])
示例10: _promote_types
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import promote_types [as 别名]
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
示例11: test_promote_types2
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import promote_types [as 别名]
def test_promote_types2(library):
ndarr = np.array(np.arange(1000), dtype=[('abc', 'float64')])
library.write('MYARR', ndarr[:800])
library.append('MYARR', ndarr[-200:].astype([('abc', 'int64')]))
saved_arr = library.read('MYARR').data
assert np.all(ndarr.astype([('abc', np.promote_types('float64', 'int64'))]) == saved_arr)
示例12: print_coercion_table
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import promote_types [as 别名]
def print_coercion_table(ntypes, inputfirstvalue, inputsecondvalue, firstarray, use_promote_types=False):
print('+', end=' ')
for char in ntypes:
print(char, end=' ')
print()
for row in ntypes:
if row == 'O':
rowtype = GenericObject
else:
rowtype = np.obj2sctype(row)
print(row, end=' ')
for col in ntypes:
if col == 'O':
coltype = GenericObject
else:
coltype = np.obj2sctype(col)
try:
if firstarray:
rowvalue = np.array([rowtype(inputfirstvalue)], dtype=rowtype)
else:
rowvalue = rowtype(inputfirstvalue)
colvalue = coltype(inputsecondvalue)
if use_promote_types:
char = np.promote_types(rowvalue.dtype, colvalue.dtype).char
else:
value = np.add(rowvalue, colvalue)
if isinstance(value, np.ndarray):
char = value.dtype.char
else:
char = np.dtype(type(value)).char
except ValueError:
char = '!'
except OverflowError:
char = '@'
except TypeError:
char = '#'
print(char, end=' ')
print()
示例13: test_dtype_promotion
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import promote_types [as 别名]
def test_dtype_promotion(self):
# datetime <op> datetime computes the metadata gcd
# timedelta <op> timedelta computes the metadata gcd
for mM in ['m', 'M']:
assert_equal(
np.promote_types(np.dtype(mM+'8[2Y]'), np.dtype(mM+'8[2Y]')),
np.dtype(mM+'8[2Y]'))
assert_equal(
np.promote_types(np.dtype(mM+'8[12Y]'), np.dtype(mM+'8[15Y]')),
np.dtype(mM+'8[3Y]'))
assert_equal(
np.promote_types(np.dtype(mM+'8[62M]'), np.dtype(mM+'8[24M]')),
np.dtype(mM+'8[2M]'))
assert_equal(
np.promote_types(np.dtype(mM+'8[1W]'), np.dtype(mM+'8[2D]')),
np.dtype(mM+'8[1D]'))
assert_equal(
np.promote_types(np.dtype(mM+'8[W]'), np.dtype(mM+'8[13s]')),
np.dtype(mM+'8[s]'))
assert_equal(
np.promote_types(np.dtype(mM+'8[13W]'), np.dtype(mM+'8[49s]')),
np.dtype(mM+'8[7s]'))
# timedelta <op> timedelta raises when there is no reasonable gcd
assert_raises(TypeError, np.promote_types,
np.dtype('m8[Y]'), np.dtype('m8[D]'))
assert_raises(TypeError, np.promote_types,
np.dtype('m8[M]'), np.dtype('m8[W]'))
# timedelta <op> timedelta may overflow with big unit ranges
assert_raises(OverflowError, np.promote_types,
np.dtype('m8[W]'), np.dtype('m8[fs]'))
assert_raises(OverflowError, np.promote_types,
np.dtype('m8[s]'), np.dtype('m8[as]'))
示例14: test_promote_types_strings
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import promote_types [as 别名]
def test_promote_types_strings(self):
assert_equal(np.promote_types('bool', 'S'), np.dtype('S5'))
assert_equal(np.promote_types('b', 'S'), np.dtype('S4'))
assert_equal(np.promote_types('u1', 'S'), np.dtype('S3'))
assert_equal(np.promote_types('u2', 'S'), np.dtype('S5'))
assert_equal(np.promote_types('u4', 'S'), np.dtype('S10'))
assert_equal(np.promote_types('u8', 'S'), np.dtype('S20'))
assert_equal(np.promote_types('i1', 'S'), np.dtype('S4'))
assert_equal(np.promote_types('i2', 'S'), np.dtype('S6'))
assert_equal(np.promote_types('i4', 'S'), np.dtype('S11'))
assert_equal(np.promote_types('i8', 'S'), np.dtype('S21'))
assert_equal(np.promote_types('bool', 'U'), np.dtype('U5'))
assert_equal(np.promote_types('b', 'U'), np.dtype('U4'))
assert_equal(np.promote_types('u1', 'U'), np.dtype('U3'))
assert_equal(np.promote_types('u2', 'U'), np.dtype('U5'))
assert_equal(np.promote_types('u4', 'U'), np.dtype('U10'))
assert_equal(np.promote_types('u8', 'U'), np.dtype('U20'))
assert_equal(np.promote_types('i1', 'U'), np.dtype('U4'))
assert_equal(np.promote_types('i2', 'U'), np.dtype('U6'))
assert_equal(np.promote_types('i4', 'U'), np.dtype('U11'))
assert_equal(np.promote_types('i8', 'U'), np.dtype('U21'))
assert_equal(np.promote_types('bool', 'S1'), np.dtype('S5'))
assert_equal(np.promote_types('bool', 'S30'), np.dtype('S30'))
assert_equal(np.promote_types('b', 'S1'), np.dtype('S4'))
assert_equal(np.promote_types('b', 'S30'), np.dtype('S30'))
assert_equal(np.promote_types('u1', 'S1'), np.dtype('S3'))
assert_equal(np.promote_types('u1', 'S30'), np.dtype('S30'))
assert_equal(np.promote_types('u2', 'S1'), np.dtype('S5'))
assert_equal(np.promote_types('u2', 'S30'), np.dtype('S30'))
assert_equal(np.promote_types('u4', 'S1'), np.dtype('S10'))
assert_equal(np.promote_types('u4', 'S30'), np.dtype('S30'))
assert_equal(np.promote_types('u8', 'S1'), np.dtype('S20'))
assert_equal(np.promote_types('u8', 'S30'), np.dtype('S30'))
示例15: _eig_worker
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import promote_types [as 别名]
def _eig_worker(hermitian, a, sort, UPLO='L'):
"""Worker for ``eig``, ``eigh``"""
if a.rank != 2 or a.shape[0] != a.shape[1]:
raise ValueError("expect a square matrix!")
a.legs[0].test_contractible(a.legs[1])
if np.any(a.qtotal != a.chinfo.make_valid()):
raise ValueError("Non-trivial qtotal -> Nilpotent. Not diagonizable!?")
piped_axes, a = a.as_completely_blocked() # ensure complete blocking
dtype = np.float if hermitian else np.complex
resw = np.zeros(a.shape[0], dtype=dtype)
resv = diag(1., a.legs[0], dtype=np.promote_types(dtype, a.dtype))
# w, v now default to 0 and the Identity
for qindices, block in zip(a._qdata, a._data): # non-zero blocks on the diagonal
if hermitian:
rw, rv = np.linalg.eigh(block, UPLO)
else:
rw, rv = np.linalg.eig(block)
if sort is not None: # apply sorting options
perm = argsort(rw, sort)
rw = np.take(rw, perm)
rv = np.take(rv, perm, axis=1)
qi = qindices[0] # both `a` and `resv` are sorted and share the same qindices
resv._data[qi] = rv # replace idendity block
resw[a.legs[0].get_slice(qi)] = rw # replace eigenvalues
if len(piped_axes) > 0:
resv = resv.split_legs(0) # the 'outer' facing leg is permuted back.
return resw, resv