def _prep(self): NX = 10 zin = nlcpy.empty(NX, dtype='c16') zout_forward = nlcpy.empty(NX, dtype='c16') zout_backward = nlcpy.empty(NX, dtype='c16') zin.real = nlcpy.arange(NX, dtype='f8') zin.imag = nlcpy.arange(NX, dtype='f8') return NX, zin, zout_forward, zout_backward
def test_4d_hypervolumetric_with_coef(self): xin = testing.shaped_arange(self.shape, nlcpy).astype(self.dtype) * 0.1 n_elem = get_n_stencil_elem(self.stencil_scale) if self.coef_array: coef_shape = list(xin.shape) for an in get_axis_numbers_from_strtype(self.type): if abs(an) <= xin.ndim: coef_shape[an] -= 2 * self.stencil_scale coef = testing.shaped_arange( [ n_elem, ] + coef_shape, nlcpy, dtype=self.dtype) * 0.01 else: coef = nlcpy.arange(n_elem) * 0.1 coef = coef.astype(dtype=self.dtype) rtol = TOL_SINGLE if self.dtype == numpy.float32 else TOL_DOUBLE sca_res, sca_out = compute_with_sca(self.type, xin, self.stencil_scale, coef=coef, is_out=self.is_out, prefix=self.prefix, optimize=self.optimize, change_coef=self.change_coef) naive_res = compute_with_naive(self.type, xin, self.stencil_scale, coef=coef) if self.is_out: assert id(sca_res) == id(sca_out) testing.assert_allclose(sca_res, naive_res, rtol=rtol)
def _prep(dtype): NX = 50 NY = 60 NZ = 40 x1 = nlcpy.arange(NZ * NY * NX, dtype=dtype).reshape(NZ, NY, NX) x2 = nlcpy.ones((NZ, NY, NX), dtype=dtype) y = nlcpy.zeros((NZ, NY, NX), dtype=dtype) return x1, x2, y
def test_assign_numpy_factor(self, dtype): xin = nlcpy.arange(10).astype(dtype) dx = nlcpy.sca.create_descriptor(xin) coef = numpy.array(-1, dtype=dtype) desc = dx[0] * coef res_sca = nlcpy.sca.create_kernel(desc).execute() res_naive = xin * coef testing.assert_allclose(res_sca, res_naive)
def diag_indices(n, ndim=2): """Returns the indices to access the main diagonal of an array. This returns a tuple of indices that can be used to access the main diagonal of an array *a* with ``a.ndim >= 2`` dimensions and shape (n, n, ..., n). For ``a.ndim = 2`` this is the usual diagonal, for ``a.ndim > 2`` this is the set of indices to access ``a[i, i, ..., i]`` for ``i = [0..n-1]``. Parameters ---------- n : int The size, along each dimension, of the arrays for which the returned indices can be used. ndim : int, optional The number of dimensions. Examples -------- Create a set of indices to access the diagonal of a (4, 4) array: >>> import nlcpy as vp >>> di = vp.diag_indices(4) >>> di (array([0, 1, 2, 3]), array([0, 1, 2, 3])) >>> a = vp.arange(16).reshape(4, 4) >>> a array([[ 0, 1, 2, 3], [ 4, 5, 6, 7], [ 8, 9, 10, 11], [12, 13, 14, 15]]) >>> a[di] = 100 >>> a array([[100, 1, 2, 3], [ 4, 100, 6, 7], [ 8, 9, 100, 11], [ 12, 13, 14, 100]]) Now, we create indices to manipulate a 3-D array: >>> d3 = vp.diag_indices(2, 3) >>> d3 (array([0, 1]), array([0, 1]), array([0, 1])) And use it to set the diagonal of an array of zeros to 1: >>> a = vp.zeros((2, 2, 2), dtype=int) >>> a[d3] = 1 >>> a array([[[1, 0], [0, 0]], <BLANKLINE> [[0, 0], [0, 1]]]) """ idx = nlcpy.arange(n) return (idx, ) * ndim
def test_assign_multiple_coef_for_multiple_description(self, dtype): xin = nlcpy.arange(10).astype(dtype) dx = nlcpy.sca.create_descriptor(xin) coef1 = nlcpy.array(-1, dtype=dtype) coef2 = nlcpy.array(2, dtype=dtype) coef3 = nlcpy.array(3, dtype=dtype) desc = dx[0] * coef1 + dx[0] * coef2 + dx[0] * coef3 res_sca = nlcpy.sca.create_kernel(desc).execute() res_naive = xin * coef1 + xin * coef2 + xin * coef3 testing.assert_allclose(res_sca, res_naive)
def test_me_case_2(): np_a = np.arange(6).reshape((3, 2)) ny_a = ny.arange(6).reshape((3, 2)) we = [1. / 4, 3. / 4] np_ans = np.average(np_a, axis=1, weights=we) ny_ans = ny.average(ny_a, axis=1, weights=we) print("ans1={} ans2={}".format(np_ans, ny_ans)) assert_allclose(np_ans, ny_ans)
def test_getitem(self): a = nlcpy.arange(numpy.prod(self.shape)).reshape(self.shape) indexes_ve = [] for s in self.indexes: if isinstance(s, numpy.ndarray): s = nlcpy.array(s) indexes_ve.append(s) indexes_ve = tuple(indexes_ve) b = a[indexes_ve] b_cpu = a.get()[self.indexes] testing.assert_array_equal(b, b_cpu)
def test_3d_volumetric_with_factor_and_coef(self): xin = testing.shaped_arange(self.shape, nlcpy).astype(self.dtype) * 0.1 n_elem = get_n_stencil_elem(self.stencil_scale) nlcpy.random.seed(0) # to avoid loss of digits, create from arenge factor = ((nlcpy.arange(n_elem) - 0.5) * 10).tolist() if self.coef_array: coef_shape = list(xin.shape) for an in get_axis_numbers_from_strtype(self.type): if abs(an) <= xin.ndim: coef_shape[an] -= 2 * self.stencil_scale coef = testing.shaped_arange( [n_elem, ] + coef_shape, nlcpy, dtype=self.dtype ) * 0.01 else: coef = (nlcpy.arange(n_elem) - 0.5) * 10 coef = coef.astype(dtype=self.dtype) rtol = TOL_SINGLE if self.dtype == numpy.float32 else TOL_DOUBLE sca_res, sca_out = compute_with_sca( self.type, xin, self.stencil_scale, factor=factor, coef=coef, is_out=self.is_out, prefix=self.prefix, optimize=self.optimize, change_coef=self.change_coef ) naive_res = compute_with_naive( self.type, xin, self.stencil_scale, factor=factor, coef=coef ) if self.is_out: assert id(sca_res) == id(sca_out) testing.assert_allclose(sca_res, naive_res, rtol=rtol)
def _take_along_axis(arr, indices, axis): shape = arr.shape shape_ones = (1, ) * indices.ndim dest_dims = list(range(axis)) + [None] + list(range( axis + 1, indices.ndim)) fancy_index = [] for dim, n in zip(dest_dims, shape): if dim is None: fancy_index.append(indices) else: ind_shape = shape_ones[:dim] + (-1, ) + shape_ones[dim + 1:] fancy_index.append(nlcpy.arange(n).reshape(ind_shape)) return arr[tuple(fancy_index)]
def test_3d_volumetric_with_factor(self): xin = testing.shaped_arange(self.shape, nlcpy).astype(self.dtype) * 0.1 n_elem = get_n_stencil_elem(self.stencil_scale) factor = (nlcpy.arange(n_elem) * 0.1).tolist() rtol = TOL_SINGLE if self.dtype == numpy.float32 else TOL_DOUBLE sca_res, sca_out = compute_with_sca( self.type, xin, self.stencil_scale, factor=factor, is_out=self.is_out, prefix=self.prefix, optimize=self.optimize ) naive_res = compute_with_naive(self.type, xin, self.stencil_scale, factor=factor) if self.is_out: assert id(sca_res) == id(sca_out) testing.assert_allclose(sca_res, naive_res, rtol=rtol)
def initialize(shape, dtype, targ): scale = .001 if targ == params.nlcpy_sca[0]: y = vp.sca.create_optimized_array(shape, dtype=dtype) _x = vp.arange(y.size, dtype=dtype).reshape(shape) * scale x = vp.sca.convert_optimized_array(_x) elif targ in (params.numba_cpu[0], params.pystencils_cpu[0], params.pystencils_gpu[0]): y = np.zeros(shape, dtype=dtype) x = np.arange(y.size, dtype=dtype).reshape(shape) * scale elif targ in (params.cupy_fusion[0], params.numba_cuda[0]): import cupy as cp y = cp.zeros(shape, dtype=dtype) x = cp.arange(y.size, dtype=dtype).reshape(shape) * scale else: raise ValueError return x, y
def insert(arr, obj, values, axis=None): """Inserts values along the given axis before the given indices. Parameters ---------- arr : array_like Input array. obj : int, slice or sequence of ints Object that defines the index or indices before which values is inserted. Support for multiple insertions when obj is a single scalar or a sequence with one element (similar to calling insert multiple times). values : array_like Values to insert into arr. If the type of values is different from that of arr, values is converted to the type of arr. values should be shaped so that arr[...,obj,...] = values is legal. axis : int, optional Axis along which to insert values. If axis is None then arr is flattened first. Returns ------- out : ndarray A copy of arr with values inserted. Note that insert does not occur in-place: a new array is returned. If axis is None, out is a flattened array. Note: Note that for higher dimensional inserts obj=0 behaves very different from obj=[0] just like arr[:,0,:] = values is different from arr[:,[0],:] = values. See Also -------- append : Appends values to the end of an array. concatenate : Joins a sequence of arrays along an existing axis. delete : Returns a new array with sub-arrays along an axis deleted. Examples -------- >>> import nlcpy as vp >>> from nlcpy import testing >>> a = vp.array([[1, 1], [2, 2], [3, 3]]) >>> a array([[1, 1], [2, 2], [3, 3]]) >>> vp.insert(a, 1, 5) array([1, 5, 1, 2, 2, 3, 3]) >>> vp.insert(a, 1, 5, axis=1) array([[1, 5, 1], [2, 5, 2], [3, 5, 3]]) Difference between sequence and scalars: >>> vp.insert(a, [1], [[1],[2],[3]], axis=1) array([[1, 1, 1], [2, 2, 2], [3, 3, 3]]) >>> vp.testing.assert_array_equal( ... vp.insert(a, 1, [1, 2, 3], axis=1), ... vp.insert(a, [1], [[1],[2],[3]], axis=1)) >>> b = a.flatten() >>> b array([1, 1, 2, 2, 3, 3]) >>> vp.insert(b, [2, 2], [5, 6]) array([1, 1, 5, 6, 2, 2, 3, 3]) >>> vp.insert(b, slice(2, 4), [5, 6]) array([1, 1, 5, 2, 6, 2, 3, 3]) >>> vp.insert(b, [2, 2], [7.13, False]) # type casting array([1, 1, 7, 0, 2, 2, 3, 3]) >>> x = vp.arange(8).reshape(2, 4) >>> idx = (1, 3) >>> vp.insert(x, idx, 999, axis=1) array([[ 0, 999, 1, 2, 999, 3], [ 4, 999, 5, 6, 999, 7]]) """ a = nlcpy.asarray(arr) if axis is None: if a.ndim != 1: a = a.ravel() axis = 0 elif isinstance(axis, nlcpy.ndarray) or isinstance(axis, numpy.ndarray): axis = int(axis) elif not isinstance(axis, int): raise TypeError("an integer is required " "(got type {0})".format(type(axis).__name__)) if axis < -a.ndim or axis >= a.ndim: raise nlcpy.AxisError( "axis {0} is out of bounds for array of dimension {1}".format(axis, a.ndim)) if axis < 0: axis += a.ndim if type(obj) is slice: start, stop, step = obj.indices(a.shape[axis]) obj = nlcpy.arange(start, stop, step) else: obj = nlcpy.array(obj) if obj.dtype.char == '?': warnings.warn( "in the future insert will treat boolean arrays and " "array-likes as a boolean index instead of casting it to " "integer", FutureWarning, stacklevel=3) elif obj.dtype.char in 'fdFD': if obj.size == 1: raise TypeError( "slice indices must be integers or " "None or have an __index__ method") elif obj.size > 0: raise IndexError( 'arrays used as indices must be of integer (or boolean) type') elif obj.dtype.char in 'IL': if obj.size == 1: objval = obj[()] if obj.ndim == 0 else obj[0] if objval > a.shape[axis]: raise IndexError( "index {0} is out of bounds for axis {1} with size {2}".format( objval, axis, a.shape[axis])) else: tmp = 'float64' if obj.dtype.char == 'L' else 'int64' raise UFuncTypeError( "Cannot cast ufunc 'add' output from dtype('{0}') to " "dtype('{1}') with casting rule 'same_kind'".format(tmp, obj.dtype)) obj = obj.astype('l') if obj.ndim > 1: raise ValueError( "index array argument obj to insert must be one dimensional or scalar") if obj.ndim == 0: if obj > a.shape[axis] or obj < -a.shape[axis]: raise IndexError( "index {0} is out of bounds for axis {1} with size {2}".format( obj[()] if obj > 0 else obj[()] + a.shape[axis], axis, a.shape[axis])) newshape = list(a.shape) if obj.size == 1: values = nlcpy.array(values, copy=False, ndmin=a.ndim, dtype=a.dtype) if obj.ndim == 0: values = nlcpy.moveaxis(values, 0, axis) newshape[axis] += values.shape[axis] obj = nlcpy.array(nlcpy.broadcast_to(obj, values.shape[axis])) val_shape = list(a.shape) val_shape[axis] = values.shape[axis] values = nlcpy.broadcast_to(values, val_shape) else: newshape[axis] += obj.size values = nlcpy.array(values, copy=False, ndmin=a.ndim, dtype=a.dtype) val_shape = list(a.shape) val_shape[axis] = obj.size values = nlcpy.broadcast_to(values, val_shape) out = nlcpy.empty(newshape, dtype=a.dtype) work = nlcpy.zeros(obj.size + out.shape[axis] + 2, dtype='l') work[-1] = -1 request._push_request( 'nlcpy_insert', 'manipulation_op', (a, obj, values, out, axis, work) ) if work[-1] != -1: raise IndexError( "index {0} is out of bounds for axis {1} with size {2}" .format(obj[work[-1]], axis, out.shape[axis])) return out
def delete(arr, obj, axis=None): """Returns a new array with sub-arrays along an axis deleted. For a one dimensional array, this returns those entries not returned by arr[obj]. Parameters ---------- arr : array_like Input array. obj : slice, int or array of ints Indicate indices of sub-arrays to remove along the specified axis. axis : int, optional The axis along which to delete the subarray defined by obj. If axis is None, obj is applied to the flattened array. Returns ------- out : ndarray A copy of arr with the elements specified by obj removed. Note that delete does not occur in-place. If axis is None, out is a flattened array. Note ---- Often it is preferable to use a boolean mask. For example: >>> import nlcpy as vp >>> arr = vp.arange(12) + 1 >>> mask = vp.ones(len(arr), dtype=bool) >>> mask[[0,2,4]] = False >>> result = arr[mask,...] Is equivalent to vp.delete(arr, [0,2,4], axis=0), but allows further use of mask. See Also -------- insert : Inserts values along the given axis before the given indices. append : Appends values to the end of an array. Examples -------- >>> import nlcpy as vp >>> arr = vp.array([[1,2,3,4], [5,6,7,8], [9,10,11,12]]) >>> arr array([[ 1, 2, 3, 4], [ 5, 6, 7, 8], [ 9, 10, 11, 12]]) >>> vp.delete(arr, 1, 0) array([[ 1, 2, 3, 4], [ 9, 10, 11, 12]]) >>> vp.delete(arr, slice(None, None, 2), 1) array([[ 2, 4], [ 6, 8], [10, 12]]) >>> vp.delete(arr, [1,3,5], None) array([ 1, 3, 5, 7, 8, 9, 10, 11, 12]) """ input_arr = nlcpy.asarray(arr) ndim = input_arr.ndim if input_arr._f_contiguous and not input_arr._c_contiguous: order_out = 'F' else: order_out = 'C' if axis is None: if ndim != 1: input_arr = input_arr.ravel() ndim = input_arr.ndim axis = ndim - 1 if isinstance(axis, numpy.ndarray) or isinstance(axis, nlcpy.ndarray): axis = int(axis) elif not isinstance(axis, int): raise TypeError("an integer is required (got type " + str(type(axis).__name__) + ")") if axis < -ndim or axis > ndim - 1: raise AxisError( "axis {} is out of bounds for array of dimension {}".format(axis, ndim)) if axis < 0: axis += ndim N = input_arr.shape[axis] if isinstance(obj, slice): start, stop, step = obj.indices(N) xr = range(start, stop, step) if len(xr) == 0: return input_arr.copy(order=order_out) else: del_obj = nlcpy.arange(start, stop, step) else: del_obj = nlcpy.asarray(obj) if del_obj.ndim != 1: del_obj = del_obj.ravel() if del_obj.dtype == bool: if del_obj.ndim != 1 or del_obj.size != input_arr.shape[axis]: raise ValueError( 'boolean array argument obj to delete must be one dimensional and ' 'match the axis length of {}'.format(input_arr.shape[axis])) del_obj = del_obj.astype(nlcpy.intp) if isinstance(obj, (int, nlcpy.integer)): if (obj < -N or obj >= N): raise IndexError( "index %i is out of bounds for axis %i with " "size %i" % (obj, axis, N)) if (obj < 0): del_obj += N elif del_obj.size > 0 and del_obj.dtype != int: raise IndexError( 'arrays used as indices must be of integer (or boolean) type') if del_obj.size == 0: new = nlcpy.array(input_arr) return new else: new = nlcpy.empty(input_arr.shape, input_arr.dtype, order_out) idx = nlcpy.ones(input_arr.shape[axis], dtype=del_obj.dtype) obj_count = nlcpy.zeros([3], dtype='l') request._push_request( 'nlcpy_delete', 'manipulation_op', (input_arr, del_obj, axis, idx, new, obj_count) ) count = obj_count.get() if count[1] != 0: raise IndexError( "index out of bounds for axis {}".format(axis)) if count[2] != 0: warnings.warn( "in the future negative indices will not be ignored by " "`numpy.delete`.", FutureWarning, stacklevel=3) sl = [slice(N - count[0]) if i == axis else slice(None) for i in range(new.ndim)] return new[sl].copy()
def fft1(x): L = len(x) phase = -2j * np.pi * (np.arange(L) / float(L)) phase = np.arange(L).reshape(-1, 1) * phase return np.sum(x * np.exp(phase), axis=1)
def test_ifft2_invalid_axes_s(self, param, norm): a = nlcpy.arange(24).reshape(2, 3, 4) with pytest.raises(ValueError): nlcpy.fft.ifft2(a, s=param[0], axes=param[1], norm=norm)