Here are the examples of the python api nlcpy.request.request._push_request taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
13 Examples
0
Source : basic.py
with BSD 3-Clause "New" or "Revised" License
from SX-Aurora
with BSD 3-Clause "New" or "Revised" License
from SX-Aurora
def eye(N, M=None, k=0, dtype=float, order='C'):
"""Returns a 2-D array with ones on the diagonal and zeros elsewhere.
Parameters
----------
N : int
Number of rows in the output.
M : int, optional
Number of columns in the output. If None, defaults to *N*.
k : int, optional
Index of the diagonal: 0 (the default) refers to the main diagonal, a positive
value refers to an upper diagonal, and a negative value to a lower diagonal.
dtype : dtype, optional
Data-type of the returned array.
order : {'C', 'F'}, optional
Whether the output should be stored in row-major (C-style) or column-major
(Fortran-style) order in memory.
Returns
-------
I : ndarray
An array where all elements are equal to zero, except for the k-th diagonal,
whose values are equal to one.
See Also
--------
identity : Returns the identity array.
diag : Extracts a diagonal or construct a diagonal array.
Examples
--------
>>> import nlcpy as vp
>>> vp.eye(2, dtype=int)
array([[1, 0],
[0, 1]])
>>> vp.eye(3, k=1)
array([[0., 1., 0.],
[0., 0., 1.],
[0., 0., 0.]])
"""
if numpy.dtype(dtype).kind == 'V':
raise NotImplementedError('void dtype in eye is not implemented yet.')
if M is None:
M = N
out = nlcpy.ndarray(shape=(N, M), dtype=dtype, order=order)
if order == 'F':
N, M = M, N
request._push_request(
"nlcpy_eye",
"creation_op",
(out, int(N), int(M), int(k)),)
return out
def identity(n, dtype=None):
0
Source : matrices.py
with BSD 3-Clause "New" or "Revised" License
from SX-Aurora
with BSD 3-Clause "New" or "Revised" License
from SX-Aurora
def tri(N, M=None, k=0, dtype=float):
"""An array with ones at and below the given diagonal and zeros elsewhere.
Parameters
----------
N : int
Number of rows in the array.
M : int, optional
Number of columns in the array. By default, *M* is taken equal to *N*.
k : int, optional
The sub-diagonal at and below which the array is filled. *k* = 0 is the main
diagonal, while *k* < 0 is below it, and *k* > 0 is above. The default is 0.
dtype : dtype, optional
Data type of the returned array. The default is float.
Returns
-------
tri : ndarray
Array with its lower triangle filled with ones and zero elsewhere; in other
words ``T[i,j] == 1`` for ``i < = j + k``, 0 otherwise.
Examples
--------
>>> import nlcpy as vp
>>> vp.tri(3, 5, 2, dtype=int)
array([[1, 1, 1, 0, 0],
[1, 1, 1, 1, 0],
[1, 1, 1, 1, 1]])
>>> vp.tri(3, 5, -1)
array([[0., 0., 0., 0., 0.],
[1., 0., 0., 0., 0.],
[1., 1., 0., 0., 0.]])
"""
if N < 0:
N = 0
else:
N = int(N)
if M is None:
M = N
elif M < 0:
M = 0
else:
M = int(M)
k = int(k)
out = nlcpy.empty([N, M], dtype=dtype)
if out.size:
request._push_request(
'nlcpy_tri',
'creation_op',
(out, k)
)
return out
def tril(m, k=0):
0
Source : ranges.py
with BSD 3-Clause "New" or "Revised" License
from SX-Aurora
with BSD 3-Clause "New" or "Revised" License
from SX-Aurora
def arange(start, stop=None, step=1, dtype=None):
"""Returns 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*). If stop is None, values are
ganerated within ``[0, start)``. For integer arguments the function is equivalent to
the Python built-in *range* function, but returns an 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 :func:`linspace` for these cases.
Parameters
----------
start : number
Start of interval. The interval includes this value.
stop : number, optional
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 as a position argument, *start* must also be given.
dtype : dtype, optional
The type of the output array. If *dtype* is not given, infer the data type from
the other input arguments.
Returns
-------
arange : 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 : Returns evenly spaced numbers over a specified interval.
Examples
--------
>>> import nlcpy as vp
>>> vp.arange(3)
array([0, 1, 2])
>>> vp.arange(3.0)
array([0., 1., 2.])
>>> vp.arange(3,7)
array([3, 4, 5, 6])
>>> vp.arange(3,7,2)
array([3, 5])
"""
if dtype is None:
if any(numpy.dtype(type(val)).kind == 'f'
for val in (start, stop, step)):
dtype = float
else:
dtype = int
if stop is None:
stop = start
start = 0
if step is None:
step = 1
size = int(numpy.ceil((stop - start) / step))
# size = int(numpy.ceil(numpy.ceil(stop - start) / step))
if size < = 0:
return nlcpy.empty((0,), dtype=dtype)
if numpy.dtype(dtype).type == numpy.bool_:
if size > 2:
raise ValueError('no fill-function for data-type.')
if size == 2:
return nlcpy.array([start, start - step], dtype=numpy.bool_)
else:
return nlcpy.array([start], dtype=numpy.bool_)
ret = nlcpy.empty((size,), dtype=dtype)
if numpy.dtype(dtype).kind == 'f':
typ = numpy.dtype('f8').type
elif numpy.dtype(dtype).kind == 'c':
typ = numpy.dtype('c16').type
elif numpy.dtype(dtype).kind == 'u':
typ = numpy.dtype('u8').type
elif numpy.dtype(dtype).kind == 'i':
typ = numpy.dtype('i8').type
elif numpy.dtype(dtype).kind == 'b':
typ = numpy.dtype('bool').type
else:
raise TypeError('detected invalid dtype.')
if ret._memloc in {on_VE, on_VE_VH}:
request._push_request(
"nlcpy_arange",
"creation_op",
(typ(start), typ(step), ret),)
if ret._memloc in {on_VH, on_VE_VH}:
del ret.vh_data
ret.vh_data = numpy.arange(typ(start), typ(stop), typ(step),
dtype=ret.dtype)
return ret
# ----------------------------------------------------------------------------
# Return evenly spaced numbers over a specified interval.
# see: https://docs.scipy.org/doc/numpy/reference/routines.array-creation.html
# ----------------------------------------------------------------------------
def linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None, axis=0):
0
Source : ranges.py
with BSD 3-Clause "New" or "Revised" License
from SX-Aurora
with BSD 3-Clause "New" or "Revised" License
from SX-Aurora
def linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None, axis=0):
"""Returns 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 : array_like
The starting value of the sequence.
stop : array_like
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. Must be non-negative.
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.
dtype : dtype, optional
The type of the output array. If *dtype* is not given, infer the data type from
the other input arguments.
axis : int, optional
The axis in the result to store the samples. Relevant only if start or stop are
array-like. By default (0), the samples will be along a new axis inserted at the
beginning. Use -1 to get an axis at the end.
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, optional
Only returned if *retstep* is True
Size of spacing between samples.
See Also
--------
arange : Returns evenly spaced values within a given interval.
Examples
--------
>>> import nlcpy as vp
>>> vp.linspace(2.0, 3.0, num=5)
array([2. , 2.25, 2.5 , 2.75, 3. ])
>>> vp.linspace(2.0, 3.0, num=5, endpoint=False)
array([2. , 2.2, 2.4, 2.6, 2.8])
>>> vp.linspace(2.0, 3.0, num=5, retstep=True)
(array([2. , 2.25, 2.5 , 2.75, 3. ]), array([0.25]))
"""
num = operator.index(num)
if num < 0:
raise ValueError("Number of samples, %s, must be non-negative." % num)
dtype_kind = numpy.dtype(dtype).kind
if dtype_kind == 'V':
raise NotImplementedError('void dtype in linspace is not implemented yet.')
start = nlcpy.asarray(start)
stop = nlcpy.asarray(stop)
dt = numpy.result_type(start, stop, float(num))
if start.dtype.char in '?iIlL' or stop.dtype.char in '?iIlL':
dt = 'D' if dt.char in 'FD' else 'd'
if dtype is None:
dtype = dt
start = nlcpy.asarray(start, dtype=dt)
stop = nlcpy.asarray(stop, dtype=dt)
delta = stop - start
div = (num - 1) if endpoint else num
if num == 0:
ret = nlcpy.empty((num,) + delta.shape, dtype=dtype)
if retstep:
ret = (ret, nlcpy.NaN)
return ret
elif div == 0 or num == 1:
ret = nlcpy.resize(start, (1,) + delta.shape).astype(dtype)
if retstep:
ret = (ret, stop)
return ret
else:
ret = nlcpy.empty((num,) + delta.shape, dtype=dtype)
retdata = ret
delta = delta[nlcpy.newaxis]
start = nlcpy.array(nlcpy.broadcast_to(start, delta.shape))
stop = nlcpy.array(nlcpy.broadcast_to(stop, delta.shape))
step = delta / div if div > 1 else delta
if retdata._memloc in {on_VE, on_VE_VH}:
denormal = nlcpy.zeros(1, dtype='l')
request._push_request(
"nlcpy_linspace",
"creation_op",
(ret, start, stop, delta, step, int(endpoint), denormal))
if axis != 0:
ret = nlcpy.moveaxis(ret, 0, axis)
if retstep:
ret = (ret, step)
if retdata._memloc in {on_VH, on_VE_VH}:
del retdata.vh_data
del step.vh_data
typ = numpy.dtype(dtype).type
if retstep:
(retdata.vh_data, step.vh_data) = numpy.linspace(typ(start),
typ(stop), num, endpoint,
typ(retstep), dtype, axis)
else:
retdata.vh_data = numpy.linspace(typ(start),
typ(stop), num, endpoint,
typ(retstep), dtype, axis)
return ret
def meshgrid(*xi, **kwargs):
0
Source : generate.py
with BSD 3-Clause "New" or "Revised" License
from SX-Aurora
with BSD 3-Clause "New" or "Revised" License
from SX-Aurora
def where(condition, x=None, y=None):
"""Returns elements chosen from *x* or *y* depending on *condition*.
Note
----
When only condition is provided, this function is a shorthand for
``nlcpy.asarray(condition).nonzero()``. Using nonzero directly should be preferred,
as it behaves correctly for subclasses. The rest of this documentation covers only
the case where all three arguments are provided.
Parameters
----------
condition : array_like, bool
Where True, yield *x*, otherwise yield *y*.
x, y : array_like
Values from which to choose. *x*, *y* and *condition* need to be broadcastable to
some shape.
Returns
-------
out : ndarray
An array with elements from *x* where *condition* is True, and elements from *y*
elsewhere.
Note
----
If all the arrays are 1-D, :func:`where` is equivalent to::
[xv if c else yv for c, xv, yv in zip(condition, x, y)]
See Also
--------
nonzero : Returns the indices of the elements
that are non-zero.
Examples
--------
>>> import nlcpy as vp
>>> a = vp.arange(10)
>>> a
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> vp.where(a < 5, a, 10*a)
array([ 0, 1, 2, 3, 4, 50, 60, 70, 80, 90])
This can be used on multidimensional arrays too:
>>> vp.where([[True, False], [True, True]],
... [[1, 2], [3, 4]],
... [[9, 8], [7, 6]])
array([[1, 8],
[3, 4]])
The shapes of x, y, and the condition are broadcast together:
>>> x = vp.arange(3).reshape([3,1])
>>> y = vp.arange(4).reshape([1,4])
>>> vp.where(x < y, x, 10 + y) # both x and 10+y are broadcast
array([[10, 0, 0, 0],
[10, 11, 1, 1],
[10, 11, 12, 2]])
>>> a = vp.array([[0, 1, 2],
... [0, 2, 4],
... [0, 3, 6]])
>>> vp.where(a < 4, a, -1) # -1 is broadcast
array([[ 0, 1, 2],
[ 0, 2, -1],
[ 0, 3, -1]])
"""
if condition is None:
condition = False
arr = nlcpy.asarray(condition)
if x is None and y is None:
return nlcpy.nonzero(arr)
if x is None or y is None:
raise ValueError("either both or neither of x and y should be given")
if not isinstance(x, nlcpy.ndarray):
x = numpy.asarray(x)
if not isinstance(y, nlcpy.ndarray):
y = numpy.asarray(y)
ret_type = numpy.result_type(x, y)
arr_x = nlcpy.asarray(x, dtype=ret_type)
arr_y = nlcpy.asarray(y, dtype=ret_type)
if arr.dtype != bool:
arr = (arr != 0)
values, shape = core._broadcast_core((arr, arr_x, arr_y))
ret = nlcpy.ndarray(shape=shape, dtype=ret_type)
request._push_request(
"nlcpy_where",
"indexing_op",
(ret, values[0], values[1], values[2]),)
return ret
def diag_indices(n, ndim=2):
0
Source : inserting.py
with BSD 3-Clause "New" or "Revised" License
from SX-Aurora
with BSD 3-Clause "New" or "Revised" License
from SX-Aurora
def fill_diagonal(a, val, wrap=False):
"""Fills the main diagonal of the given array of any dimensionality.
For an array *a* with ``a.ndim >= 2``, the diagonal is the list of locations with
indices ``a[i, ..., i]`` all identical. This function modifies the input array
in-place, it does not return a value.
Parameters
----------
a : array_like
Array whose diagonal is to be filled, it gets modified in-place.
val : scalar
Value to be written on the diagonal, its type must be compatible with that of
the array a.
wrap : bool
For tall matrices, the diagonal "wrapped" after N columns.
You can have this behavior with this option. This affects only tall matrices.
See Also
--------
diag_indices : Returns the indices to access the main diagonal of an array.
Note
----
This functionality can be obtained via diag_indices, but internally this version
uses a much faster implementation that never constructs the indices and uses
simple slicing.
Examples
--------
>>> import nlcpy as vp
>>> a = vp.zeros((3, 3), int)
>>> vp.fill_diagonal(a, 5)
>>> a
array([[5, 0, 0],
[0, 5, 0],
[0, 0, 5]])
The same function can operate on a 4-D array:
>>> a = vp.zeros((3, 3, 3, 3), int)
>>> vp.fill_diagonal(a, 4)
We only show a few blocks for clarity:
>>> a[0, 0]
array([[4, 0, 0],
[0, 0, 0],
[0, 0, 0]])
>>> a[1, 1]
array([[0, 0, 0],
[0, 4, 0],
[0, 0, 0]])
>>> a[2, 2]
array([[0, 0, 0],
[0, 0, 0],
[0, 0, 4]])
The wrap option affects only tall matrices:
>>> # tall matrices no wrap
>>> a = vp.zeros((5, 3), int)
>>> vp.fill_diagonal(a, 4)
>>> a
array([[4, 0, 0],
[0, 4, 0],
[0, 0, 4],
[0, 0, 0],
[0, 0, 0]])
>>> # tall matrices wrap
>>> a = vp.zeros((5, 3), int)
>>> vp.fill_diagonal(a, 4, wrap=True)
>>> a
array([[4, 0, 0],
[0, 4, 0],
[0, 0, 4],
[0, 0, 0],
[4, 0, 0]])
>>> # wide matrices
>>> a = vp.zeros((3, 5), int)
>>> vp.fill_diagonal(a, 4, wrap=True)
>>> a
array([[4, 0, 0, 0, 0],
[0, 4, 0, 0, 0],
[0, 0, 4, 0, 0]])
The anti-diagonal can be filled by reversing the order of elements using either
nlcpy.flipud or nlcpy.fliplr.
>>> a = vp.zeros((3, 3), int);
>>> vp.fill_diagonal(vp.fliplr(a), [1,2,3]) # Horizontal flip
>>> a
array([[0, 0, 1],
[0, 2, 0],
[3, 0, 0]])
>>> vp.fill_diagonal(vp.flipud(a), [1,2,3]) # Vertical flip
>>> a
array([[0, 0, 3],
[0, 2, 0],
[1, 0, 0]])
Note that the order in which the diagonal is filled varies depending on the flip
function.
"""
if a.ndim < 2:
raise ValueError('array must be at least 2-d')
val = nlcpy.asarray(val, dtype=a.dtype).flatten()
if val.size == 0:
return
if a.ndim > 2:
for i in range(1, len(a.shape)):
if a.shape[0] != a.shape[i]:
raise ValueError('All dimensions of input must be of equal length')
wrap = 1 if wrap else 0
request._push_request(
"nlcpy_fill_diagonal",
"indexing_op",
(a, val, wrap)
)
0
Source : products.py
with BSD 3-Clause "New" or "Revised" License
from SX-Aurora
with BSD 3-Clause "New" or "Revised" License
from SX-Aurora
def dot(a, b, out=None):
"""Computes a dot product of two arrays.
- If both *a* and *b* are 1-D arrays, it is inner product of vectors (without complex
conjugation).
- If both *a* and *b* are 2-D arrays, it is matrix multiplication, but using
:func:`nlcpy.matmul` or ``a @ b`` is preferred.
- If either *a* or *b* is 0-D (scalar), it is equivalent to multiply and using
``nlcpy.multiply(a,b)`` or ``a * b`` is preferred.
- If *a* is an N-D array and *b* is a 1-D array, it is a sum product over the last
axis of *a* and *b*.
- If *a* is an N-D array and *b* is an M-D array (where ``M>=2``), it is a
sum product over the last axis of *a* and the second-to-last axis of *b*:
``dot(a, b)[i,j,k,m] = sum(a[i,j,:] * b[k,:,m])``
Parameters
----------
a : array_like
Input arrays or scalars.
b : array_like
Input arrays or scalars.
out : ndarray, optional
Output argument. This must have the exact kind that would be returned if it was
not used. In particular, *out.dtype* must be the dtype that would be returned for
*dot(a,b)*.
Returns
-------
output : ndarray
Returns the dot product of *a* and *b*. If *a* and *b* are both scalars or both
1-D arrays then this function returns the result as a 0-dimention array.
Examples
--------
>>> import nlcpy as vp
>>> vp.dot(3, 4)
array(12)
Neither argument is complex-conjugated:
>>> vp.dot([2j, 3j], [2j, 3j])
array(-13.+0.j)
For 2-D arrays it is the matrix product:
>>> a = [[1, 0], [0, 1]]
>>> b = [[4, 1], [2, 2]]
>>> vp.dot(a,b)
array([[4, 1],
[2, 2]])
>>> a = vp.arange(3*4*5*6).reshape((3, 4, 5, 6))
>>> b = vp.arange(3*4*5*6)[::-1].reshape((5, 4, 6, 3))
>>> vp.dot(a, b)[2, 3, 2, 1, 2, 2]
array(499128)
>>> sum(a[2, 3, 2, :] * b[1, 2, :, 2])
array(499128)
"""
a = nlcpy.asanyarray(a)
b = nlcpy.asanyarray(b)
dtype_out = numpy.result_type(a.dtype, b.dtype)
if out is not None:
if not isinstance(out, nlcpy.ndarray):
raise TypeError("'out' must be an array")
if dtype_out != out.dtype:
raise ValueError('output array is incorrect dtype')
# if either a or b is 0-D array, it is equivalent to nlcpy.multiply
if a.ndim == 0 or b.ndim == 0:
return nlcpy.asanyarray(ufunc_op.multiply(a, b, out=out), order='C')
# if both a and b are 1-D arrays, it is inner product of vectors
if a.ndim == 1 and b.ndim == 1:
return cblas_wrapper.cblas_dot(a, b, out=out)
# if both a and b are 2-D arrays, it is matrix multiplication
if a.ndim == 2 and b.ndim == 2:
return cblas_wrapper.cblas_gemm(
a, b, out=out, dtype=numpy.result_type(a.dtype, b.dtype))
# if either a or b are N-D array, it is sum product over the
# last(or second-last) axis.
if b.ndim > 1:
if a.shape[-1] != b.shape[-2]:
raise ValueError('mismatch input shape')
shape_out = a.shape[:-1] + b.shape[:-2] + (b.shape[-1],)
else:
if a.shape[-1] != b.shape[-1]:
raise ValueError('mismatch input shape')
shape_out = a.shape[:-1]
if out is None:
out = nlcpy.empty(shape_out, dtype=dtype_out)
if out.dtype in (
numpy.int8, numpy.int16,
numpy.uint8, numpy.uint16, numpy.float16
):
raise TypeError('output dtype \'%s\' is not supported' % dtype_out)
elif out.shape != shape_out or not out.flags.c_contiguous:
raise ValueError(
'output array is not acceptable (must have the right datatype, '
'number of dimensions, and be a C-Array)')
out.fill(0)
if a.size > 0 and b.size > 0:
request._push_request(
"nlcpy_dot",
"linalg_op",
(a, b, out),
)
return out
def inner(a, b):
0
Source : core.py
with BSD 3-Clause "New" or "Revised" License
from SX-Aurora
with BSD 3-Clause "New" or "Revised" License
from SX-Aurora
def __call__(self, a, b, *args, **kwargs):
"Execute the call behavior."
# Get the data
(da, db) = (getdata(a), getdata(b))
# Get the result
result = self.f(da, db, *args, **kwargs)
# Get the mask as a combination of the source masks and invalid
m1 = getmask(a)
m2 = getmask(b)
if m1 is nomask and m2 is nomask:
m = nlcpy.zeros_like(result, dtype=numpy.bool_)
m1 = m
m2 = m
else:
m = nlcpy.empty_like(result, dtype=numpy.bool_)
if m1 is nomask:
m1 = m2
elif m2 is nomask:
m2 = m1
request._push_request(
"nlcpy_domain_mask",
"mask_op",
(m1, m2, result, m),
)
# Apply the domain
domain = ufunc_domain.get(self.f, None)
if domain is not None:
m |= domain(da, db)
# Take care of the scalar case first
if not m.ndim:
if m:
return masked
else:
return result
# When the mask is True, put back da if possible
# any errors, just abort; impossible to guarantee masked values
if type(a) is MaskedArray:
try:
nlcpy.copyto(result, 0, casting='unsafe', where=m)
# avoid using "*" since this may be overlaid
masked_da = nlcpy.multiply(m, da)
# only add back if it can be cast safely
if numpy.can_cast(masked_da.dtype, result.dtype, casting='safe'):
result += masked_da
except Exception:
pass
# Transforms to a (subclass of) MaskedArray
masked_result = result.view(MaskedArray)
masked_result._mask = m
if isinstance(a, MaskedArray):
masked_result._update_from(a)
elif isinstance(b, MaskedArray):
masked_result._update_from(b)
masked_result._sharedmask = False
return masked_result
divide = _DomainedBinaryOperation(ufunc_op.divide, _DomainSafeDivide(), 0, 1)
0
Source : add_remove.py
with BSD 3-Clause "New" or "Revised" License
from SX-Aurora
with BSD 3-Clause "New" or "Revised" License
from SX-Aurora
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 insert(arr, obj, values, axis=None):
0
Source : add_remove.py
with BSD 3-Clause "New" or "Revised" License
from SX-Aurora
with BSD 3-Clause "New" or "Revised" License
from SX-Aurora
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 resize(a, new_shape):
0
Source : add_remove.py
with BSD 3-Clause "New" or "Revised" License
from SX-Aurora
with BSD 3-Clause "New" or "Revised" License
from SX-Aurora
def unique(ar, return_index=False, return_inverse=False, return_counts=False, axis=None):
"""Finds the unique elements of an array.
Returns the sorted unique elements of an array.
There are three optional outputs in addition to the unique elements:
- the indices of the input array that give the unique values
- the indices of the unique array that reconstruct the input array
- the number of times each unique value comes up in the input array
Parameters
----------
ar : array_like
Input array.
Unless *axis* is specified, this will be flattened if it is not already 1-D.
return_index : bool, optional
If True, also return the indices of *ar* (along the specified axis, if provided,
or in the flattened array) that result in the unique array.
return_inverse : bool, optional
If True, also return the indices of the unique array (for the specified axis,
if provided) that can be used to reconstruct *ar*.
return_counts : bool, optional
If True, also return the number of times each unique item appears in *ar*.
axis : int or None, optional
The axis to operate on. If None, *ar* will be flattened. If an integer, the
subarrays indexed by the given axis will be flattened and treated as the
elements of a 1-D array with the dimension of the given axis, see the notes
for more details. Object arrays or structured arrays that contain objects are
not supported if the *axis* kwarg is used. The default is None.
Returns
-------
unique : ndarray
The sorted unique values.
unique_indices : ndarray, optional
The indices of the first occurrences of the unique values in the original array.
Only provided if *return_index* is True.
unique_inverse : ndarray, optional
The indices to reconstruct the original array from the unique array.
Only provided if *return_inverse* is True.
unique_count : ndarray, optional
The number of times each of the unique values comes up in the original array.
Only provided if *return_counts* is True.
Restriction
-----------
*NotImplementedError*:
- If 'c' is contained in *ar.dtype.kind*.
Note
----
When an axis is specified the subarrays indexed by the axis are sorted. This is done
by making the specified axis the first dimension of the array and then flattening
the subarrays in C order. The flattened subarrays are then viewed as a structured
type with each element given a label, with the effect that we end up with a 1-D
array of structured types that can be treated in the same way as any other 1-D
array. The result is that the flattened subarrays are sorted in lexicographic order
starting with the first element.
Examples
--------
>>> import nlcpy as vp
>>> vp.unique([1, 1, 2, 2, 3, 3])
array([1, 2, 3])
>>> a =vp.array([[1, 1], [2, 3]])
>>> vp.unique(a)
array([1, 2, 3])
Return the unique rows of a 2D array
>>> a = vp.array([[1, 0, 0], [1, 0, 0], [2, 3, 4]])
>>> vp.unique(a, axis=0)
array([[1, 0, 0],
[2, 3, 4]])
Return the indices of the original array that give the unique values:
>>> a = vp.array([1, 2, 2, 3, 1])
>>> u, indices = vp.unique(a, return_index=True)
>>> u
array([1, 2, 3])
>>> indices
array([0, 1, 3])
>>> a[indices]
array([1, 2, 3])
Reconstruct the input array from the unique values:
>>> a = vp.array([1, 2, 6, 4, 2, 3, 2])
>>> u, indices = vp.unique(a, return_inverse=True)
>>> u
array([1, 2, 3, 4, 6])
>>> indices
array([0, 1, 4, 3, 1, 2, 1])
>>> u[indices]
array([1, 2, 6, 4, 2, 3, 2])
"""
ar = nlcpy.asanyarray(ar)
if axis is not None:
if axis < 0:
axis = axis + ar.ndim
if axis < 0 or axis >= ar.ndim:
raise AxisError('Axis out of range')
if ar.ndim > 1 and axis is not None:
if ar.size == 0:
if axis is None:
shape = ()
else:
shape = list(ar.shape)
shape[axis] = int(shape[axis] / 2)
return nlcpy.empty(shape, dtype=ar.dtype)
ar = nlcpy.moveaxis(ar, axis, 0)
orig_shape = ar.shape
ar = ar.reshape(orig_shape[0], -1)
aux = nlcpy.array(ar)
perm = nlcpy.empty(ar.shape[0], dtype='l')
request._push_request(
'nlcpy_sort_multi',
'sorting_op',
(ar, aux, perm, return_index)
)
mask = nlcpy.empty(aux.shape[0], dtype='?')
mask[0] = True
mask[1:] = nlcpy.any(aux[1:] != aux[:-1], axis=1)
ret = aux[mask]
ret = ret.reshape(-1, *orig_shape[1:])
ret = nlcpy.moveaxis(ret, 0, axis)
else:
ar = ar.flatten()
if return_index or return_inverse:
perm = ar.argsort(kind='stable' if return_index else None)
aux = ar[perm]
else:
ar.sort()
aux = ar
mask = nlcpy.empty(aux.shape[0], dtype='?')
if mask.size:
mask[0] = True
mask[1:] = aux[1:] != aux[:-1]
ret = aux[mask]
if not return_index and not return_inverse and not return_counts:
return ret
ret = (ret,)
if return_index:
ret += (perm[mask],)
if return_inverse:
imask = nlcpy.cumsum(mask) - 1
inv_idx = nlcpy.empty(mask.shape, dtype=nlcpy.intp)
inv_idx[perm] = imask
ret += (inv_idx,)
if return_counts:
nonzero = nlcpy.nonzero(mask)[0]
idx = nlcpy.empty((nonzero.size + 1,), nonzero.dtype)
idx[:-1] = nonzero
idx[-1] = mask.size
ret += (idx[1:] - idx[:-1],)
return ret
0
Source : rearranging.py
with BSD 3-Clause "New" or "Revised" License
from SX-Aurora
with BSD 3-Clause "New" or "Revised" License
from SX-Aurora
def roll(a, shift, axis=None):
"""Rolls array elements along a given axis.
Elements that roll beyond the last position are re-introduced at the first.
Parameters
----------
a : array_like
Input array.
shift : int or tuple of ints
The number of places by which elements are shifted. If a tuple, then *axis* must
be a tuple of the same size, and each of the given axes is shifted by the
corresponding number. If an int while *axis* is a tuple of ints, then the
same value is used for all given axes.
axis : int or tuple of ints, optional
Axis or axes along which elements are shifted. By default, the array is
flattened before shifting, after which the original shape is restored.
Returns
-------
res : ndarray
Output array, with the same shape as *a*.
See Also
--------
rollaxis : Rolls the specified axis backwards, until it lies in a given position.
Examples
--------
>>> import nlcpy as vp
>>> x = vp.arange(10)
>>> vp.roll(x, 2)
array([8, 9, 0, 1, 2, 3, 4, 5, 6, 7])
>>> vp.roll(x, -2)
array([2, 3, 4, 5, 6, 7, 8, 9, 0, 1])
>>> x2 = vp.reshape(x, (2,5))
>>> x2
array([[0, 1, 2, 3, 4],
[5, 6, 7, 8, 9]])
>>> vp.roll(x2, 1)
array([[9, 0, 1, 2, 3],
[4, 5, 6, 7, 8]])
>>> vp.roll(x2, -1)
array([[1, 2, 3, 4, 5],
[6, 7, 8, 9, 0]])
>>> vp.roll(x2, 1, axis=0)
array([[5, 6, 7, 8, 9],
[0, 1, 2, 3, 4]])
>>> vp.roll(x2, -1, axis=0)
array([[5, 6, 7, 8, 9],
[0, 1, 2, 3, 4]])
>>> vp.roll(x2, 1, axis=1)
array([[4, 0, 1, 2, 3],
[9, 5, 6, 7, 8]])
>>> vp.roll(x2, -1, axis=1)
array([[1, 2, 3, 4, 0],
[6, 7, 8, 9, 5]])
"""
a = nlcpy.asanyarray(a)
if axis is None:
return roll(a.ravel(), shift, 0).reshape(a.shape)
if type(axis) not in (tuple, list):
try:
axis = [operator.index(axis)]
except TypeError:
pass
_axis = axis.get() if isinstance(axis, nlcpy.ndarray) else axis
axis = [ax + a.ndim if ax < 0 else ax for ax in _axis]
for ax in axis:
if ax < 0 or ax >= a.ndim:
raise AxisError(
'axis {} is out of bounds for array of dimension {}'
.format(ax, a.ndim))
shift = nlcpy.asanyarray(shift)
axis = nlcpy.asanyarray(axis)
if shift.ndim > 1 or axis.ndim > 1:
raise ValueError(
"'shift' and 'axis' should be scalars or 1D sequences")
if shift.size > axis.size:
axis = nlcpy.broadcast_to(axis, shift.shape)
else:
shift = nlcpy.broadcast_to(shift, axis.shape)
shift = nlcpy.array(shift, dtype='l')
axis = nlcpy.array(axis, dtype='l')
result = nlcpy.empty(a.shape, dtype=a.dtype)
work = nlcpy.zeros(a.ndim, dtype='l')
request._push_request(
'nlcpy_roll',
'manipulation_op',
(a, shift, axis, work, result)
)
return result
0
Source : tiling.py
with BSD 3-Clause "New" or "Revised" License
from SX-Aurora
with BSD 3-Clause "New" or "Revised" License
from SX-Aurora
def tile(A, reps):
"""Constructs an array by repeating A the number of times given by reps.
If *reps* has length ``d``, the result will have dimension of ``max(d, A.ndim)``.
If ``A.ndim < d`` , *A* is promoted to be d-dimensional by prepending new axes.
So a shape (3,) array is promoted to (1, 3) for 2-D replication, or shape
(1, 1, 3) for 3-D replication.
If this is not the desired behavior, promote *A* to d-dimensions
manually before calling this function.
If ``A.ndim > d``, *reps* is promoted to *A.ndim* by pre-pending 1's to it.
Thus for an *A* of shape (2, 3, 4, 5), a *reps* of (2, 2) is treated as
(1, 1, 2, 2).
Parameters
----------
A : array_like
The input array.
reps : array_like
The number of repetitions of *A* along each axis.
Returns
-------
c : ndarray
The tiled output array.
Note
----
Although tile may be used for broadcasting, it is strongly recommended to use nlcpy's
broadcasting operations and functions.
See Also
--------
broadcast_to : Broadcasts an array to a new shape.
Examples
--------
>>> import nlcpy as vp
>>> a = vp.array([0, 1, 2])
>>> vp.tile(a, 2)
array([0, 1, 2, 0, 1, 2])
>>> vp.tile(a, (2, 2))
array([[0, 1, 2, 0, 1, 2],
[0, 1, 2, 0, 1, 2]])
>>> vp.tile(a, (2, 1, 2))
array([[[0, 1, 2, 0, 1, 2]],
< BLANKLINE>
[[0, 1, 2, 0, 1, 2]]])
>>> b = vp.array([[1, 2], [3, 4]])
>>> vp.tile(b, 2)
array([[1, 2, 1, 2],
[3, 4, 3, 4]])
>>> vp.tile(b, (2, 1))
array([[1, 2],
[3, 4],
[1, 2],
[3, 4]])
>>> c = vp.array([1,2,3,4])
>>> vp.tile(c,(4,1))
array([[1, 2, 3, 4],
[1, 2, 3, 4],
[1, 2, 3, 4],
[1, 2, 3, 4]])
"""
if not isinstance(A, ndarray):
A = core.argument_conversion(A)
# TODO: numpy.isscalar -> nlcpy.isscalar
if numpy.isscalar(reps) or reps is None:
shape_reps = (reps,)
dim_reps = len(shape_reps)
elif isinstance(reps, (ndarray, numpy.ndarray)):
if reps.ndim == 0:
shape_reps = (reps,)
elif reps.ndim == 1:
shape_reps = tuple([reps[i] for i in range(reps.size)])
elif reps.ndim > 1:
raise ValueError("The truth value of an array with more than"
+ " one element is ambiguous. "
+ "Use a.any() or a.all()")
dim_reps = reps.size
elif isinstance(reps, (list, tuple)):
reps_size = 1
if len(reps) < = 0:
reps = (1,)
else:
if A.ndim in [0, 1, 2]:
inner_cnt = 1
else:
inner_cnt = functools.reduce(operator.mul, A.shape[0:-1])
for i in range(len(reps)):
if isinstance(reps[i], (list, tuple)):
if len(reps[i]) < = 0:
raise ValueError("operands could not be broadcast"
+ " together with shape ("
+ str(reps_size * inner_cnt)
+ ",) (0,)")
if len(reps[i]) == 1:
if isinstance(reps[i][0], (list, tuple)):
raise ValueError(
"object too deep for desired array")
else:
raise TypeError("'%s' object cannot be"
" interpreted as an integer"
% (type(reps[i]).__name__))
elif len(reps[i]) > 1:
list_flg = False
scal_flg = False
for j in range(len(reps[i])):
if isinstance(reps[i][j], (list, tuple)):
list_flg = True
# TODO: numpy.isscalar -> nlcpy.isscalar
elif numpy.isscalar(reps[i][j]):
scal_flg = True
elif isinstance(reps[i][j], (ndarray, numpy.ndarray)):
if reps[i][j].size == 1:
scal_flg = True
elif reps[i][j].size < = 0 or reps[i][j].size >= 2:
list_flg = True
if list_flg is True and scal_flg is True:
raise ValueError(
"setting an array element with a sequence.")
elif not list_flg and scal_flg:
raise ValueError("operands could not be broadcast"
+ " together with shape ("
+ str(reps_size * inner_cnt)
+ ",) (" + str(len(reps[i]))
+ ",)")
elif list_flg and not scal_flg:
raise ValueError(
"object too deep for desired array")
elif isinstance(reps[i], (ndarray, numpy.ndarray)):
if reps[i].size > 1 and reps.ndim > 0:
raise ValueError(
"The truth value of an array with more than"
+ " one element is ambiguous."
+ " Use a.any() or a.all()")
else:
if reps[i].ndim == 0:
shape_reps = (reps[i],)
elif reps[i].ndim == 1:
shape_reps = (reps[i],)
elif reps[i] is not None and not isinstance(reps[i], int):
if isinstance(reps[i], complex):
reps_size *= int(reps[i].real)
else:
reps_size *= int(reps[i])
shape_reps = tuple(reps)
dim_reps = len(shape_reps)
if A.ndim < dim_reps:
A = array(A, ndmin=dim_reps)
shape_A = A.shape
shape_reps = (1,) * (A.ndim - dim_reps) + shape_reps
shape = tuple(s * t for s, t in zip(shape_A, shape_reps))
ret = ndarray(shape=shape, dtype=A.dtype)
if ret.size > 0:
request._push_request(
'nlcpy_tile',
'manipulation_op',
(A, ret)
)
return ret
def repeat(a, repeats, axis=None):