Python cupy.arange() Examples

The following are 30 code examples of cupy.arange(). 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 cupy , or try the search function .
Example #1
Source File: non_maximum_suppression.py    From chainer-compiler with MIT License 6 votes vote down vote up
def _non_maximum_suppression_gpu(bbox, thresh, score=None, limit=None):
    if len(bbox) == 0:
        return cp.zeros((0,), dtype=np.int32)

    n_bbox = bbox.shape[0]

    if score is not None:
        order = score.argsort()[::-1].astype(np.int32)
    else:
        order = cp.arange(n_bbox, dtype=np.int32)

    sorted_bbox = bbox[order, :]
    selec, n_selec = _call_nms_kernel(
        sorted_bbox, thresh)
    selec = selec[:n_selec]
    selec = order[selec]
    if limit is not None:
        selec = selec[:limit]
    return selec 
Example #2
Source File: voxelization.py    From mesh_reconstruction with MIT License 6 votes vote down vote up
def _voxelize_sub2(faces, size):
    bs, nf = faces.shape[:2]
    faces = cp.ascontiguousarray(faces)
    voxels = cp.zeros((faces.shape[0], size, size, size), 'int32')
    chainer.cuda.elementwise(
        'int32 j, raw T faces, raw int32 bs, raw int32 nf, raw int32 vs',
        'raw int32 voxels',
        '''
            int fn = j % nf;
            int bn = j / nf;
            float* face = &faces[(bn * nf + fn) * 9];
            for (int k = 0; k < 3; k++) {
                int yi = face[3 * k + 0];
                int xi = face[3 * k + 1];
                int zi = face[3 * k + 2];
                if ((0 <= yi) && (yi < vs) && (0 <= xi) && (xi < vs) && (0 <= zi) && (zi < vs))
                    voxels[bn * vs * vs * vs + yi * vs * vs + xi * vs + zi] = 1;
            }
        ''',
        'function',
    )(cp.arange(bs * nf).astype('int32'), faces, bs, nf, size, voxels)
    return voxels 
Example #3
Source File: test_cupy_interop.py    From chainer with MIT License 6 votes vote down vote up
def test_cupy_to_chainerx_delete_cupy_first():
    dtype = numpy.float32
    a_cupy = cupy.arange(6, dtype=dtype).reshape((2, 3))
    a_chx = _fromrawpointer(
        a_cupy.data.mem.ptr,
        a_cupy.shape,
        a_cupy.dtype,
        a_cupy.strides,
        'cuda:0',
        0,
        a_cupy)

    del a_cupy

    a_chx += 1
    chainerx.testing.assert_array_equal_ex(
        a_chx, numpy.array([[1, 2, 3], [4, 5, 6]], dtype)) 
Example #4
Source File: test_cupy_interop.py    From chainer with MIT License 6 votes vote down vote up
def test_cupy_to_chainerx_delete_chainerx_first():
    dtype = numpy.float32
    a_cupy = cupy.arange(6, dtype=dtype).reshape((2, 3))
    a_chx = _fromrawpointer(
        a_cupy.data.mem.ptr,
        a_cupy.shape,
        a_cupy.dtype,
        a_cupy.strides,
        'cuda:0',
        0,
        a_cupy)

    del a_chx

    a_cupy += 1
    chainerx.testing.assert_array_equal_ex(
        a_cupy.get(), numpy.array([[1, 2, 3], [4, 5, 6]], dtype)) 
Example #5
Source File: non_maximum_suppression.py    From chainercv with MIT License 6 votes vote down vote up
def _non_maximum_suppression_gpu(bbox, thresh, score=None, limit=None):
    if len(bbox) == 0:
        return cp.zeros((0,), dtype=np.int32)

    n_bbox = bbox.shape[0]

    if score is not None:
        order = score.argsort()[::-1].astype(np.int32)
    else:
        order = cp.arange(n_bbox, dtype=np.int32)

    sorted_bbox = bbox[order, :]
    selec, n_selec = _call_nms_kernel(
        sorted_bbox, thresh)
    selec = selec[:n_selec]
    selec = order[selec]
    if limit is not None:
        selec = selec[:limit]
    return selec 
