Beispiel #1
0
    def test_type(self):
        # Check the type of the returned histogram
        a = np.arange(10) + .5
        h, b = histogram(a)
        assert_(np.issubdtype(h.dtype, np.integer))

        h, b = histogram(a, density=True)
        assert_(np.issubdtype(h.dtype, np.floating))

        h, b = histogram(a, weights=np.ones(10, int))
        assert_(np.issubdtype(h.dtype, np.integer))

        h, b = histogram(a, weights=np.ones(10, float))
        assert_(np.issubdtype(h.dtype, np.floating))
Beispiel #2
0
 def test_shape_and_dtype(self):
     sizes = (4, 5, 3, 2)
     # Test both lists and arrays
     for func in (range, np.arange):
         arrays = np.ix_(*[func(sz) for sz in sizes])
         for k, (a, sz) in enumerate(zip(arrays, sizes)):
             assert_equal(a.shape[k], sz)
             assert_(all(sh == 1 for j, sh in enumerate(a.shape) if j != k))
             assert_(np.issubdtype(a.dtype, np.integer))
Beispiel #3
0
 def test_large_types(self):
     for t in [np.int32, np.int64, np.float32, np.float64, np.longdouble]:
         a = t(51)
         b = a**4
         msg = "error with %r: got %r" % (t, b)
         if np.issubdtype(t, np.integer):
             assert_(b == 6765201, msg)
         else:
             assert_almost_equal(b, 6765201, err_msg=msg)
Beispiel #4
0
    def test_asfarray(self):
        a = asfarray(np.array([1, 2, 3]))
        assert_equal(a.__class__, np.ndarray)
        assert_(np.issubdtype(a.dtype, np.floating))

        # previously this would infer dtypes from arrays, unlike every single
        # other numpy function
        assert_raises(TypeError,
                      asfarray,
                      np.array([1, 2, 3]),
                      dtype=np.array(1.0))
Beispiel #5
0
def _round_ifneeded(arr, dtype):
    """
    Rounds arr inplace if destination dtype is integer.

    Parameters
    ----------
    arr : ndarray
        Input array.
    dtype : dtype
        The dtype of the destination array.

    """
    if np.issubdtype(dtype, np.integer):
        arr.round(out=arr)
Beispiel #6
0
 def test_objects(self):
     from decimal import Decimal
     p = np.poly1d([Decimal('4.0'), Decimal('3.0'), Decimal('2.0')])
     p2 = p * Decimal('1.333333333333333')
     assert_(p2[1] == Decimal("3.9999999999999990"))
     p2 = p.deriv()
     assert_(p2[1] == Decimal('8.0'))
     p2 = p.integ()
     assert_(p2[3] == Decimal("1.333333333333333333333333333"))
     assert_(p2[2] == Decimal('1.5'))
     assert_(np.issubdtype(p2.coeffs.dtype, np.object_))
     p = np.poly([Decimal(1), Decimal(2)])
     assert_equal(np.poly([Decimal(1), Decimal(2)]),
                  [1, Decimal(-3), Decimal(2)])
Beispiel #7
0
 def test_mixed_types(self):
     typelist = [
         np.int8, np.int16, np.float16, np.float32, np.float64, np.int8,
         np.int16, np.int32, np.int64
     ]
     for t1 in typelist:
         for t2 in typelist:
             a = t1(3)
             b = t2(2)
             result = a**b
             msg = ("error with %r and %r:"
                    "got %r, expected %r") % (t1, t2, result, 9)
             if np.issubdtype(np.dtype(result), np.integer):
                 assert_(result == 9, msg)
             else:
                 assert_almost_equal(result, 9, err_msg=msg)
