Exemple #1
0
    def _mean(a, axis=None, dtype=None, out=None):
        arr = array_create.array(a)
        is_float16_result = False
        rcount = _count_reduce_items(arr, axis)
        # Make this warning show up first
        if rcount == 0:
            warnings.warn("Mean of empty slice.", RuntimeWarning, stacklevel=2)

        # Cast bool, unsigned int, and int to float64 by default
        if dtype is None:
            if issubclass(arr.dtype.type, (numpy.integer, numpy.bool_)):
                dtype = numpy.dtype('f8')
            elif issubclass(arr.dtype.type, numpy.float16):
                dtype = numpy.dtype('f4')
                is_float16_result = True

        ret = sum(arr, axis, dtype, out)
        if isinstance(ret, numpy.ndarray):
            ret = ufuncs.true_divide(ret, rcount, out=ret)
            if is_float16_result and out is None:
                ret = a.dtype.type(ret)
        elif hasattr(ret, 'dtype'):
            if is_float16_result:
                ret = a.dtype.type(ret / rcount)
            else:
                ret = ret.dtype.type(ret / rcount)
        else:
            ret = ret / rcount
        return ret
Exemple #2
0
    def _mean(a, axis=None, dtype=None, out=None):
        arr = array_create.array(a)
        is_float16_result = False
        rcount = _count_reduce_items(arr, axis)
        # Make this warning show up first
        if rcount == 0:
            warnings.warn("Mean of empty slice.", RuntimeWarning, stacklevel=2)

        # Cast bool, unsigned int, and int to float64 by default
        if dtype is None:
            if issubclass(arr.dtype.type, (numpy.integer, numpy.bool_)):
                dtype = numpy.dtype('f8')
            elif issubclass(arr.dtype.type, numpy.float16):
                dtype = numpy.dtype('f4')
                is_float16_result = True

        ret = sum(arr, axis, dtype, out)
        if isinstance(ret, numpy.ndarray):
            ret = ufuncs.true_divide(ret, rcount, out=ret)
            if is_float16_result and out is None:
                ret = a.dtype.type(ret)
        elif hasattr(ret, 'dtype'):
            if is_float16_result:
                ret = a.dtype.type(ret / rcount)
            else:
                ret = ret.dtype.type(ret / rcount)
        else:
            ret = ret / rcount
        return ret
Exemple #3
0
    def random_array(self, shape, dtype=None):
        """Return a random array of the given shape and dtype. If dtype is None, the type is determent by
        the --dtype command line arguments"""

        dtype = self.dtype if dtype is None else dtype
        size = functools.reduce(operator.mul, shape)
        if issubclass(numpy.dtype(dtype).type, numpy.integer):
            if bohrium is not None:
                # If bohrium is installed, we always uses the random123 in Bohrium even when running pure NumPy
                ret = bohrium.random.randint(1,
                                             size=size,
                                             bohrium=bh_is_loaded_as_np)
            else:
                ret = numpy.random.randint(1, size=size)
        else:
            if bohrium is not None:
                # If bohrium is installed, we always uses the random123 in Bohrium even when running pure NumPy
                ret = bohrium.random.rand(*shape, bohrium=bh_is_loaded_as_np)
            else:
                ret = numpy.random.rand(*shape)
        return np.array(ret, dtype=dtype)
