Python numpy.find_common_type() Examples

The following are 30 code examples of numpy.find_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: distance.py    From GraphicDesignPatternByPython with MIT License 6 votes vote down vote up
def _nbool_correspond_ft_tf(u, v, w=None):
    if u.dtype == v.dtype == bool and w is None:
        not_u = ~u
        not_v = ~v
        nft = (not_u & v).sum()
        ntf = (u & not_v).sum()
    else:
        dtype = np.find_common_type([int], [u.dtype, v.dtype])
        u = u.astype(dtype)
        v = v.astype(dtype)
        not_u = 1.0 - u
        not_v = 1.0 - v
        if w is not None:
            not_u = w * not_u
            u = w * u
        nft = (not_u * v).sum()
        ntf = (u * not_v).sum()
    return (nft, ntf) 
Example #2
Source File: matfuncs.py    From lambda-packs with MIT License 6 votes vote down vote up
def __init__(self, *args, **kwargs):
        self._structure = kwargs.get('structure', None)
        for A in args:
            if len(A.shape) != 2 or A.shape[0] != A.shape[1]:
                raise ValueError(
                        'For now, the ProductOperator implementation is '
                        'limited to the product of multiple square matrices.')
        if args:
            n = args[0].shape[0]
            for A in args:
                for d in A.shape:
                    if d != n:
                        raise ValueError(
                                'The square matrices of the ProductOperator '
                                'must all have the same shape.')
            self.shape = (n, n)
            self.ndim = len(self.shape)
        self.dtype = np.find_common_type([x.dtype for x in args], [])
        self._operator_sequence = args 
Example #3
Source File: np_conserved.py    From tenpy with GNU General Public License v3.0 6 votes vote down vote up
def astype(self, dtype, copy=True):
        """Return copy with new dtype, upcasting all blocks in ``_data``.

        Parameters
        ----------
        dtype : convertible to a np.dtype
            The new data type.
            If None, deduce the new dtype as common type of ``self._data``.
        copy : bool
            Whether to make a copy of the blocks even if the type didn't change.

        Returns
        -------
        copy : :class:`Array`
            Deep copy of self with new dtype.
        """
        cp = self.copy(deep=False)  # manual deep copy: don't copy every block twice
        cp._qdata = cp._qdata.copy()
        if dtype is None:
            dtype = np.find_common_type([d.dtype for d in self._data], [])
        cp.dtype = dtype = np.dtype(dtype)
        if copy or dtype != self.dtype:
            cp._data = [d.astype(dtype, copy=copy) for d in self._data]
        return cp 
Example #4
Source File: mps.py    From tenpy with GNU General Public License v3.0 6 votes vote down vote up
def __init__(self, bra, ket, init_LP=None, init_RP=None, age_LP=0, age_RP=0):
        if ket is None:
            ket = bra
        if ket is not bra:
            ket._gauge_compatible_vL_vR(bra)  # ensure matching charges
        self.bra = bra
        self.ket = ket
        self.dtype = np.find_common_type([bra.dtype, ket.dtype], [])
        self.L = L = lcm(bra.L, ket.L)
        self._finite = bra.finite
        self._LP = [None] * L
        self._RP = [None] * L
        self._LP_age = [None] * L
        self._RP_age = [None] * L
        self._finite = self.ket.finite  # just for _to_valid_index
        if init_LP is None:
            init_LP = self.init_LP(0)
        self.set_LP(0, init_LP, age=age_LP)
        if init_RP is None:
            init_RP = self.init_RP(L - 1)
        self.set_RP(L - 1, init_RP, age=age_RP)
        self.test_sanity() 
Example #5
Source File: distance.py    From lambda-packs with MIT License 6 votes vote down vote up
def _nbool_correspond_ft_tf(u, v, w=None):
    if u.dtype == v.dtype == bool and w is None:
        not_u = ~u
        not_v = ~v
        nft = (not_u & v).sum()
        ntf = (u & not_v).sum()
    else:
        dtype = np.find_common_type([int], [u.dtype, v.dtype])
        u = u.astype(dtype)
        v = v.astype(dtype)
        not_u = 1.0 - u
        not_v = 1.0 - v
        if w is not None:
            not_u = w * not_u
            u = w * u
        nft = (not_u * v).sum()
        ntf = (u * not_v).sum()
    return (nft, ntf) 
