Python numpy.common_type() Examples
The following are 30
code examples of numpy.common_type().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
numpy
, or try the search function
.
Example #1
Source File: test_linalg.py From Mastering-Elasticsearch-7.0 with MIT License | 6 votes |
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)
Example #2
Source File: test_linalg.py From elasticintel with GNU General Public License v3.0 | 6 votes |
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)
Example #3
Source File: test_linalg.py From ImageFusion with MIT License | 6 votes |
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)
Example #4
Source File: test_linalg.py From mxnet-lambda with Apache License 2.0 | 6 votes |
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)
Example #5
Source File: test_linalg.py From coffeegrindsize with MIT License | 6 votes |
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)
Example #6
Source File: test_linalg.py From pySINDy with MIT License | 6 votes |
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)
Example #7
Source File: __init__.py From cupy with MIT License | 6 votes |
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
Example #8
Source File: test_arithmetic.py From predictive-maintenance-using-machine-learning with Apache License 2.0 | 6 votes |
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)
Example #9
Source File: test_linalg.py From predictive-maintenance-using-machine-learning with Apache License 2.0 | 6 votes |
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)
Example #10
Source File: test_linalg.py From GraphicDesignPatternByPython with MIT License | 6 votes |
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)
Example #11
Source File: test_linalg.py From Serverless-Deep-Learning-with-TensorFlow-and-AWS-Lambda with MIT License | 6 votes |
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)
Example #12
Source File: test_linalg.py From Computable with MIT License | 6 votes |
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)
Example #13
Source File: test_linalg.py From twitter-stock-recommendation with MIT License | 6 votes |
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)
Example #14
Source File: test_linalg.py From auto-alt-text-lambda-api with MIT License | 6 votes |
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)
Example #15
Source File: test_linalg.py From lambda-packs with MIT License | 6 votes |
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)
Example #16
Source File: test_linalg.py From keras-lambda with MIT License | 6 votes |
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)
Example #17
Source File: test_linalg.py From recruit with Apache License 2.0 | 6 votes |
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)
Example #18
Source File: random_test.py From tenpy with GNU General Public License v3.0 | 6 votes |
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
Example #19
Source File: test_linalg.py From vnpy_crypto with MIT License | 6 votes |
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)
Example #20
Source File: test_arithmetic.py From recruit with Apache License 2.0 | 6 votes |
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)
Example #21
Source File: test_quantity_non_ufuncs.py From Carnets with BSD 3-Clause "New" or "Revised" License | 5 votes |
def test_common_type(self): self.check(np.common_type)
Example #22
Source File: kproxy_supercell.py From pyscf with Apache License 2.0 | 5 votes |
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
Example #23
Source File: kproxy_supercell.py From pyscf with Apache License 2.0 | 5 votes |
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))
Example #24
Source File: test_common.py From pyscf with Apache License 2.0 | 5 votes |
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
Example #25
Source File: test_common.py From pyscf with Apache License 2.0 | 5 votes |
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
Example #26
Source File: test_common.py From pyscf with Apache License 2.0 | 5 votes |
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
Example #27
Source File: test_array_function.py From cupy with MIT License | 5 votes |
def test_array_function_common_type(self, xp): return numpy.common_type(xp.arange(2, dtype='f8'), xp.arange(2, dtype='f4'))
Example #28
Source File: mparray.py From mpnum with BSD 3-Clause "New" or "Revised" License | 5 votes |
def dtype(self): """Returns the dtype that should be returned by ``to_array``""" return np.common_type(*tuple(self._lt))
Example #29
Source File: utils.py From coffeegrindsize with MIT License | 4 votes |
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)
Example #30
Source File: utils.py From Carnets with BSD 3-Clause "New" or "Revised" License | 4 votes |
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)