Exemple #4
0
def linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=float, bohrium=True):
    """
    Return evenly spaced numbers over a specified interval.

    Returns `num` evenly spaced samples, calculated over the
    interval [`start`, `stop` ].

    The endpoint of the interval can optionally be excluded.

    Parameters
    ----------
    start : scalar
        The starting value of the sequence.
    stop : scalar
        The end value of the sequence, unless `endpoint` is set to False.
        In that case, the sequence consists of all but the last of ``num + 1``
        evenly spaced samples, so that `stop` is excluded.  Note that the step
        size changes when `endpoint` is False.
    num : int, optional
        Number of samples to generate. Default is 50.
    endpoint : bool, optional
        If True, `stop` is the last sample. Otherwise, it is not included.
        Default is True.
    retstep : bool, optional
        If True, return (`samples`, `step`), where `step` is the spacing
        between samples.

    Returns
    -------
    samples : ndarray
        There are `num` equally spaced samples in the closed interval
        ``[start, stop]`` or the half-open interval ``[start, stop)``
        (depending on whether `endpoint` is True or False).
    step : float (only if `retstep` is True)
        Size of spacing between samples.


    See Also
    --------
    arange : Similiar to `linspace`, but uses a step size (instead of the
             number of samples).
    logspace : Samples uniformly distributed in log space.

    Examples
    --------
    >>> np.linspace(2.0, 3.0, num=5)
        array([ 2.  ,  2.25,  2.5 ,  2.75,  3.  ])
    >>> np.linspace(2.0, 3.0, num=5, endpoint=False)
        array([ 2. ,  2.2,  2.4,  2.6,  2.8])
    >>> np.linspace(2.0, 3.0, num=5, retstep=True)
        (array([ 2.  ,  2.25,  2.5 ,  2.75,  3.  ]), 0.25)

    Graphical illustration:

    >>> import matplotlib.pyplot as plt
    >>> N = 8
    >>> y = np.zeros(N)
    >>> x1 = np.linspace(0, 10, N, endpoint=True)
    >>> x2 = np.linspace(0, 10, N, endpoint=False)
    >>> plt.plot(x1, y, 'o')
    [<matplotlib.lines.Line2D object at 0x...>]
    >>> plt.plot(x2, y + 0.5, 'o')
    [<matplotlib.lines.Line2D object at 0x...>]
    >>> plt.ylim([-0.5, 1])
    (-0.5, 1)
    >>> plt.show()

    """
    if not bohrium:
        # TODO: add copy=False to .astype()
        return numpy.linspace(start, stop, num=num, endpoint=endpoint, retstep=retstep).astype(dtype)

    num = int(num)
    if num <= 0:
        return array([], dtype=dtype)

    if endpoint:
        if num == 1:
            return array([numpy.dtype(dtype).type(start)])
        step = (stop - start) / float((num - 1))
    else:
        step = (stop - start) / float(num)

    y = arange(num, dtype=dtype)
    if step != 1: y *= step
    if start != 0: y += start

    if retstep:
        return y, step
    else:
        return y
Exemple #5
0
def arange(start, stop=None, step=1, dtype=None, bohrium=True):
    """
    arange([start,] stop[, step,], dtype=None)

    Return evenly spaced values within a given interval.

    Values are generated within the half-open interval ``[start, stop)``
    (in other words, the interval including `start` but excluding `stop`).
    For integer arguments the function is equivalent to the Python built-in
    `range <http://docs.python.org/lib/built-in-funcs.html>`_ function,
    but returns a ndarray rather than a list.

    When using a non-integer step, such as 0.1, the results will often not
    be consistent.  It is better to use ``linspace`` for these cases.

    Parameters
    ----------
    start : number, optional
        Start of interval.  The interval includes this value.  The default
        start value is 0.
    stop : number
        End of interval.  The interval does not include this value, except
        in some cases where `step` is not an integer and floating point
        round-off affects the length of `out`.
    step : number, optional
        Spacing between values.  For any output `out`, this is the distance
        between two adjacent values, ``out[i+1] - out[i]``.  The default
        step size is 1.  If `step` is specified, `start` must also be given.
    dtype : dtype
        The type of the output array.  If `dtype` is not given, infer the data
        type from the other input arguments.

    Returns
    -------
    out : ndarray
        Array of evenly spaced values.

        For floating point arguments, the length of the result is
        ``ceil((stop - start)/step)``.  Because of floating point overflow,
        this rule may result in the last element of `out` being greater
        than `stop`.

    See Also
    --------
    linspace : Evenly spaced numbers with careful handling of endpoints.
    ogrid: Arrays of evenly spaced numbers in N-dimensions
    mgrid: Grid-shaped arrays of evenly spaced numbers in N-dimensions

    Examples
    --------
    >>> np.arange(3)
    array([0, 1, 2])
    >>> np.arange(3.0)
    array([ 0.,  1.,  2.])
    >>> np.arange(3,7)
    array([3, 4, 5, 6])
    >>> np.arange(3,7,2)
    array([3, 5])

    """
    if not bohrium:
        return numpy.arange(start, stop, step, dtype)

    if stop is None:
        stop = start
        start = type(stop)(0)

    try:
        integers = (int, long)
    except:
        integers = (int,)
    if not (isinstance(stop, integers) and isinstance(start, integers)):
        raise ValueError("arange(): start and stop must be integers")

    if step == 0:
        raise ValueError("arange(): step cannot be zero")

    # Let's make sure that 'step' is always positive
    swap_back = False
    if step < 0:
        step *= -1
        (start, stop) = (stop, start)
        swap_back = True

    if start >= stop:
        return array([], dtype=dtype, bohrium=bohrium)

    size = int(math.ceil((float(stop) - float(start)) / float(step)))
    if dtype is None:
        dtype = numpy.int64
    else:
        start = numpy.dtype(dtype).type(start)
        stop = numpy.dtype(dtype).type(stop)
        step = numpy.dtype(dtype).type(step)

    result = simply_range(size, dtype=dtype)
    if swap_back:
        step *= -1
        (start, stop) = (stop, start)

    if step != 1:
        result *= step

    if start != 0:
        result += start

    return result