Example #6
Source File: distance.py    From lambda-packs with MIT License 6 votes vote down vote up
def _nbool_correspond_all(u, v, w=None):
    if u.dtype == v.dtype == bool and w is None:
        not_u = ~u
        not_v = ~v
        nff = (not_u & not_v).sum()
        nft = (not_u & v).sum()
        ntf = (u & not_v).sum()
        ntt = (u & v).sum()
    else:
        dtype = np.find_common_type([int], [u.dtype, v.dtype])
        u = u.astype(dtype)
        v = v.astype(dtype)
        not_u = 1.0 - u
        not_v = 1.0 - v
        if w is not None:
            not_u = w * not_u
            u = w * u
        nff = (not_u * not_v).sum()
        nft = (not_u * v).sum()
        ntf = (u * not_v).sum()
        ntt = (u * v).sum()
    return (nff, nft, ntf, ntt) 
Example #7
Source File: mps.py    From tenpy with GNU General Public License v3.0 6 votes vote down vote up
def __init__(self, sites, Bs, SVs, bc='finite', form='B', norm=1.):
        self.sites = list(sites)
        self.chinfo = self.sites[0].leg.chinfo
        self.dtype = dtype = np.find_common_type([B.dtype for B in Bs], [])
        self.form = self._parse_form(form)
        self.bc = bc  # one of ``'finite', 'periodic', 'segment'``.
        self.norm = norm
        self.grouped = 1

        # make copies of Bs and SVs
        self._B = [B.astype(dtype, copy=True).itranspose(self._B_labels) for B in Bs]
        self._S = [None] * (self.L + 1)
        for i in range(self.L + 1)[self.nontrivial_bonds]:
            self._S[i] = np.array(SVs[i], dtype=np.float)
        if self.bc == 'infinite':
            self._S[-1] = self._S[0]
        elif self.bc == 'finite':
            self._S[0] = self._S[-1] = np.ones([1])
        self._transfermatrix_keep = 1
        self.test_sanity() 
Example #8
Source File: mpo.py    From tenpy with GNU General Public License v3.0 6 votes vote down vote up
def __init__(self, bra, H, ket, init_LP=None, init_RP=None, age_LP=0, age_RP=0):
        if ket is None:
            ket = bra
        if ket is not bra:
            ket._gauge_compatible_vL_vR(bra)  # ensure matching charges
        self.bra = bra
        self.ket = ket
        self.H = H
        self.L = L = lcm(lcm(bra.L, ket.L), H.L)
        self._finite = bra.finite
        self.dtype = np.find_common_type([bra.dtype, ket.dtype, H.dtype], [])
        self._LP = [None] * L
        self._RP = [None] * L
        self._LP_age = [None] * L
        self._RP_age = [None] * L
        if init_LP is None:
            init_LP = self.init_LP(0)
        self.set_LP(0, init_LP, age=age_LP)
        if init_RP is None:
            init_RP = self.init_RP(L - 1)
        self.set_RP(L - 1, init_RP, age=age_RP)
        self.test_sanity() 
Example #9
Source File: mpo.py    From tenpy with GNU General Public License v3.0 6 votes vote down vote up
def __init__(self,
                 sites,
                 Ws,
                 bc='finite',
                 IdL=None,
                 IdR=None,
                 max_range=None,
                 explicit_plus_hc=False):
        self.sites = list(sites)
        self.chinfo = self.sites[0].leg.chinfo
        self.dtype = dtype = np.find_common_type([W.dtype for W in Ws], [])
        self._W = [W.astype(dtype, copy=True) for W in Ws]
        self.IdL = self._get_Id(IdL, len(sites))
        self.IdR = self._get_Id(IdR, len(sites))
        self.grouped = 1
        self.bc = bc
        self.max_range = max_range
        self.explicit_plus_hc = explicit_plus_hc
        self.test_sanity() 