Example #6
Source File: cross.py    From neural_renderer with MIT License 6 votes vote down vote up
def forward_gpu(self, inputs):
        a, b = inputs
        c = cp.zeros_like(a, 'float32')
        chainer.cuda.elementwise(
            'int32 j, raw T a, raw T b',
            'raw T c',
            '''
                float* ap = (float*)&a[j * 3];
                float* bp = (float*)&b[j * 3];
                float* cp = (float*)&c[j * 3];
                cp[0] = ap[1] * bp[2] - ap[2] * bp[1];
                cp[1] = ap[2] * bp[0] - ap[0] * bp[2];
                cp[2] = ap[0] * bp[1] - ap[1] * bp[0];
            ''',
            'function',
        )(
            cp.arange(a.size / 3).astype('int32'), a, b, c,
        )
        return c, 
Example #7
Source File: polynomial.py    From cupy with MIT License 6 votes vote down vote up
def polyvander(x, deg):
    """Computes the Vandermonde matrix of given degree.

    Args:
        x (cupy.ndarray): array of points
        deg (int): degree of the resulting matrix.

    Returns:
        cupy.ndarray: The Vandermonde matrix

    .. seealso:: :func:`numpy.polynomial.polynomial.polyvander`

    """
    deg = cupy.polynomial.polyutils._deprecate_as_int(deg, 'deg')
    if deg < 0:
        raise ValueError('degree must be non-negative')
    if x.ndim == 0:
        x = x.ravel()
    dtype = cupy.float64 if x.dtype.kind in 'biu' else x.dtype
    out = x ** cupy.arange(deg + 1, dtype=dtype).reshape((-1,) + (1,) * x.ndim)
    return cupy.moveaxis(out, 0, -1) 
Example #8
Source File: kmeans.py    From cupy with MIT License 6 votes vote down vote up
def fit_custom(X, n_clusters, max_iter):
    assert X.ndim == 2

    n_samples = len(X)

    pred = cupy.zeros(n_samples)

    initial_indexes = cupy.random.choice(n_samples, n_clusters, replace=False)
    centers = X[initial_indexes]

    for _ in range(max_iter):
        distances = var_kernel(X[:, None, 0], X[:, None, 1],
                               centers[None, :, 1], centers[None, :, 0])
        new_pred = cupy.argmin(distances, axis=1)
        if cupy.all(new_pred == pred):
            break
        pred = new_pred

        i = cupy.arange(n_clusters)
        mask = pred == i[:, None]
        sums = sum_kernel(X, mask[:, :, None], axis=1)
        counts = count_kernel(mask, axis=1).reshape((n_clusters, 1))
        centers = sums / counts

    return centers, pred 
Example #9
Source File: ranges.py    From cupy with MIT License 6 votes vote down vote up
def logspace(start, stop, num=50, endpoint=True, base=10.0, dtype=None):
    """Returns an array with evenly-spaced values on a log-scale.

    Instead of specifying the step width like :func:`cupy.arange`, this
    function requires the total number of elements specified.

    Args:
        start: Start of the interval.
        stop: End of the interval.
        num: Number of elements.
        endpoint (bool): If ``True``, the stop value is included as the last
            element. Otherwise, the stop value is omitted.
        base (float): Base of the log space. The step sizes between the
            elements on a log-scale are the same as ``base``.
        dtype: Data type specifier. It is inferred from the start and stop
            arguments by default.

    Returns:
        cupy.ndarray: The 1-D array of ranged values.

    """
    y = linspace(start, stop, num=num, endpoint=endpoint)
    if dtype is None:
        return core.power(base, y)
    return core.power(base, y).astype(dtype) 
Example #10
Source File: test_cupy_interop.py    From chainer with MIT License 6 votes vote down vote up
def test_chainerx_to_cupy_delete_cupy_first():
    dtype = 'float32'
    a_chx = chainerx.arange(6, dtype=dtype, device='cuda:0').reshape((2, 3))
    a_cupy = cupy.ndarray(
        a_chx.shape,
        cupy.dtype(a_chx.dtype.name),
        cupy.cuda.MemoryPointer(cupy.cuda.UnownedMemory(
            a_chx.data_ptr + a_chx.offset,
            a_chx.data_size,
            a_chx,
            0), 0),
        strides=a_chx.strides,
    )

    del a_cupy

    a_chx += 1
    chainerx.testing.assert_array_equal_ex(
        a_chx, numpy.array([[1, 2, 3], [4, 5, 6]], dtype)) 