Beispiel #8
0
 def __init__(self,
              dtype_or_func=None,
              default=None,
              missing_values=None,
              locked=False):
     # Defines a lock for upgrade
     self._locked = bool(locked)
     # No input dtype: minimal initialization
     if dtype_or_func is None:
         self.func = str2bool
         self._status = 0
         self.default = default or False
         dtype = np.dtype('bool')
     else:
         # Is the input a np.dtype ?
         try:
             self.func = None
             dtype = np.dtype(dtype_or_func)
         except TypeError:
             # dtype_or_func must be a function, then
             if not hasattr(dtype_or_func, '__call__'):
                 errmsg = ("The input argument `dtype` is neither a"
                           " function nor a dtype (got '%s' instead)")
                 raise TypeError(errmsg % type(dtype_or_func))
             # Set the function
             self.func = dtype_or_func
             # If we don't have a default, try to guess it or set it to
             # None
             if default is None:
                 try:
                     default = self.func('0')
                 except ValueError:
                     default = None
             dtype = self._getdtype(default)
         # Set the status according to the dtype
         _status = -1
         for (i, (deftype, func, default_def)) in enumerate(self._mapper):
             if np.issubdtype(dtype.type, deftype):
                 _status = i
                 if default is None:
                     self.default = default_def
                 else:
                     self.default = default
                 break
         # if a converter for the specific dtype is available use that
         last_func = func
         for (i, (deftype, func, default_def)) in enumerate(self._mapper):
             if dtype.type == deftype:
                 _status = i
                 last_func = func
                 if default is None:
                     self.default = default_def
                 else:
                     self.default = default
                 break
         func = last_func
         if _status == -1:
             # We never found a match in the _mapper...
             _status = 0
             self.default = default
         self._status = _status
         # If the input was a dtype, set the function to the last we saw
         if self.func is None:
             self.func = func
         # If the status is 1 (int), change the function to
         # something more robust.
         if self.func == self._mapper[1][1]:
             if issubclass(dtype.type, np.uint64):
                 self.func = np.uint64
             elif issubclass(dtype.type, np.int64):
                 self.func = np.int64
             else:
                 self.func = lambda x: int(float(x))
     # Store the list of strings corresponding to missing values.
     if missing_values is None:
         self.missing_values = set([''])
     else:
         if isinstance(missing_values, basestring):
             missing_values = missing_values.split(",")
         self.missing_values = set(list(missing_values) + [''])
     #
     self._callingfunction = self._strict_call
     self.type = self._dtypeortype(dtype)
     self._checked = False
     self._initial_default = default
Beispiel #9
0
def _get_bin_edges(a, bins, range, weights):
    """
    Computes the bins used internally by `histogram`.

    Parameters
    ==========
    a : ndarray
        Ravelled data array
    bins, range
        Forwarded arguments from `histogram`.
    weights : ndarray, optional
        Ravelled weights array, or None

    Returns
    =======
    bin_edges : ndarray
        Array of bin edges
    uniform_bins : (Number, Number, int):
        The upper bound, lowerbound, and number of bins, used in the optimized
        implementation of `histogram` that works on uniform bins.
    """
    # parse the overloaded bins argument
    n_equal_bins = None
    bin_edges = None

    if isinstance(bins, basestring):
        bin_name = bins
        # if `bins` is a string for an automatic method,
        # this will replace it with the number of bins calculated
        if bin_name not in _hist_bin_selectors:
            raise ValueError(
                "{!r} is not a valid estimator for `bins`".format(bin_name))
        if weights is not None:
            raise TypeError("Automated estimation of the number of "
                            "bins is not supported for weighted data")

        first_edge, last_edge = _get_outer_edges(a, range)

        # truncate the range if needed
        if range is not None:
            keep = (a >= first_edge)
            keep &= (a <= last_edge)
            if not np.logical_and.reduce(keep):
                a = a[keep]

        if a.size == 0:
            n_equal_bins = 1
        else:
            # Do not call selectors on empty arrays
            width = _hist_bin_selectors[bin_name](a)
            if width:
                n_equal_bins = int(
                    np.ceil(_unsigned_subtract(last_edge, first_edge) / width))
            else:
                # Width can be zero for some estimators, e.g. FD when
                # the IQR of the data is zero.
                n_equal_bins = 1

    elif np.ndim(bins) == 0:
        try:
            n_equal_bins = operator.index(bins)
        except TypeError:
            raise TypeError('`bins` must be an integer, a string, or an array')
        if n_equal_bins < 1:
            raise ValueError('`bins` must be positive, when an integer')

        first_edge, last_edge = _get_outer_edges(a, range)

    elif np.ndim(bins) == 1:
        bin_edges = np.asarray(bins)
        if np.any(bin_edges[:-1] > bin_edges[1:]):
            raise ValueError(
                '`bins` must increase monotonically, when an array')

    else:
        raise ValueError('`bins` must be 1d, when an array')

    if n_equal_bins is not None:
        # gh-10322 means that type resolution rules are dependent on array
        # shapes. To avoid this causing problems, we pick a type now and stick
        # with it throughout.
        bin_type = np.result_type(first_edge, last_edge, a)
        if np.issubdtype(bin_type, np.integer):
            bin_type = np.result_type(bin_type, float)

        # bin edges must be computed
        bin_edges = np.linspace(first_edge,
                                last_edge,
                                n_equal_bins + 1,
                                endpoint=True,
                                dtype=bin_type)
        return bin_edges, (first_edge, last_edge, n_equal_bins)
    else:
        return bin_edges, None