Example #10
Source File: matfuncs.py    From GraphicDesignPatternByPython with MIT License 6 votes vote down vote up
def __init__(self, *args, **kwargs):
        self._structure = kwargs.get('structure', None)
        for A in args:
            if len(A.shape) != 2 or A.shape[0] != A.shape[1]:
                raise ValueError(
                        'For now, the ProductOperator implementation is '
                        'limited to the product of multiple square matrices.')
        if args:
            n = args[0].shape[0]
            for A in args:
                for d in A.shape:
                    if d != n:
                        raise ValueError(
                                'The square matrices of the ProductOperator '
                                'must all have the same shape.')
            self.shape = (n, n)
            self.ndim = len(self.shape)
        self.dtype = np.find_common_type([x.dtype for x in args], [])
        self._operator_sequence = args 
Example #11
Source File: distance.py    From GraphicDesignPatternByPython with MIT License 6 votes vote down vote up
def _nbool_correspond_all(u, v, w=None):
    if u.dtype == v.dtype == bool and w is None:
        not_u = ~u
        not_v = ~v
        nff = (not_u & not_v).sum()
        nft = (not_u & v).sum()
        ntf = (u & not_v).sum()
        ntt = (u & v).sum()
    else:
        dtype = np.find_common_type([int], [u.dtype, v.dtype])
        u = u.astype(dtype)
        v = v.astype(dtype)
        not_u = 1.0 - u
        not_v = 1.0 - v
        if w is not None:
            not_u = w * not_u
            u = w * u
        nff = (not_u * not_v).sum()
        nft = (not_u * v).sum()
        ntf = (u * not_v).sum()
        ntt = (u * v).sum()
    return (nff, nft, ntf, ntt) 
Example #12
Source File: test_numerictypes.py    From GraphicDesignPatternByPython with MIT License 5 votes vote down vote up
def test_scalar_loses2(self):
        res = np.find_common_type(['f4', 'f4'], ['i8'])
        assert_(res == 'f4') 
Example #13
Source File: test_numerictypes.py    From GraphicDesignPatternByPython with MIT License 5 votes vote down vote up
def test_scalar_wins(self):
        res = np.find_common_type(['f4', 'f4', 'i2'], ['c8'])
        assert_(res == 'c8') 
Example #14
Source File: test_numerictypes.py    From GraphicDesignPatternByPython with MIT License 5 votes vote down vote up
def test_scalar_wins2(self):
        res = np.find_common_type(['u4', 'i4', 'i4'], ['f4'])
        assert_(res == 'f8') 
Example #15
Source File: test_numerictypes.py    From vnpy_crypto with MIT License 5 votes vote down vote up
def test_scalar_loses2(self):
        res = np.find_common_type(['f4', 'f4'], ['i8'])
        assert_(res == 'f4') 
Example #16
Source File: sputils.py    From Computable with MIT License 5 votes vote down vote up
def upcast(*args):
    """Returns the nearest supported sparse dtype for the
    combination of one or more types.

    upcast(t0, t1, ..., tn) -> T  where T is a supported dtype

    Examples
    --------

    >>> upcast('int32')
    <type 'numpy.int32'>
    >>> upcast('bool')
    <type 'numpy.bool_'>
    >>> upcast('int32','float32')
    <type 'numpy.float64'>
    >>> upcast('bool',complex,float)
    <type 'numpy.complex128'>

    """

    t = _upcast_memo.get(hash(args))
    if t is not None:
        return t

    if np.all([np.issubdtype(np.bool, arg) for arg in args]):
        # numpy 1.5.x compat - it gives int8 for
        # np.find_common_type([np.bool, np.bool)
        upcast = np.bool
    else:
        upcast = np.find_common_type(args, [])

    for t in supported_dtypes:
        if np.can_cast(upcast, t):
            _upcast_memo[hash(args)] = t
            return t

    raise TypeError('no supported conversion for types: %r' % (args,)) 
Example #17
Source File: test_numerictypes.py    From GraphicDesignPatternByPython with MIT License 5 votes vote down vote up
def test_scalar_loses1(self):
        res = np.find_common_type(['f4', 'f4', 'i2'], ['f8'])
        assert_(res == 'f4') 
Example #18
Source File: interface.py    From Computable with MIT License 5 votes vote down vote up
def _get_dtype(operators, dtypes=[]):
    for obj in operators:
        if obj is not None and hasattr(obj, 'dtype'):
            dtypes.append(obj.dtype)
    return np.find_common_type(dtypes, []) 