Example #11
Source File: test_cupy_interop.py    From chainer with MIT License 6 votes vote down vote up
def test_chainerx_to_cupy_delete_chainerx_first():
    dtype = 'float32'
    a_chx = chainerx.arange(6, dtype=dtype, device='cuda:0').reshape((2, 3))
    a_cupy = cupy.ndarray(
        a_chx.shape,
        cupy.dtype(a_chx.dtype.name),
        cupy.cuda.MemoryPointer(cupy.cuda.UnownedMemory(
            a_chx.data_ptr + a_chx.offset,
            a_chx.data_size,
            a_chx,
            0), 0),
        strides=a_chx.strides,
    )

    del a_chx

    a_cupy += 1
    chainerx.testing.assert_array_equal_ex(
        a_cupy.get(), numpy.array([[1, 2, 3], [4, 5, 6]], dtype)) 
Example #12
Source File: test_cupy_interop.py    From chainer with MIT License 6 votes vote down vote up
def test_chainerx_to_cupy_nondefault_device():
    dtype = 'float32'
    a_chx = chainerx.arange(6, dtype=dtype, device='cuda:1').reshape((2, 3))
    a_cupy = cupy.ndarray(
        a_chx.shape,
        cupy.dtype(a_chx.dtype.name),
        cupy.cuda.MemoryPointer(cupy.cuda.UnownedMemory(
            a_chx.data_ptr + a_chx.offset,
            a_chx.data_size,
            a_chx,
            -1), 0),
        strides=a_chx.strides,
    )

    assert a_cupy.device.id == 1
    chainerx.testing.assert_array_equal_ex(a_chx, a_cupy.get()) 
Example #13
Source File: non_maximum_suppression.py    From FATE with Apache License 2.0 6 votes vote down vote up
def _non_maximum_suppression_gpu(bbox, thresh, score=None, limit=None):
    if len(bbox) == 0:
        return cp.zeros((0,), dtype=np.int32)

    n_bbox = bbox.shape[0]

    if score is not None:
        order = score.argsort()[::-1].astype(np.int32)
    else:
        order = cp.arange(n_bbox, dtype=np.int32)

    sorted_bbox = bbox[order, :]
    selec, n_selec = _call_nms_kernel(
        sorted_bbox, thresh)
    selec = selec[:n_selec]
    selec = order[selec]
    if limit is not None:
        selec = selec[:limit]
    return cp.asnumpy(selec) 
Example #14
Source File: test_driver.py    From cupy with MIT License 6 votes vote down vote up
def test_ctxGetCurrent_thread(self):
        # Make sure to create context in main thread.
        cupy.arange(1)

        def f(self):
            self._result0 = driver.ctxGetCurrent()
            cupy.arange(1)
            self._result1 = driver.ctxGetCurrent()

        self._result0 = None
        self._result1 = None
        t = threading.Thread(target=f, args=(self,))
        t.daemon = True
        t.start()
        t.join()

        # The returned context pointer must be NULL on sub thread
        # without valid context.
        self.assertEqual(0, self._result0)

        # After the context is created, it should return the valid
        # context pointer.
        self.assertNotEqual(0, self._result1) 
Example #15
Source File: test_nccl.py    From cupy with MIT License 5 votes vote down vote up
def test_single_proc_single_dev(self):
        comms = cuda.nccl.NcclCommunicator.initAll(1)
        cuda.nccl.groupStart()
        for comm in comms:
            cuda.Device(comm.device_id()).use()
            sendbuf = cupy.arange(10)
            recvbuf = cupy.zeros_like(sendbuf)
            comm.allReduce(sendbuf.data.ptr, recvbuf.data.ptr, 10,
                           cuda.nccl.NCCL_INT64, cuda.nccl.NCCL_SUM,
                           cuda.Stream.null.ptr)
        cuda.nccl.groupEnd()
        assert cupy.allclose(sendbuf, recvbuf) 
Example #16
Source File: test_scan.py    From cupy with MIT License 5 votes vote down vote up
def test_scan(self, dtype):
        element_num = 10000

        if dtype in {cupy.int8, cupy.uint8, cupy.float16}:
            element_num = 100

        a = cupy.ones((element_num,), dtype=dtype)
        prefix_sum = scan(a)
        expect = cupy.arange(start=1, stop=element_num + 1).astype(dtype)

        testing.assert_array_equal(prefix_sum, expect) 