Beispiel #10
0
    def test_unary_ufunc_1d_manual(self):
        # Exercise branches in PyArray_EQUIVALENTLY_ITERABLE

        def check(a, b):
            a_orig = a.copy()
            b_orig = b.copy()

            b0 = b.copy()
            c1 = ufunc(a, out=b0)
            c2 = ufunc(a, out=b)
            assert_array_equal(c1, c2)

            # Trigger "fancy ufunc loop" code path
            mask = view_element_first_byte(b).view(np.bool_)

            a[...] = a_orig
            b[...] = b_orig
            c1 = ufunc(a, out=b.copy(), where=mask.copy()).copy()

            a[...] = a_orig
            b[...] = b_orig
            c2 = ufunc(a, out=b, where=mask.copy()).copy()

            # Also, mask overlapping with output
            a[...] = a_orig
            b[...] = b_orig
            c3 = ufunc(a, out=b, where=mask).copy()

            assert_array_equal(c1, c2)
            assert_array_equal(c1, c3)

        dtypes = [np.int8, np.int16, np.int32, np.int64, np.float32,
                  np.float64, np.complex64, np.complex128]
        dtypes = [np.dtype(x) for x in dtypes]

        for dtype in dtypes:
            if np.issubdtype(dtype, np.integer):
                ufunc = np.invert
            else:
                ufunc = np.reciprocal

            n = 1000
            k = 10
            indices = [
                np.index_exp[:n],
                np.index_exp[k:k+n],
                np.index_exp[n-1::-1],
                np.index_exp[k+n-1:k-1:-1],
                np.index_exp[:2*n:2],
                np.index_exp[k:k+2*n:2],
                np.index_exp[2*n-1::-2],
                np.index_exp[k+2*n-1:k-1:-2],
            ]

            for xi, yi in itertools.product(indices, indices):
                v = np.arange(1, 1 + n*2 + k, dtype=dtype)
                x = v[xi]
                y = v[yi]

                with np.errstate(all='ignore'):
                    check(x, y)

                    # Scalar cases
                    check(x[:1], y)
                    check(x[-1:], y)
                    check(x[:1].reshape([]), y)
                    check(x[-1:].reshape([]), y)
Beispiel #11
0
 def test_sibling_class(self):
     for w1, w2 in itertools.product(self.wrappers, repeat=2):
         assert_(not np.issubdtype(w1(np.float32), w2(np.float64)))
         assert_(not np.issubdtype(w1(np.float64), w2(np.float32)))
Beispiel #12
0
 def test_subclass_backwards(self):
     for w in self.wrappers:
         assert_(not np.issubdtype(np.floating, w(np.float32)))
         assert_(not np.issubdtype(np.floating, w(np.float64)))
Beispiel #13
0
 def test_subclass(self):
     # note we cannot promote floating to a dtype, as it would turn into a
     # concrete type
     for w in self.wrappers:
         assert_(np.issubdtype(w(np.float32), np.floating))
         assert_(np.issubdtype(w(np.float64), np.floating))
Beispiel #14
0
 def test_same(self):
     for cls in (np.float32, np.int32):
         for w1, w2 in itertools.product(self.wrappers, repeat=2):
             assert_(np.issubdtype(w1(cls), w2(cls)))
Beispiel #15
0
 def test_both_abstract(self):
     assert_(np.issubdtype(np.floating, np.inexact))
     assert_(not np.issubdtype(np.inexact, np.floating))