Example #19
Source File: ops.py    From Computable with MIT License 5 votes vote down vote up
def _arith_method_PANEL(op, name, str_rep=None, fill_zeros=None,
                        default_axis=None, **eval_kwargs):
    # copied from Series na_op above, but without unnecessary branch for
    # non-scalar
    def na_op(x, y):
        try:
            result = expressions.evaluate(op, str_rep, x, y,
                                          raise_on_error=True, **eval_kwargs)
        except TypeError:

            # TODO: might need to find_common_type here?
            result = pa.empty(len(x), dtype=x.dtype)
            mask = notnull(x)
            result[mask] = op(x[mask], y)
            result, changed = com._maybe_upcast_putmask(result, -mask, pa.NA)

        result = com._fill_zeros(result, y, fill_zeros)
        return result

    # work only for scalars
    def f(self, other):
        if not np.isscalar(other):
            raise ValueError('Simple arithmetic with %s can only be '
                             'done with scalar values' %
                             self._constructor.__name__)

        return self._combine(other, op)
    f.__name__ = name
    return f 
Example #20
Source File: test_regression.py    From Computable with MIT License 5 votes vote down vote up
def test_find_common_type_boolean(self):
        # Ticket #1695
        assert_(np.find_common_type([], ['?', '?']) == '?') 
Example #21
Source File: test_numerictypes.py    From Computable with MIT License 5 votes vote down vote up
def test_scalar_wins2(self):
        res = np.find_common_type(['u4', 'i4', 'i4'], ['f4'])
        assert_(res == 'f8') 
Example #22
Source File: test_numerictypes.py    From Computable with MIT License 5 votes vote down vote up
def test_scalar_wins(self):
        res = np.find_common_type(['f4', 'f4', 'i2'], ['c8'])
        assert_(res == 'c8') 
Example #23
Source File: test_numerictypes.py    From Computable with MIT License 5 votes vote down vote up
def test_scalar_loses2(self):
        res = np.find_common_type(['f4', 'f4'], ['i8'])
        assert_(res == 'f4') 
Example #24
Source File: test_numerictypes.py    From Computable with MIT License 5 votes vote down vote up
def test_scalar_loses1(self):
        res = np.find_common_type(['f4', 'f4', 'i2'], ['f8'])
        assert_(res == 'f4') 
Example #25
Source File: test_core.py    From Computable with MIT License 5 votes vote down vote up
def test_where_type(self):
        "Test the type conservation with where"
        x = np.arange(4, dtype=np.int32)
        y = np.arange(4, dtype=np.float32) * 2.2
        test = where(x > 1.5, y, x).dtype
        control = np.find_common_type([np.int32, np.float32], [])
        assert_equal(test, control) 
Example #26
Source File: internals.py    From vnpy_crypto with MIT License 5 votes vote down vote up
def _interleaved_dtype(blocks):
    if not len(blocks):
        return None

    dtype = find_common_type([b.dtype for b in blocks])

    # only numpy compat
    if isinstance(dtype, (PandasExtensionDtype, ExtensionDtype)):
        dtype = np.object

    return dtype 
Example #27
Source File: test_regression.py    From vnpy_crypto with MIT License 5 votes vote down vote up
def test_find_common_type_boolean(self):
        # Ticket #1695
        assert_(np.find_common_type([], ['?', '?']) == '?') 
Example #28
Source File: test_numerictypes.py    From vnpy_crypto with MIT License 5 votes vote down vote up
def test_scalar_wins2(self):
        res = np.find_common_type(['u4', 'i4', 'i4'], ['f4'])
        assert_(res == 'f8') 
Example #29
Source File: test_numerictypes.py    From vnpy_crypto with MIT License 5 votes vote down vote up
def test_scalar_wins(self):
        res = np.find_common_type(['f4', 'f4', 'i2'], ['c8'])
        assert_(res == 'c8') 
Example #30
Source File: test_numerictypes.py    From recruit with Apache License 2.0 5 votes vote down vote up
def test_scalar_loses1(self):
        res = np.find_common_type(['f4', 'f4', 'i2'], ['f8'])
        assert_(res == 'f4')