Example #17
Source File: insert.py    From cupy with MIT License 5 votes vote down vote up
def place(arr, mask, vals):
    """Change elements of an array based on conditional and input values.

    This function uses the first N elements of `vals`, where N is the number
    of true values in `mask`.

    Args:
        arr (cupy.ndarray): Array to put data into.
        mask (array-like): Boolean mask array. Must have the same size as `a`.
        vals (array-like): Values to put into `a`. Only the first
            N elements are used, where N is the number of True values in
            `mask`. If `vals` is smaller than N, it will be repeated, and if
            elements of `a` are to be masked, this sequence must be non-empty.

    Examples
    --------
    >>> arr = np.arange(6).reshape(2, 3)
    >>> np.place(arr, arr>2, [44, 55])
    >>> arr
    array([[ 0,  1,  2],
           [44, 55, 44]])

    .. warning::

        This function may synchronize the device.

    .. seealso:: :func:`numpy.place`
    """
    # TODO(niboshi): Avoid nonzero which may synchronize the device.
    mask = cupy.asarray(mask)
    if arr.size != mask.size:
        raise ValueError('Mask and data must be the same size.')
    vals = cupy.asarray(vals)

    mask_indices = mask.ravel().nonzero()[0]  # may synchronize
    if mask_indices.size == 0:
        return
    if vals.size == 0:
        raise ValueError('Cannot insert from an empty array.')
    arr.put(mask_indices, vals, mode='wrap') 
Example #18
Source File: indexing.py    From cupy with MIT License 5 votes vote down vote up
def take_along_axis(a, indices, axis):
    """Take values from the input array by matching 1d index and data slices.

    Args:
        a (cupy.ndarray): Array to extract elements.
        indices (cupy.ndarray): Indices to take along each 1d slice of ``a``.
        axis (int): The axis to take 1d slices along.

    Returns:
        cupy.ndarray: The indexed result.

    .. seealso:: :func:`numpy.take_along_axis`
    """

    if indices.dtype.kind not in ('i', 'u'):
        raise IndexError('`indices` must be an integer array')

    if axis is None:
        a = a.ravel()
        axis = 0

    ndim = a.ndim

    if not (-ndim <= axis < ndim):
        raise numpy.AxisError('Axis overrun')

    axis %= a.ndim

    if ndim != indices.ndim:
        raise ValueError(
            '`indices` and `a` must have the same number of dimensions')

    fancy_index = []
    for i, n in enumerate(a.shape):
        if i == axis:
            fancy_index.append(indices)
        else:
            ind_shape = (1,) * i + (-1,) + (1,) * (ndim - i - 1)
            fancy_index.append(cupy.arange(n).reshape(ind_shape))

    return a[fancy_index] 
Example #19
Source File: generate.py    From cupy with MIT License 5 votes vote down vote up
def indices(dimensions, dtype=int):
    """Returns an array representing the indices of a grid.

    Computes an array where the subarrays contain index values 0,1,...
    varying only along the corresponding axis.

    Args:
        dimensions: The shape of the grid.
        dtype: Data type specifier. It is int by default.

    Returns:
        ndarray:
        The array of grid indices,
        ``grid.shape = (len(dimensions),) + tuple(dimensions)``.

    Examples
    --------
    >>> grid = cupy.indices((2, 3))
    >>> grid.shape
    (2, 2, 3)
    >>> grid[0]        # row indices
    array([[0, 0, 0],
           [1, 1, 1]])
    >>> grid[1]        # column indices
    array([[0, 1, 2],
           [0, 1, 2]])

    .. seealso:: :func:`numpy.indices`

    """
    dimensions = tuple(dimensions)
    N = len(dimensions)
    shape = (1,) * N
    res = cupy.empty((N,) + dimensions, dtype=dtype)
    for i, dim in enumerate(dimensions):
        res[i] = cupy.arange(dim, dtype=dtype).reshape(
            shape[:i] + (dim,) + shape[i + 1:]
        )
    return res 
