本文整理汇总了Python中numpy.common_type方法的典型用法代码示例。如果您正苦于以下问题:Python numpy.common_type方法的具体用法?Python numpy.common_type怎么用?Python numpy.common_type使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类numpy
的用法示例。
在下文中一共展示了numpy.common_type方法的11个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: dot_generalized
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import common_type [as 别名]
def dot_generalized(a, b):
a = asarray(a)
if a.ndim >= 3:
if a.ndim == b.ndim:
# matrix x matrix
new_shape = a.shape[:-1] + b.shape[-1:]
elif a.ndim == b.ndim + 1:
# matrix x vector
new_shape = a.shape[:-1]
else:
raise ValueError("Not implemented...")
r = np.empty(new_shape, dtype=np.common_type(a, b))
for c in itertools.product(*map(range, a.shape[:-2])):
r[c] = dot(a[c], b[c])
return r
else:
return dot(a, b)
示例2: test_df_arith_2d_array_collike_broadcasts
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import common_type [as 别名]
def test_df_arith_2d_array_collike_broadcasts(self,
all_arithmetic_operators):
# GH#23000
opname = all_arithmetic_operators
arr = np.arange(6).reshape(3, 2)
df = pd.DataFrame(arr, columns=[True, False], index=['A', 'B', 'C'])
collike = arr[:, [1]] # shape --> (nrows, 1)
assert collike.shape == (df.shape[0], 1)
exvals = {True: getattr(df[True], opname)(collike.squeeze()),
False: getattr(df[False], opname)(collike.squeeze())}
dtype = None
if opname in ['__rmod__', '__rfloordiv__']:
# Series ops may return mixed int/float dtypes in cases where
# DataFrame op will return all-float. So we upcast `expected`
dtype = np.common_type(*[x.values for x in exvals.values()])
expected = pd.DataFrame(exvals, columns=df.columns, index=df.index,
dtype=dtype)
result = getattr(df, opname)(collike)
tm.assert_frame_equal(result, expected)
示例3: random_MPS
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import common_type [as 别名]
def random_MPS(L, d, chimax, func=randmat.standard_normal_complex, bc='finite', form='B'):
site = Site(charges.LegCharge.from_trivial(d))
chi = [chimax] * (L + 1)
if bc == 'finite':
for i in range(L // 2 + 1):
chi[i] = chi[L - i] = min(chi[i], d**i)
Bs = []
for i in range(L):
B = func((d, chi[i], chi[i + 1]))
B /= np.sqrt(chi[i + 1]) * d
Bs.append(B)
dtype = np.common_type(*Bs)
psi = MPS.from_Bflat([site] * L, Bs, bc=bc, dtype=dtype, form=None)
if form is not None:
psi.canonical_form()
psi.convert_form(form)
return psi
示例4: common_type
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import common_type [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: remove_phase_difference
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import common_type [as 别名]
def remove_phase_difference(v1, v2, axis=0, threshold=1e-5):
"""Removes the phase difference between two vectors."""
dtype = numpy.common_type(numpy.asarray(v1), numpy.asarray(v2))
v1, v2 = numpy.array(v1, dtype=dtype), numpy.array(v2, dtype=dtype)
v1, v2 = pull_dim(v1, axis), pull_dim(v2, axis)
v2 /= phase_difference(v1, v2, threshold=threshold)[:, numpy.newaxis]
return v1, v2
示例6: sparse_transform
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import common_type [as 别名]
def sparse_transform(m, *args):
"""
Performs a sparse transform of a dense tensor.
Args:
m (ndarray): a tensor to transform;
*args: alternating indexes and bases to transform into;
Returns:
The transformed tensor.
"""
result = m
for i, (index, basis) in enumerate(zip(args[::2], args[1::2])):
if len(basis.shape) != 2:
raise ValueError("Transform {:d} is not a matrix: shape = {}".format(
i, repr(basis.shape)
))
if result.shape[index] != basis.shape[0]:
raise ValueError("Dimension mismatch of transform {:d}: m.shape[{:d}] = {:d} != basis.shape[0] = {:d}".format(
i, index, result.shape[index], basis.shape[0],
))
if "getcol" not in dir(basis):
raise ValueError("No 'getcol' in the transform matrix {:d}: not a CSC sparse matrix?")
result_shape = result.shape[:index] + (basis.shape[1],) + result.shape[index + 1:]
new_result = numpy.zeros(result_shape, numpy.common_type(*(
args[1::2] + (m,)
)))
for b2 in range(basis.shape[1]):
slice_b2 = (slice(None),) * index + (b2,)
col = basis.getcol(b2)
for b1 in col.nonzero()[0]:
slice_b1 = (slice(None),) * index + (b1,)
new_result[slice_b2] += col[b1, 0] * result[slice_b1]
result = new_result
return result
示例7: get_sparse_ov_transform
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import common_type [as 别名]
def get_sparse_ov_transform(oo, vv):
"""
Retrieves a sparse `ovov` transform out of sparse `oo` and `vv` transforms.
Args:
oo (ndarray): the transformation in the occupied space;
vv (ndarray): the transformation in the virtual space;
Returns:
The resulting matrix representing the sparse transform in the `ov` space.
"""
i, a = oo.shape
j, b = vv.shape
# If the input is dense the result is simply
# return (oo[:, numpy.newaxis, :, numpy.newaxis] * vv[numpy.newaxis, :, numpy.newaxis, :]).reshape(i*j, a*b)
result_data = numpy.zeros(oo.nnz * vv.nnz, dtype=numpy.common_type(oo, vv))
result_indices = numpy.zeros(len(result_data), dtype=int)
result_indptr = numpy.zeros(a * b + 1, dtype=int)
ptr_counter = 0
for i_a in range(a):
oo_col = oo.getcol(i_a)
assert tuple(oo_col.indptr.tolist()) == (0, len(oo_col.data))
i_i, oo_col_v = oo_col.indices, oo_col.data
for i_b in range(b):
vv_col = vv.getcol(i_b)
assert tuple(vv_col.indptr.tolist()) == (0, len(vv_col.data))
i_j, vv_col_v = vv_col.indices, vv_col.data
data_length = len(i_i) * len(i_j)
result_indices[ptr_counter:ptr_counter + data_length] = ((i_i * j)[:, numpy.newaxis] + i_j[numpy.newaxis, :]).reshape(-1)
result_data[ptr_counter:ptr_counter + data_length] = (oo_col_v[:, numpy.newaxis] * vv_col_v[numpy.newaxis, :]).reshape(-1)
result_indptr[i_a * b + i_b] = ptr_counter
ptr_counter += data_length
result_indptr[-1] = ptr_counter
return sparse.csc_matrix((result_data, result_indices, result_indptr))
示例8: dtype
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import common_type [as 别名]
def dtype(self):
"""Returns the dtype that should be returned by ``to_array``"""
return np.common_type(*tuple(self._lt))
示例9: test_array_function_common_type
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import common_type [as 别名]
def test_array_function_common_type(self, xp):
return numpy.common_type(xp.arange(2, dtype='f8'),
xp.arange(2, dtype='f4'))
示例10: test_common_type
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import common_type [as 别名]
def test_common_type(self):
self.check(np.common_type)
示例11: nulp_diff
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import common_type [as 别名]
def nulp_diff(x, y, dtype=None):
"""For each item in x and y, return the number of representable floating
points between them.
Parameters
----------
x : array_like
first input array
y : array_like
second input array
dtype : dtype, optional
Data-type to convert `x` and `y` to if given. Default is None.
Returns
-------
nulp : array_like
number of representable floating point numbers between each item in x
and y.
Examples
--------
# By definition, epsilon is the smallest number such as 1 + eps != 1, so
# there should be exactly one ULP between 1 and 1 + eps
>>> nulp_diff(1, 1 + np.finfo(x.dtype).eps)
1.0
"""
import numpy as np
if dtype:
x = np.array(x, dtype=dtype)
y = np.array(y, dtype=dtype)
else:
x = np.array(x)
y = np.array(y)
t = np.common_type(x, y)
if np.iscomplexobj(x) or np.iscomplexobj(y):
raise NotImplementedError("_nulp not implemented for complex array")
x = np.array(x, dtype=t)
y = np.array(y, dtype=t)
if not x.shape == y.shape:
raise ValueError("x and y do not have the same shape: %s - %s" %
(x.shape, y.shape))
def _diff(rx, ry, vdt):
diff = np.array(rx-ry, dtype=vdt)
return np.abs(diff)
rx = integer_repr(x)
ry = integer_repr(y)
return _diff(rx, ry, t)