Example #20
Source File: fft.py    From cupy with MIT License 5 votes vote down vote up
def fftfreq(n, d=1.0):
    """Return the FFT sample frequencies.

    Args:
        n (int): Window length.
        d (scalar): Sample spacing.

    Returns:
        cupy.ndarray: Array of length ``n`` containing the sample frequencies.

    .. seealso:: :func:`numpy.fft.fftfreq`
    """
    return cupy.hstack((cupy.arange(0, (n - 1) // 2 + 1, dtype=np.float64),
                        cupy.arange(-(n // 2), 0, dtype=np.float64))) / n / d 
Example #21
Source File: test_indexing.py    From cupy with MIT License 5 votes vote down vote up
def test_select_default_scalar(self, dtype):
        a = cupy.arange(10)
        b = cupy.arange(20)
        condlist = [a < 3, b > 8]
        choicelist = [a, b]
        with pytest.raises(TypeError):
            cupy.select(condlist, choicelist, [dtype(2)]) 
Example #22
Source File: test_indexing.py    From cupy with MIT License 5 votes vote down vote up
def test_select_type_error_condlist(self, dtype):
        a = cupy.arange(10, dtype=dtype)
        condlist = [[3] * 10, [2] * 10]
        choicelist = [a, a**2]
        with pytest.raises(AttributeError):
            cupy.select(condlist, choicelist) 
Example #23
Source File: test_indexing.py    From cupy with MIT License 5 votes vote down vote up
def test_select_length_error(self, dtype):
        a = cupy.arange(10, dtype=dtype)
        condlist = [a > 3]
        choicelist = [a, a**2]
        with pytest.raises(ValueError):
            cupy.select(condlist, choicelist) 
Example #24
Source File: test_indexing.py    From cupy with MIT License 5 votes vote down vote up
def test_select_choicelist_condlist_broadcast(self, xp, dtype):
        a = cupy.arange(10, dtype=dtype)
        b = cupy.arange(20, dtype=dtype).reshape(2, 10)
        condlist = [a < 4, b > 8]
        choicelist = [cupy.repeat(a, 2).reshape(2, 10), b]
        return cupy.select(condlist, choicelist) 
Example #25
Source File: test_indexing.py    From cupy with MIT License 5 votes vote down vote up
def test_select_odd_shaped_broadcastable(self, xp, dtype):
        a = xp.arange(10, dtype=dtype)
        b = xp.arange(30, dtype=dtype).reshape(3, 10)
        condlist = [a < 3, b > 8]
        choicelist = [a, b]
        return xp.select(condlist, choicelist) 
Example #26
Source File: test_indexing.py    From cupy with MIT License 5 votes vote down vote up
def test_select_default_complex(self, xp, dtype):
        a = xp.arange(10, dtype=dtype)
        condlist = [a > 3, a < 5]
        choicelist = [a, a**2]
        default = 3
        return xp.select(condlist, choicelist, default) 
Example #27
Source File: test_indexing.py    From cupy with MIT License 5 votes vote down vote up
def test_select_default(self, xp, dtype):
        a = xp.arange(10, dtype=dtype)
        condlist = [a > 3, a < 5]
        choicelist = [a, a**2]
        default = 3
        return xp.select(condlist, choicelist, default) 
Example #28
Source File: test_indexing.py    From cupy with MIT License 5 votes vote down vote up
def test_select_complex(self, xp, dtype):
        a = xp.arange(10, dtype=dtype)
        condlist = [a > 3, a < 5]
        choicelist = [a, a**2]
        return xp.select(condlist, choicelist) 
Example #29
Source File: test_indexing.py    From cupy with MIT License 5 votes vote down vote up
def test_select(self, xp, dtype):
        a = xp.arange(10, dtype=dtype)
        condlist = [a > 3, a < 5]
        choicelist = [a, a**2]
        return xp.select(condlist, choicelist) 
Example #30
Source File: pcanet.py    From PCANet with MIT License 5 votes vote down vote up
def binary_to_decimal(X):
    """
    | This function takes :code:`X` of shape (n_images, L2, y, x) as an argument.
    | Supporse that :code:`X[k]` (0 <= k < n_images) can be represented as

    .. code-block:: none

        X[k] = [map_k[0], map_k[1], ..., map_k[L2-1]]

    where the shape of each map_k is (y, x).

    Then we calculate

    .. code-block:: none

        a[0] * map_k[0] + a[1] * map_k[1] + ... + a[L2-1] * map_k[L2-1]

    for each :code:`X[k]`, where :math:`a = [2^{L2-1}, 2^{L2-2}, ..., 2^{0}]`

    Therefore, the output shape must be (n_images, y, x)

    Parameters
    ----------
    X: xp.ndarray
        Feature maps
    """
    a = xp.arange(X.shape[1])[::-1]
    a = xp.power(2, a)
    return xp.tensordot(X, a, axes=([1], [0]))