wrap = None<EOL>if type(arr) is not ndarray:<EOL><INDENT>try:<EOL><INDENT>wrap = arr.__array_wrap__<EOL><DEDENT>except AttributeError:<EOL><INDENT>pass<EOL><DEDENT><DEDENT>arr = asarray(arr)<EOL>ndim = arr.ndim<EOL>if axis is None:<EOL><INDENT>if ndim != <NUM_LIT:1>:<EOL><INDENT>arr = arr.ravel()<EOL><DEDENT>ndim = arr.ndim<EOL>axis = ndim - <NUM_LIT:1><EOL><DEDENT>if ndim == <NUM_LIT:0>:<EOL><INDENT>warnings.warn(<EOL>"<STR_LIT>"<EOL>"<STR_LIT>", DeprecationWarning)<EOL>if wrap:<EOL><INDENT>return wrap(arr)<EOL><DEDENT>else:<EOL><INDENT>return arr.copy()<EOL><DEDENT><DEDENT>slobj = [slice(None)]*ndim<EOL>N = arr.shape[axis]<EOL>newshape = list(arr.shape)<EOL>if isinstance(obj, slice):<EOL><INDENT>start, stop, step = obj.indices(N)<EOL>xr = range(start, stop, step)<EOL>numtodel = len(xr)<EOL>if numtodel <= <NUM_LIT:0>:<EOL><INDENT>if wrap:<EOL><INDENT>return wrap(arr.copy())<EOL><DEDENT>else:<EOL><INDENT>return arr.copy()<EOL><DEDENT><DEDENT>if step < <NUM_LIT:0>:<EOL><INDENT>step = -step<EOL>start = xr[-<NUM_LIT:1>]<EOL>stop = xr[<NUM_LIT:0>] + <NUM_LIT:1><EOL><DEDENT>newshape[axis] -= numtodel<EOL>new = empty(newshape, arr.dtype, arr.flags.fnc)<EOL>if start == <NUM_LIT:0>:<EOL><INDENT>pass<EOL><DEDENT>else:<EOL><INDENT>slobj[axis] = slice(None, start)<EOL>new[slobj] = arr[slobj]<EOL><DEDENT>if stop == N:<EOL><INDENT>pass<EOL><DEDENT>else:<EOL><INDENT>slobj[axis] = slice(stop-numtodel, None)<EOL>slobj2 = [slice(None)]*ndim<EOL>slobj2[axis] = slice(stop, None)<EOL>new[slobj] = arr[slobj2]<EOL><DEDENT>if step == <NUM_LIT:1>:<EOL><INDENT>pass<EOL><DEDENT>else:  <EOL><INDENT>keep = ones(stop-start, dtype=bool)<EOL>keep[:stop-start:step] = False<EOL>slobj[axis] = slice(start, stop-numtodel)<EOL>slobj2 = [slice(None)]*ndim<EOL>slobj2[axis] = slice(start, stop)<EOL>arr = arr[slobj2]<EOL>slobj2[axis] = keep<EOL>new[slobj] = arr[slobj2]<EOL><DEDENT>if wrap:<EOL><INDENT>return wrap(new)<EOL><DEDENT>else:<EOL><INDENT>return new<EOL><DEDENT><DEDENT>_obj = obj<EOL>obj = np.asarray(obj)<EOL>if obj.dtype == bool:<EOL><INDENT>warnings.warn(<EOL>"<STR_LIT>"<EOL>"<STR_LIT>", FutureWarning)<EOL>obj = obj.astype(intp)<EOL><DEDENT>if isinstance(_obj, (int, long, integer)):<EOL><INDENT>obj = obj.item()<EOL>if (obj < -N or obj >= N):<EOL><INDENT>raise IndexError(<EOL>"<STR_LIT>"<EOL>"<STR_LIT>" % (obj, axis, N))<EOL><DEDENT>if (obj < <NUM_LIT:0>):<EOL><INDENT>obj += N<EOL><DEDENT>newshape[axis] -= <NUM_LIT:1><EOL>new = empty(newshape, arr.dtype, arr.flags.fnc)<EOL>slobj[axis] = slice(None, obj)<EOL>new[slobj] = arr[slobj]<EOL>slobj[axis] = slice(obj, None)<EOL>slobj2 = [slice(None)]*ndim<EOL>slobj2[axis] = slice(obj+<NUM_LIT:1>, None)<EOL>new[slobj] = arr[slobj2]<EOL><DEDENT>else:<EOL><INDENT>if obj.size == <NUM_LIT:0> and not isinstance(_obj, np.ndarray):<EOL><INDENT>obj = obj.astype(intp)<EOL><DEDENT>if not np.can_cast(obj, intp, '<STR_LIT>'):<EOL><INDENT>warnings.warn(<EOL>"<STR_LIT>"<EOL>"<STR_LIT>", DeprecationWarning)<EOL>obj = obj.astype(intp)<EOL><DEDENT>keep = ones(N, dtype=bool)<EOL>inside_bounds = (obj < N) & (obj >= -N)<EOL>if not inside_bounds.all():<EOL><INDENT>warnings.warn(<EOL>"<STR_LIT>"<EOL>"<STR_LIT>",<EOL>DeprecationWarning)<EOL>obj = obj[inside_bounds]<EOL><DEDENT>positive_indices = obj >= <NUM_LIT:0><EOL>if not positive_indices.all():<EOL><INDENT>warnings.warn(<EOL>"<STR_LIT>"<EOL>"<STR_LIT>", FutureWarning)<EOL>obj = obj[positive_indices]<EOL><DEDENT>keep[obj, ] = False<EOL>slobj[axis] = keep<EOL>new = arr[slobj]<EOL><DEDENT>if wrap:<EOL><INDENT>return wrap(new)<EOL><DEDENT>else:<EOL><INDENT>return new<EOL><DEDENT>

Return 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 which sub-arrays to remove.
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.

See Also
--------
insert : Insert elements into an array.
append : Append elements at the end of an array.

Notes
-----
Often it is preferable to use a boolean mask. For example:

>>> mask = np.ones(len(arr), dtype=bool)
>>> mask[[0,2,4]] = False
>>> result = arr[mask,...]

Is equivalent to `np.delete(arr, [0,2,4], axis=0)`, but allows further
use of `mask`.

Examples
--------
>>> arr = np.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]])
>>> np.delete(arr, 1, 0)
array([[ 1,  2,  3,  4],
       [ 9, 10, 11, 12]])

>>> np.delete(arr, np.s_[::2], 1)
array([[ 2,  4],
       [ 6,  8],
       [10, 12]])
>>> np.delete(arr, [1,3,5], None)
array([ 1,  3,  5,  7,  8,  9, 10, 11, 12])


def insert(arr, obj, values, axis=None):

wrap = None<EOL>if type(arr) is not ndarray:<EOL><INDENT>try:<EOL><INDENT>wrap = arr.__array_wrap__<EOL><DEDENT>except AttributeError:<EOL><INDENT>pass<EOL><DEDENT><DEDENT>arr = asarray(arr)<EOL>ndim = arr.ndim<EOL>if axis is None:<EOL><INDENT>if ndim != <NUM_LIT:1>:<EOL><INDENT>arr = arr.ravel()<EOL><DEDENT>ndim = arr.ndim<EOL>axis = ndim - <NUM_LIT:1><EOL><DEDENT>else:<EOL><INDENT>if ndim > <NUM_LIT:0> and (axis < -ndim or axis >= ndim):<EOL><INDENT>raise IndexError(<EOL>"<STR_LIT>"<EOL>"<STR_LIT>" % (axis, ndim))<EOL><DEDENT>if (axis < <NUM_LIT:0>):<EOL><INDENT>axis += ndim<EOL><DEDENT><DEDENT>if (ndim == <NUM_LIT:0>):<EOL><INDENT>warnings.warn(<EOL>"<STR_LIT>"<EOL>"<STR_LIT>", DeprecationWarning)<EOL>arr = arr.copy()<EOL>arr[...] = values<EOL>if wrap:<EOL><INDENT>return wrap(arr)<EOL><DEDENT>else:<EOL><INDENT>return arr<EOL><DEDENT><DEDENT>slobj = [slice(None)]*ndim<EOL>N = arr.shape[axis]<EOL>newshape = list(arr.shape)<EOL>if isinstance(obj, slice):<EOL><INDENT>indices = arange(*obj.indices(N), **{'<STR_LIT>': intp})<EOL><DEDENT>else:<EOL><INDENT>indices = np.array(obj)<EOL>if indices.dtype == bool:<EOL><INDENT>warnings.warn(<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>", FutureWarning)<EOL>indices = indices.astype(intp)<EOL><DEDENT>elif indices.ndim > <NUM_LIT:1>:<EOL><INDENT>raise ValueError(<EOL>"<STR_LIT>"<EOL>"<STR_LIT>")<EOL><DEDENT><DEDENT>if indices.size == <NUM_LIT:1>:<EOL><INDENT>index = indices.item()<EOL>if index < -N or index > N:<EOL><INDENT>raise IndexError(<EOL>"<STR_LIT>"<EOL>"<STR_LIT>" % (obj, axis, N))<EOL><DEDENT>if (index < <NUM_LIT:0>):<EOL><INDENT>index += N<EOL><DEDENT>values = array(values, copy=False, ndmin=arr.ndim, dtype=arr.dtype)<EOL>if indices.ndim == <NUM_LIT:0>:<EOL><INDENT>values = np.rollaxis(values, <NUM_LIT:0>, (axis % values.ndim) + <NUM_LIT:1>)<EOL><DEDENT>numnew = values.shape[axis]<EOL>newshape[axis] += numnew<EOL>new = empty(newshape, arr.dtype, arr.flags.fnc)<EOL>slobj[axis] = slice(None, index)<EOL>new[slobj] = arr[slobj]<EOL>slobj[axis] = slice(index, index+numnew)<EOL>new[slobj] = values<EOL>slobj[axis] = slice(index+numnew, None)<EOL>slobj2 = [slice(None)] * ndim<EOL>slobj2[axis] = slice(index, None)<EOL>new[slobj] = arr[slobj2]<EOL>if wrap:<EOL><INDENT>return wrap(new)<EOL><DEDENT>return new<EOL><DEDENT>elif indices.size == <NUM_LIT:0> and not isinstance(obj, np.ndarray):<EOL><INDENT>indices = indices.astype(intp)<EOL><DEDENT>if not np.can_cast(indices, intp, '<STR_LIT>'):<EOL><INDENT>warnings.warn(<EOL>"<STR_LIT>"<EOL>"<STR_LIT>", DeprecationWarning)<EOL>indices = indices.astype(intp)<EOL><DEDENT>indices[indices < <NUM_LIT:0>] += N<EOL>numnew = len(indices)<EOL>order = indices.argsort(kind='<STR_LIT>')   <EOL>indices[order] += np.arange(numnew)<EOL>newshape[axis] += numnew<EOL>old_mask = ones(newshape[axis], dtype=bool)<EOL>old_mask[indices] = False<EOL>new = empty(newshape, arr.dtype, arr.flags.fnc)<EOL>slobj2 = [slice(None)]*ndim<EOL>slobj[axis] = indices<EOL>slobj2[axis] = old_mask<EOL>new[slobj] = values<EOL>new[slobj2] = arr<EOL>if wrap:<EOL><INDENT>return wrap(new)<EOL><DEDENT>return new<EOL>

Insert 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.

    .. versionadded:: 1.8.0

    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.

See Also
--------
append : Append elements at the end of an array.
concatenate : Join a sequence of arrays together.
delete : Delete elements from an array.

Notes
-----
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`.

Examples
--------
>>> a = np.array([[1, 1], [2, 2], [3, 3]])
>>> a
array([[1, 1],
       [2, 2],
       [3, 3]])
>>> np.insert(a, 1, 5)
array([1, 5, 1, 2, 2, 3, 3])
>>> np.insert(a, 1, 5, axis=1)
array([[1, 5, 1],
       [2, 5, 2],
       [3, 5, 3]])

Difference between sequence and scalars:
>>> np.insert(a, [1], [[1],[2],[3]], axis=1)
array([[1, 1, 1],
       [2, 2, 2],
       [3, 3, 3]])
>>> np.array_equal(np.insert(a, 1, [1, 2, 3], axis=1),
...                np.insert(a, [1], [[1],[2],[3]], axis=1))
True

>>> b = a.flatten()
>>> b
array([1, 1, 2, 2, 3, 3])
>>> np.insert(b, [2, 2], [5, 6])
array([1, 1, 5, 6, 2, 2, 3, 3])

>>> np.insert(b, slice(2, 4), [5, 6])
array([1, 1, 5, 2, 6, 2, 3, 3])

>>> np.insert(b, [2, 2], [7.13, False]) # type casting
array([1, 1, 7, 0, 2, 2, 3, 3])

>>> x = np.arange(8).reshape(2, 4)
>>> idx = (1, 3)
>>> np.insert(x, idx, 999, axis=1)
array([[  0, 999,   1,   2, 999,   3],
       [  4, 999,   5,   6, 999,   7]])


arr = asanyarray(arr)<EOL>if axis is None:<EOL><INDENT>if arr.ndim != <NUM_LIT:1>:<EOL><INDENT>arr = arr.ravel()<EOL><DEDENT>values = ravel(values)<EOL>axis = arr.ndim-<NUM_LIT:1><EOL><DEDENT>return concatenate((arr, values), axis=axis)<EOL>

Append values to the end of an array.

Parameters
----------
arr : array_like
    Values are appended to a copy of this array.
values : array_like
    These values are appended to a copy of `arr`.  It must be of the
    correct shape (the same shape as `arr`, excluding `axis`).  If
    `axis` is not specified, `values` can be any shape and will be
    flattened before use.
axis : int, optional
    The axis along which `values` are appended.  If `axis` is not
    given, both `arr` and `values` are flattened before use.

Returns
-------
append : ndarray
    A copy of `arr` with `values` appended to `axis`.  Note that
    `append` does not occur in-place: a new array is allocated and
    filled.  If `axis` is None, `out` is a flattened array.

See Also
--------
insert : Insert elements into an array.
delete : Delete elements from an array.

Examples
--------
>>> np.append([1, 2, 3], [[4, 5, 6], [7, 8, 9]])
array([1, 2, 3, 4, 5, 6, 7, 8, 9])

When `axis` is specified, `values` must have the correct shape.

>>> np.append([[1, 2, 3], [4, 5, 6]], [[7, 8, 9]], axis=0)
array([[1, 2, 3],
       [4, 5, 6],
       [7, 8, 9]])
>>> np.append([[1, 2, 3], [4, 5, 6]], [7, 8, 9], axis=0)
Traceback (most recent call last):
...
ValueError: arrays must have same number of dimensions


excluded = self.excluded<EOL>if not kwargs and not excluded:<EOL><INDENT>func = self.pyfunc<EOL>vargs = args<EOL><DEDENT>else:<EOL><INDENT>nargs = len(args)<EOL>names = [_n for _n in kwargs if _n not in excluded]<EOL>inds = [_i for _i in range(nargs) if _i not in excluded]<EOL>the_args = list(args)<EOL>def func(*vargs):<EOL><INDENT>for _n, _i in enumerate(inds):<EOL><INDENT>the_args[_i] = vargs[_n]<EOL><DEDENT>kwargs.update(zip(names, vargs[len(inds):]))<EOL>return self.pyfunc(*the_args, **kwargs)<EOL><DEDENT>vargs = [args[_i] for _i in inds]<EOL>vargs.extend([kwargs[_n] for _n in names])<EOL><DEDENT>return self._vectorize_call(func=func, args=vargs)<EOL>

Return arrays with the results of `pyfunc` broadcast (vectorized) over
`args` and `kwargs` not in `excluded`.


def _get_ufunc_and_otypes(self, func, args):

<EOL>if not args:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>if self.otypes:<EOL><INDENT>otypes = self.otypes<EOL>nout = len(otypes)<EOL>if func is self.pyfunc and self._ufunc is not None:<EOL><INDENT>ufunc = self._ufunc<EOL><DEDENT>else:<EOL><INDENT>ufunc = self._ufunc = frompyfunc(func, len(args), nout)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>inputs = [asarray(_a).flat[<NUM_LIT:0>] for _a in args]<EOL>outputs = func(*inputs)<EOL>if self.cache:<EOL><INDENT>_cache = [outputs]<EOL>def _func(*vargs):<EOL><INDENT>if _cache:<EOL><INDENT>return _cache.pop()<EOL><DEDENT>else:<EOL><INDENT>return func(*vargs)<EOL><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>_func = func<EOL><DEDENT>if isinstance(outputs, tuple):<EOL><INDENT>nout = len(outputs)<EOL><DEDENT>else:<EOL><INDENT>nout = <NUM_LIT:1><EOL>outputs = (outputs,)<EOL><DEDENT>otypes = '<STR_LIT>'.join([asarray(outputs[_k]).dtype.char<EOL>for _k in range(nout)])<EOL>ufunc = frompyfunc(_func, len(args), nout)<EOL><DEDENT>return ufunc, otypes<EOL>


if not args:<EOL><INDENT>_res = func()<EOL><DEDENT>else:<EOL><INDENT>ufunc, otypes = self._get_ufunc_and_otypes(func=func, args=args)<EOL>inputs = [array(_a, copy=False, subok=True, dtype=object)<EOL>for _a in args]<EOL>outputs = ufunc(*inputs)<EOL>if ufunc.nout == <NUM_LIT:1>:<EOL><INDENT>_res = array(outputs,<EOL>copy=False, subok=True, dtype=otypes[<NUM_LIT:0>])<EOL><DEDENT>else:<EOL><INDENT>_res = tuple([array(_x, copy=False, subok=True, dtype=_t)<EOL>for _x, _t in zip(outputs, otypes)])<EOL><DEDENT><DEDENT>return _res<EOL>

Vectorized call to `func` over positional `args`.


def apply_along_axis(func1d, axis, arr, *args, **kwargs):

arr = asarray(arr)<EOL>nd = arr.ndim<EOL>if axis < <NUM_LIT:0>:<EOL><INDENT>axis += nd<EOL><DEDENT>if (axis >= nd):<EOL><INDENT>raise ValueError("<STR_LIT>"<EOL>% (axis, nd))<EOL><DEDENT>ind = [<NUM_LIT:0>]*(nd-<NUM_LIT:1>)<EOL>i = zeros(nd, '<STR_LIT:O>')<EOL>indlist = list(range(nd))<EOL>indlist.remove(axis)<EOL>i[axis] = slice(None, None)<EOL>outshape = asarray(arr.shape).take(indlist)<EOL>i.put(indlist, ind)<EOL>res = func1d(arr[tuple(i.tolist())], *args, **kwargs)<EOL>if isscalar(res):<EOL><INDENT>outarr = zeros(outshape, asarray(res).dtype)<EOL>outarr[tuple(ind)] = res<EOL>Ntot = product(outshape)<EOL>k = <NUM_LIT:1><EOL>while k < Ntot:<EOL><INDENT>ind[-<NUM_LIT:1>] += <NUM_LIT:1><EOL>n = -<NUM_LIT:1><EOL>while (ind[n] >= outshape[n]) and (n > (<NUM_LIT:1>-nd)):<EOL><INDENT>ind[n-<NUM_LIT:1>] += <NUM_LIT:1><EOL>ind[n] = <NUM_LIT:0><EOL>n -= <NUM_LIT:1><EOL><DEDENT>i.put(indlist, ind)<EOL>res = func1d(arr[tuple(i.tolist())], *args, **kwargs)<EOL>outarr[tuple(ind)] = res<EOL>k += <NUM_LIT:1><EOL><DEDENT>return outarr<EOL><DEDENT>else:<EOL><INDENT>Ntot = product(outshape)<EOL>holdshape = outshape<EOL>outshape = list(arr.shape)<EOL>outshape[axis] = len(res)<EOL>outarr = zeros(outshape, asarray(res).dtype)<EOL>outarr[tuple(i.tolist())] = res<EOL>k = <NUM_LIT:1><EOL>while k < Ntot:<EOL><INDENT>ind[-<NUM_LIT:1>] += <NUM_LIT:1><EOL>n = -<NUM_LIT:1><EOL>while (ind[n] >= holdshape[n]) and (n > (<NUM_LIT:1>-nd)):<EOL><INDENT>ind[n-<NUM_LIT:1>] += <NUM_LIT:1><EOL>ind[n] = <NUM_LIT:0><EOL>n -= <NUM_LIT:1><EOL><DEDENT>i.put(indlist, ind)<EOL>res = func1d(arr[tuple(i.tolist())], *args, **kwargs)<EOL>outarr[tuple(i.tolist())] = res<EOL>k += <NUM_LIT:1><EOL><DEDENT>return outarr<EOL><DEDENT>

Apply a function to 1-D slices along the given axis.

Execute `func1d(a, *args)` where `func1d` operates on 1-D arrays and `a`
is a 1-D slice of `arr` along `axis`.

Parameters
----------
func1d : function
    This function should accept 1-D arrays. It is applied to 1-D
    slices of `arr` along the specified axis.
axis : integer
    Axis along which `arr` is sliced.
arr : ndarray
    Input array.
args : any
    Additional arguments to `func1d`.
kwargs: any
    Additional named arguments to `func1d`.

    .. versionadded:: 1.9.0

Returns
-------
apply_along_axis : ndarray
    The output array. The shape of `outarr` is identical to the shape of
    `arr`, except along the `axis` dimension, where the length of `outarr`
    is equal to the size of the return value of `func1d`.  If `func1d`
    returns a scalar `outarr` will have one fewer dimensions than `arr`.

See Also
--------
apply_over_axes : Apply a function repeatedly over multiple axes.

Examples
--------
>>> def my_func(a):
...     \"\"\"Average first and last element of a 1-D array\"\"\"
...     return (a[0] + a[-1]) * 0.5
>>> b = np.array([[1,2,3], [4,5,6], [7,8,9]])
>>> np.apply_along_axis(my_func, 0, b)
array([ 4.,  5.,  6.])
>>> np.apply_along_axis(my_func, 1, b)
array([ 2.,  5.,  8.])

For a function that doesn't return a scalar, the number of dimensions in
`outarr` is the same as `arr`.

>>> b = np.array([[8,1,7], [4,3,9], [5,2,6]])
>>> np.apply_along_axis(sorted, 1, b)
array([[1, 7, 8],
       [3, 4, 9],
       [2, 5, 6]])


val = asarray(a)<EOL>N = a.ndim<EOL>if array(axes).ndim == <NUM_LIT:0>:<EOL><INDENT>axes = (axes,)<EOL><DEDENT>for axis in axes:<EOL><INDENT>if axis < <NUM_LIT:0>:<EOL><INDENT>axis = N + axis<EOL><DEDENT>args = (val, axis)<EOL>res = func(*args)<EOL>if res.ndim == val.ndim:<EOL><INDENT>val = res<EOL><DEDENT>else:<EOL><INDENT>res = expand_dims(res, axis)<EOL>if res.ndim == val.ndim:<EOL><INDENT>val = res<EOL><DEDENT>else:<EOL><INDENT>raise ValueError("<STR_LIT>"<EOL>"<STR_LIT>")<EOL><DEDENT><DEDENT><DEDENT>return val<EOL>

Apply a function repeatedly over multiple axes.

`func` is called as `res = func(a, axis)`, where `axis` is the first
element of `axes`.  The result `res` of the function call must have
either the same dimensions as `a` or one less dimension.  If `res`
has one less dimension than `a`, a dimension is inserted before
`axis`.  The call to `func` is then repeated for each axis in `axes`,
with `res` as the first argument.

Parameters
----------
func : function
    This function must take two arguments, `func(a, axis)`.
a : array_like
    Input array.
axes : array_like
    Axes over which `func` is applied; the elements must be integers.

Returns
-------
apply_over_axis : ndarray
    The output array.  The number of dimensions is the same as `a`,
    but the shape can be different.  This depends on whether `func`
    changes the shape of its output with respect to its input.

See Also
--------
apply_along_axis :
    Apply a function to 1-D slices of an array along the given axis.

Notes
------
This function is equivalent to tuple axis arguments to reorderable ufuncs
with keepdims=True. Tuple axis arguments to ufuncs have been availabe since
version 1.7.0.

Examples
--------
>>> a = np.arange(24).reshape(2,3,4)
>>> a
array([[[ 0,  1,  2,  3],
        [ 4,  5,  6,  7],
        [ 8,  9, 10, 11]],
       [[12, 13, 14, 15],
        [16, 17, 18, 19],
        [20, 21, 22, 23]]])

Sum over axes 0 and 2. The result has same number of dimensions
as the original array:

>>> np.apply_over_axes(np.sum, a, [0,2])
array([[[ 60],
        [ 92],
        [124]]])

Tuple axis arguments to ufuncs are equivalent:

>>> np.sum(a, axis=(0,2), keepdims=True)
array([[[ 60],
        [ 92],
        [124]]])


a = asarray(a)<EOL>shape = a.shape<EOL>if axis < <NUM_LIT:0>:<EOL><INDENT>axis = axis + len(shape) + <NUM_LIT:1><EOL><DEDENT>return a.reshape(shape[:axis] + (<NUM_LIT:1>,) + shape[axis:])<EOL>

Expand the shape of an array.

Insert a new axis, corresponding to a given position in the array shape.

Parameters
----------
a : array_like
    Input array.
axis : int
    Position (amongst axes) where new axis is to be inserted.

Returns
-------
res : ndarray
    Output array. The number of dimensions is one greater than that of
    the input array.

See Also
--------
doc.indexing, atleast_1d, atleast_2d, atleast_3d

Examples
--------
>>> x = np.array([1,2])
>>> x.shape
(2,)

The following is equivalent to ``x[np.newaxis,:]`` or ``x[np.newaxis]``:

>>> y = np.expand_dims(x, axis=0)
>>> y
array([[1, 2]])
>>> y.shape
(1, 2)

>>> y = np.expand_dims(x, axis=1)  # Equivalent to x[:,newaxis]
>>> y
array([[1],
       [2]])
>>> y.shape
(2, 1)

Note that some examples may use ``None`` instead of ``np.newaxis``.  These
are the same objects:

>>> np.newaxis is None
True


arrays = []<EOL>for v in tup:<EOL><INDENT>arr = array(v, copy=False, subok=True)<EOL>if arr.ndim < <NUM_LIT:2>:<EOL><INDENT>arr = array(arr, copy=False, subok=True, ndmin=<NUM_LIT:2>).T<EOL><DEDENT>arrays.append(arr)<EOL><DEDENT>return _nx.concatenate(arrays, <NUM_LIT:1>)<EOL>

Stack 1-D arrays as columns into a 2-D array.

Take a sequence of 1-D arrays and stack them as columns
to make a single 2-D array. 2-D arrays are stacked as-is,
just like with `hstack`.  1-D arrays are turned into 2-D columns
first.

Parameters
----------
tup : sequence of 1-D or 2-D arrays.
    Arrays to stack. All of them must have the same first dimension.

Returns
-------
stacked : 2-D array
    The array formed by stacking the given arrays.

See Also
--------
hstack, vstack, concatenate

Examples
--------
>>> a = np.array((1,2,3))
>>> b = np.array((2,3,4))
>>> np.column_stack((a,b))
array([[1, 2],
       [2, 3],
       [3, 4]])


return _nx.concatenate([atleast_3d(_m) for _m in tup], <NUM_LIT:2>)<EOL>

Stack arrays in sequence depth wise (along third axis).

Takes a sequence of arrays and stack them along the third axis
to make a single array. Rebuilds arrays divided by `dsplit`.
This is a simple way to stack 2D arrays (images) into a single
3D array for processing.

Parameters
----------
tup : sequence of arrays
    Arrays to stack. All of them must have the same shape along all
    but the third axis.

Returns
-------
stacked : ndarray
    The array formed by stacking the given arrays.

See Also
--------
vstack : Stack along first axis.
hstack : Stack along second axis.
concatenate : Join arrays.
dsplit : Split array along third axis.

Notes
-----
Equivalent to ``np.concatenate(tup, axis=2)``.

Examples
--------
>>> a = np.array((1,2,3))
>>> b = np.array((2,3,4))
>>> np.dstack((a,b))
array([[[1, 2],
        [2, 3],
        [3, 4]]])

>>> a = np.array([[1],[2],[3]])
>>> b = np.array([[2],[3],[4]])
>>> np.dstack((a,b))
array([[[1, 2]],
       [[2, 3]],
       [[3, 4]]])


def array_split(ary, indices_or_sections, axis=<NUM_LIT:0>):

try:<EOL><INDENT>Ntotal = ary.shape[axis]<EOL><DEDENT>except AttributeError:<EOL><INDENT>Ntotal = len(ary)<EOL><DEDENT>try:<EOL><INDENT>Nsections = len(indices_or_sections) + <NUM_LIT:1><EOL>div_points = [<NUM_LIT:0>] + list(indices_or_sections) + [Ntotal]<EOL><DEDENT>except TypeError:<EOL><INDENT>Nsections = int(indices_or_sections)<EOL>if Nsections <= <NUM_LIT:0>:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>Neach_section, extras = divmod(Ntotal, Nsections)<EOL>section_sizes = ([<NUM_LIT:0>] +<EOL>extras * [Neach_section+<NUM_LIT:1>] +<EOL>(Nsections-extras) * [Neach_section])<EOL>div_points = _nx.array(section_sizes).cumsum()<EOL><DEDENT>sub_arys = []<EOL>sary = _nx.swapaxes(ary, axis, <NUM_LIT:0>)<EOL>for i in range(Nsections):<EOL><INDENT>st = div_points[i]<EOL>end = div_points[i + <NUM_LIT:1>]<EOL>sub_arys.append(_nx.swapaxes(sary[st:end], axis, <NUM_LIT:0>))<EOL><DEDENT>if sub_arys[-<NUM_LIT:1>].size == <NUM_LIT:0> and sub_arys[-<NUM_LIT:1>].ndim != <NUM_LIT:1>:<EOL><INDENT>warnings.warn("<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>",<EOL>FutureWarning)<EOL>sub_arys = _replace_zero_by_x_arrays(sub_arys)<EOL><DEDENT>return sub_arys<EOL>

Split an array into multiple sub-arrays.

Please refer to the ``split`` documentation.  The only difference
between these functions is that ``array_split`` allows
`indices_or_sections` to be an integer that does *not* equally
divide the axis.

See Also
--------
split : Split array into multiple sub-arrays of equal size.

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


try:<EOL><INDENT>len(indices_or_sections)<EOL><DEDENT>except TypeError:<EOL><INDENT>sections = indices_or_sections<EOL>N = ary.shape[axis]<EOL>if N % sections:<EOL><INDENT>raise ValueError(<EOL>'<STR_LIT>')<EOL><DEDENT><DEDENT>res = array_split(ary, indices_or_sections, axis)<EOL>return res<EOL>

Split an array into multiple sub-arrays.

Parameters
----------
ary : ndarray
    Array to be divided into sub-arrays.
indices_or_sections : int or 1-D array
    If `indices_or_sections` is an integer, N, the array will be divided
    into N equal arrays along `axis`.  If such a split is not possible,
    an error is raised.

    If `indices_or_sections` is a 1-D array of sorted integers, the entries
    indicate where along `axis` the array is split.  For example,
    ``[2, 3]`` would, for ``axis=0``, result in

      - ary[:2]
      - ary[2:3]
      - ary[3:]

    If an index exceeds the dimension of the array along `axis`,
    an empty sub-array is returned correspondingly.
axis : int, optional
    The axis along which to split, default is 0.

Returns
-------
sub-arrays : list of ndarrays
    A list of sub-arrays.

Raises
------
ValueError
    If `indices_or_sections` is given as an integer, but
    a split does not result in equal division.

See Also
--------
array_split : Split an array into multiple sub-arrays of equal or
              near-equal size.  Does not raise an exception if
              an equal division cannot be made.
hsplit : Split array into multiple sub-arrays horizontally (column-wise).
vsplit : Split array into multiple sub-arrays vertically (row wise).
dsplit : Split array into multiple sub-arrays along the 3rd axis (depth).
concatenate : Join arrays together.
hstack : Stack arrays in sequence horizontally (column wise).
vstack : Stack arrays in sequence vertically (row wise).
dstack : Stack arrays in sequence depth wise (along third dimension).

Examples
--------
>>> x = np.arange(9.0)
>>> np.split(x, 3)
[array([ 0.,  1.,  2.]), array([ 3.,  4.,  5.]), array([ 6.,  7.,  8.])]

>>> x = np.arange(8.0)
>>> np.split(x, [3, 5, 6, 10])
[array([ 0.,  1.,  2.]),
 array([ 3.,  4.]),
 array([ 5.]),
 array([ 6.,  7.]),
 array([], dtype=float64)]


if len(_nx.shape(ary)) == <NUM_LIT:0>:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>if len(ary.shape) > <NUM_LIT:1>:<EOL><INDENT>return split(ary, indices_or_sections, <NUM_LIT:1>)<EOL><DEDENT>else:<EOL><INDENT>return split(ary, indices_or_sections, <NUM_LIT:0>)<EOL><DEDENT>

Split an array into multiple sub-arrays horizontally (column-wise).

Please refer to the `split` documentation.  `hsplit` is equivalent
to `split` with ``axis=1``, the array is always split along the second
axis regardless of the array dimension.

See Also
--------
split : Split an array into multiple sub-arrays of equal size.

Examples
--------
>>> x = np.arange(16.0).reshape(4, 4)
>>> x
array([[  0.,   1.,   2.,   3.],
       [  4.,   5.,   6.,   7.],
       [  8.,   9.,  10.,  11.],
       [ 12.,  13.,  14.,  15.]])
>>> np.hsplit(x, 2)
[array([[  0.,   1.],
       [  4.,   5.],
       [  8.,   9.],
       [ 12.,  13.]]),
 array([[  2.,   3.],
       [  6.,   7.],
       [ 10.,  11.],
       [ 14.,  15.]])]
>>> np.hsplit(x, np.array([3, 6]))
[array([[  0.,   1.,   2.],
       [  4.,   5.,   6.],
       [  8.,   9.,  10.],
       [ 12.,  13.,  14.]]),
 array([[  3.],
       [  7.],
       [ 11.],
       [ 15.]]),
 array([], dtype=float64)]

With a higher dimensional array the split is still along the second axis.

>>> x = np.arange(8.0).reshape(2, 2, 2)
>>> x
array([[[ 0.,  1.],
        [ 2.,  3.]],
       [[ 4.,  5.],
        [ 6.,  7.]]])
>>> np.hsplit(x, 2)
[array([[[ 0.,  1.]],
       [[ 4.,  5.]]]),
 array([[[ 2.,  3.]],
       [[ 6.,  7.]]])]


if len(_nx.shape(ary)) < <NUM_LIT:2>:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>return split(ary, indices_or_sections, <NUM_LIT:0>)<EOL>

Split an array into multiple sub-arrays vertically (row-wise).

Please refer to the ``split`` documentation.  ``vsplit`` is equivalent
to ``split`` with `axis=0` (default), the array is always split along the
first axis regardless of the array dimension.

See Also
--------
split : Split an array into multiple sub-arrays of equal size.

Examples
--------
>>> x = np.arange(16.0).reshape(4, 4)
>>> x
array([[  0.,   1.,   2.,   3.],
       [  4.,   5.,   6.,   7.],
       [  8.,   9.,  10.,  11.],
       [ 12.,  13.,  14.,  15.]])
>>> np.vsplit(x, 2)
[array([[ 0.,  1.,  2.,  3.],
       [ 4.,  5.,  6.,  7.]]),
 array([[  8.,   9.,  10.,  11.],
       [ 12.,  13.,  14.,  15.]])]
>>> np.vsplit(x, np.array([3, 6]))
[array([[  0.,   1.,   2.,   3.],
       [  4.,   5.,   6.,   7.],
       [  8.,   9.,  10.,  11.]]),
 array([[ 12.,  13.,  14.,  15.]]),
 array([], dtype=float64)]

With a higher dimensional array the split is still along the first axis.

>>> x = np.arange(8.0).reshape(2, 2, 2)
>>> x
array([[[ 0.,  1.],
        [ 2.,  3.]],
       [[ 4.,  5.],
        [ 6.,  7.]]])
>>> np.vsplit(x, 2)
[array([[[ 0.,  1.],
        [ 2.,  3.]]]),
 array([[[ 4.,  5.],
        [ 6.,  7.]]])]


if len(_nx.shape(ary)) < <NUM_LIT:3>:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>return split(ary, indices_or_sections, <NUM_LIT:2>)<EOL>

Split array into multiple sub-arrays along the 3rd axis (depth).

Please refer to the `split` documentation.  `dsplit` is equivalent
to `split` with ``axis=2``, the array is always split along the third
axis provided the array dimension is greater than or equal to 3.

See Also
--------
split : Split an array into multiple sub-arrays of equal size.

Examples
--------
>>> x = np.arange(16.0).reshape(2, 2, 4)
>>> x
array([[[  0.,   1.,   2.,   3.],
        [  4.,   5.,   6.,   7.]],
       [[  8.,   9.,  10.,  11.],
        [ 12.,  13.,  14.,  15.]]])
>>> np.dsplit(x, 2)
[array([[[  0.,   1.],
        [  4.,   5.]],
       [[  8.,   9.],
        [ 12.,  13.]]]),
 array([[[  2.,   3.],
        [  6.,   7.]],
       [[ 10.,  11.],
        [ 14.,  15.]]])]
>>> np.dsplit(x, np.array([3, 6]))
[array([[[  0.,   1.,   2.],
        [  4.,   5.,   6.]],
       [[  8.,   9.,  10.],
        [ 12.,  13.,  14.]]]),
 array([[[  3.],
        [  7.]],
       [[ 11.],
        [ 15.]]]),
 array([], dtype=float64)]


wrappers = sorted((getattr(x, '<STR_LIT>', <NUM_LIT:0>), -i,<EOL>x.__array_prepare__) for i, x in enumerate(args)<EOL>if hasattr(x, '<STR_LIT>'))<EOL>if wrappers:<EOL><INDENT>return wrappers[-<NUM_LIT:1>][-<NUM_LIT:1>]<EOL><DEDENT>return None<EOL>

Find the wrapper for the array with the highest priority.

    In case of ties, leftmost wins. If no wrapper is found, return None


wrappers = sorted((getattr(x, '<STR_LIT>', <NUM_LIT:0>), -i,<EOL>x.__array_wrap__) for i, x in enumerate(args)<EOL>if hasattr(x, '<STR_LIT>'))<EOL>if wrappers:<EOL><INDENT>return wrappers[-<NUM_LIT:1>][-<NUM_LIT:1>]<EOL><DEDENT>return None<EOL>


b = asanyarray(b)<EOL>a = array(a, copy=False, subok=True, ndmin=b.ndim)<EOL>ndb, nda = b.ndim, a.ndim<EOL>if (nda == <NUM_LIT:0> or ndb == <NUM_LIT:0>):<EOL><INDENT>return _nx.multiply(a, b)<EOL><DEDENT>as_ = a.shape<EOL>bs = b.shape<EOL>if not a.flags.contiguous:<EOL><INDENT>a = reshape(a, as_)<EOL><DEDENT>if not b.flags.contiguous:<EOL><INDENT>b = reshape(b, bs)<EOL><DEDENT>nd = ndb<EOL>if (ndb != nda):<EOL><INDENT>if (ndb > nda):<EOL><INDENT>as_ = (<NUM_LIT:1>,)*(ndb-nda) + as_<EOL><DEDENT>else:<EOL><INDENT>bs = (<NUM_LIT:1>,)*(nda-ndb) + bs<EOL>nd = nda<EOL><DEDENT><DEDENT>result = outer(a, b).reshape(as_+bs)<EOL>axis = nd-<NUM_LIT:1><EOL>for _ in range(nd):<EOL><INDENT>result = concatenate(result, axis=axis)<EOL><DEDENT>wrapper = get_array_prepare(a, b)<EOL>if wrapper is not None:<EOL><INDENT>result = wrapper(result)<EOL><DEDENT>wrapper = get_array_wrap(a, b)<EOL>if wrapper is not None:<EOL><INDENT>result = wrapper(result)<EOL><DEDENT>return result<EOL>

Kronecker product of two arrays.

Computes the Kronecker product, a composite array made of blocks of the
second array scaled by the first.

Parameters
----------
a, b : array_like

Returns
-------
out : ndarray

See Also
--------
outer : The outer product

Notes
-----
The function assumes that the number of dimenensions of `a` and `b`
are the same, if necessary prepending the smallest with ones.
If `a.shape = (r0,r1,..,rN)` and `b.shape = (s0,s1,...,sN)`,
the Kronecker product has shape `(r0*s0, r1*s1, ..., rN*SN)`.
The elements are products of elements from `a` and `b`, organized
explicitly by::

    kron(a,b)[k0,k1,...,kN] = a[i0,i1,...,iN] * b[j0,j1,...,jN]

where::

    kt = it * st + jt,  t = 0,...,N

In the common 2-D case (N=1), the block structure can be visualized::

    [[ a[0,0]*b,   a[0,1]*b,  ... , a[0,-1]*b  ],
     [  ...                              ...   ],
     [ a[-1,0]*b,  a[-1,1]*b, ... , a[-1,-1]*b ]]

Examples
--------
>>> np.kron([1,10,100], [5,6,7])
array([  5,   6,   7,  50,  60,  70, 500, 600, 700])
>>> np.kron([5,6,7], [1,10,100])
array([  5,  50, 500,   6,  60, 600,   7,  70, 700])

>>> np.kron(np.eye(2), np.ones((2,2)))
array([[ 1.,  1.,  0.,  0.],
       [ 1.,  1.,  0.,  0.],
       [ 0.,  0.,  1.,  1.],
       [ 0.,  0.,  1.,  1.]])

>>> a = np.arange(100).reshape((2,5,2,5))
>>> b = np.arange(24).reshape((2,3,4))
>>> c = np.kron(a,b)
>>> c.shape
(2, 10, 6, 20)
>>> I = (1,3,0,2)
>>> J = (0,2,1)
>>> J1 = (0,) + J             # extend to ndim=4
>>> S1 = (1,) + b.shape
>>> K = tuple(np.array(I) * np.array(S1) + np.array(J1))
>>> c[K] == a[I]*b[J]
True


try:<EOL><INDENT>tup = tuple(reps)<EOL><DEDENT>except TypeError:<EOL><INDENT>tup = (reps,)<EOL><DEDENT>d = len(tup)<EOL>c = _nx.array(A, copy=False, subok=True, ndmin=d)<EOL>shape = list(c.shape)<EOL>n = max(c.size, <NUM_LIT:1>)<EOL>if (d < c.ndim):<EOL><INDENT>tup = (<NUM_LIT:1>,)*(c.ndim-d) + tup<EOL><DEDENT>for i, nrep in enumerate(tup):<EOL><INDENT>if nrep != <NUM_LIT:1>:<EOL><INDENT>c = c.reshape(-<NUM_LIT:1>, n).repeat(nrep, <NUM_LIT:0>)<EOL><DEDENT>dim_in = shape[i]<EOL>dim_out = dim_in*nrep<EOL>shape[i] = dim_out<EOL>n //= max(dim_in, <NUM_LIT:1>)<EOL><DEDENT>return c.reshape(shape)<EOL>

Construct 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.

See Also
--------
repeat : Repeat elements of an array.

Examples
--------
>>> a = np.array([0, 1, 2])
>>> np.tile(a, 2)
array([0, 1, 2, 0, 1, 2])
>>> np.tile(a, (2, 2))
array([[0, 1, 2, 0, 1, 2],
       [0, 1, 2, 0, 1, 2]])
>>> np.tile(a, (2, 1, 2))
array([[[0, 1, 2, 0, 1, 2]],
       [[0, 1, 2, 0, 1, 2]]])

>>> b = np.array([[1, 2], [3, 4]])
>>> np.tile(b, 2)
array([[1, 2, 1, 2],
       [3, 4, 3, 4]])
>>> np.tile(b, (2, 1))
array([[1, 2],
       [3, 4],
       [1, 2],
       [3, 4]])


import numpy<EOL>if numpy.show_config is None:<EOL><INDENT>d = os.path.join(os.path.dirname(numpy.__file__), '<STR_LIT>', '<STR_LIT>')<EOL><DEDENT>else:<EOL><INDENT>import numpy.core as core<EOL>d = os.path.join(os.path.dirname(core.__file__), '<STR_LIT>')<EOL><DEDENT>return d<EOL>

Return the directory that contains the NumPy \\*.h header files.

Extension modules that need to compile against NumPy should use this
function to locate the appropriate include directory.

Notes
-----
When using ``distutils``, for example in ``setup.py``.
::

    import numpy as np
    ...
    Extension('extension_name', ...
            include_dirs=[np.get_include()])
    ...


<EOL>if args:<EOL><INDENT>fn = args[<NUM_LIT:0>]<EOL>args = args[<NUM_LIT:1>:]<EOL>if '<STR_LIT>' in kwargs:<EOL><INDENT>kwargs['<STR_LIT>'] = kwargs.pop('<STR_LIT>')<EOL><DEDENT>if '<STR_LIT>' in kwargs:<EOL><INDENT>kwargs['<STR_LIT>'] = kwargs.pop('<STR_LIT>')<EOL><DEDENT>return _Deprecate(*args, **kwargs)(fn)<EOL><DEDENT>else:<EOL><INDENT>return _Deprecate(*args, **kwargs)<EOL><DEDENT>

Issues a DeprecationWarning, adds warning to `old_name`'s
docstring, rebinds ``old_name.__name__`` and returns the new
function object.

This function may also be used as a decorator.

Parameters
----------
func : function
    The function to be deprecated.
old_name : str, optional
    The name of the function to be deprecated. Default is None, in
    which case the name of `func` is used.
new_name : str, optional
    The new name for the function. Default is None, in which case the
    deprecation message is that `old_name` is deprecated. If given, the
    deprecation message is that `old_name` is deprecated and `new_name`
    should be used instead.
message : str, optional
    Additional explanation of the deprecation.  Displayed in the
    docstring after the warning.

Returns
-------
old_func : function
    The deprecated function.

Examples
--------
Note that ``olduint`` returns a value after printing Deprecation
Warning:

>>> olduint = np.deprecate(np.uint)
>>> olduint(6)
/usr/lib/python2.5/site-packages/numpy/lib/utils.py:114:
DeprecationWarning: uint32 is deprecated
  warnings.warn(str1, DeprecationWarning)
6


ai = a.__array_interface__<EOL>a_data = ai['<STR_LIT:data>'][<NUM_LIT:0>]<EOL>astrides = ai['<STR_LIT>']<EOL>ashape = ai['<STR_LIT>']<EOL>bytes_a = asarray(a).dtype.itemsize<EOL>a_low = a_high = a_data<EOL>if astrides is None:<EOL><INDENT>a_high += a.size * bytes_a<EOL><DEDENT>else:<EOL><INDENT>for shape, stride in zip(ashape, astrides):<EOL><INDENT>if stride < <NUM_LIT:0>:<EOL><INDENT>a_low += (shape-<NUM_LIT:1>)*stride<EOL><DEDENT>else:<EOL><INDENT>a_high += (shape-<NUM_LIT:1>)*stride<EOL><DEDENT><DEDENT>a_high += bytes_a<EOL><DEDENT>return a_low, a_high<EOL>

Returns pointers to the end-points of an array.

Parameters
----------
a : ndarray
    Input array. It must conform to the Python-side of the array
    interface.

Returns
-------
(low, high) : tuple of 2 integers
    The first integer is the first byte of the array, the second
    integer is just past the last byte of the array.  If `a` is not
    contiguous it will not use every byte between the (`low`, `high`)
    values.

Examples
--------
>>> I = np.eye(2, dtype='f'); I.dtype
dtype('float32')
>>> low, high = np.byte_bounds(I)
>>> high - low == I.size*I.itemsize
True
>>> I = np.eye(2, dtype='G'); I.dtype
dtype('complex192')
>>> low, high = np.byte_bounds(I)
>>> high - low == I.size*I.itemsize
True


if vardict is None:<EOL><INDENT>frame = sys._getframe().f_back<EOL>vardict = frame.f_globals<EOL><DEDENT>sta = []<EOL>cache = {}<EOL>for name in vardict.keys():<EOL><INDENT>if isinstance(vardict[name], ndarray):<EOL><INDENT>var = vardict[name]<EOL>idv = id(var)<EOL>if idv in cache.keys():<EOL><INDENT>namestr = name + "<STR_LIT>" % cache[idv]<EOL>original = <NUM_LIT:0><EOL><DEDENT>else:<EOL><INDENT>cache[idv] = name<EOL>namestr = name<EOL>original = <NUM_LIT:1><EOL><DEDENT>shapestr = "<STR_LIT>".join(map(str, var.shape))<EOL>bytestr = str(var.nbytes)<EOL>sta.append([namestr, shapestr, bytestr, var.dtype.name,<EOL>original])<EOL><DEDENT><DEDENT>maxname = <NUM_LIT:0><EOL>maxshape = <NUM_LIT:0><EOL>maxbyte = <NUM_LIT:0><EOL>totalbytes = <NUM_LIT:0><EOL>for k in range(len(sta)):<EOL><INDENT>val = sta[k]<EOL>if maxname < len(val[<NUM_LIT:0>]):<EOL><INDENT>maxname = len(val[<NUM_LIT:0>])<EOL><DEDENT>if maxshape < len(val[<NUM_LIT:1>]):<EOL><INDENT>maxshape = len(val[<NUM_LIT:1>])<EOL><DEDENT>if maxbyte < len(val[<NUM_LIT:2>]):<EOL><INDENT>maxbyte = len(val[<NUM_LIT:2>])<EOL><DEDENT>if val[<NUM_LIT:4>]:<EOL><INDENT>totalbytes += int(val[<NUM_LIT:2>])<EOL><DEDENT><DEDENT>if len(sta) > <NUM_LIT:0>:<EOL><INDENT>sp1 = max(<NUM_LIT:10>, maxname)<EOL>sp2 = max(<NUM_LIT:10>, maxshape)<EOL>sp3 = max(<NUM_LIT:10>, maxbyte)<EOL>prval = "<STR_LIT>" % (sp1*'<STR_LIT:U+0020>', sp2*'<STR_LIT:U+0020>', sp3*'<STR_LIT:U+0020>')<EOL>print(prval + "<STR_LIT:\n>" + "<STR_LIT:=>"*(len(prval)+<NUM_LIT:5>) + "<STR_LIT:\n>")<EOL><DEDENT>for k in range(len(sta)):<EOL><INDENT>val = sta[k]<EOL>print("<STR_LIT>" % (val[<NUM_LIT:0>], '<STR_LIT:U+0020>'*(sp1-len(val[<NUM_LIT:0>])+<NUM_LIT:4>),<EOL>val[<NUM_LIT:1>], '<STR_LIT:U+0020>'*(sp2-len(val[<NUM_LIT:1>])+<NUM_LIT:5>),<EOL>val[<NUM_LIT:2>], '<STR_LIT:U+0020>'*(sp3-len(val[<NUM_LIT:2>])+<NUM_LIT:5>),<EOL>val[<NUM_LIT:3>]))<EOL><DEDENT>print("<STR_LIT>" % totalbytes)<EOL>return<EOL>

Print the Numpy arrays in the given dictionary.

If there is no dictionary passed in or `vardict` is None then returns
Numpy arrays in the globals() dictionary (all Numpy arrays in the
namespace).

Parameters
----------
vardict : dict, optional
    A dictionary possibly containing ndarrays.  Default is globals().

Returns
-------
out : None
    Returns 'None'.

Notes
-----
Prints out the name, shape, bytes and type of all of the ndarrays
present in `vardict`.

Examples
--------
>>> a = np.arange(10)
>>> b = np.ones(20)
>>> np.who()
Name            Shape            Bytes            Type
===========================================================
a               10               40               int32
b               20               160              float64
Upper bound on total bytes  =       200

>>> d = {'x': np.arange(2.0), 'y': np.arange(3.0), 'txt': 'Some str',
... 'idx':5}
>>> np.who(d)
Name            Shape            Bytes            Type
===========================================================
y               3                24               float64
x               2                16               float64
Upper bound on total bytes  =       40


extra = "<STR_LIT>"<EOL>tic = "<STR_LIT>"<EOL>bp = lambda x: x<EOL>cls = getattr(obj, '<STR_LIT>', type(obj))<EOL>nm = getattr(cls, '<STR_LIT>', cls)<EOL>strides = obj.strides<EOL>endian = obj.dtype.byteorder<EOL>print("<STR_LIT>", nm, file=output)<EOL>print("<STR_LIT>", obj.shape, file=output)<EOL>print("<STR_LIT>", strides, file=output)<EOL>print("<STR_LIT>", obj.itemsize, file=output)<EOL>print("<STR_LIT>", bp(obj.flags.aligned), file=output)<EOL>print("<STR_LIT>", bp(obj.flags.contiguous), file=output)<EOL>print("<STR_LIT>", obj.flags.fortran, file=output)<EOL>print(<EOL>"<STR_LIT>" % (hex(obj.ctypes._as_parameter_.value), extra),<EOL>file=output<EOL>)<EOL>print("<STR_LIT>", end='<STR_LIT:U+0020>', file=output)<EOL>if endian in ['<STR_LIT:|>', '<STR_LIT:=>']:<EOL><INDENT>print("<STR_LIT>" % (tic, sys.byteorder, tic), file=output)<EOL>byteswap = False<EOL><DEDENT>elif endian == '<STR_LIT:>>':<EOL><INDENT>print("<STR_LIT>" % (tic, tic), file=output)<EOL>byteswap = sys.byteorder != "<STR_LIT>"<EOL><DEDENT>else:<EOL><INDENT>print("<STR_LIT>" % (tic, tic), file=output)<EOL>byteswap = sys.byteorder != "<STR_LIT>"<EOL><DEDENT>print("<STR_LIT>", bp(byteswap), file=output)<EOL>print("<STR_LIT>" % obj.dtype, file=output)<EOL>

Provide information about ndarray obj.

    Parameters
    ----------
    obj: ndarray
        Must be ndarray, not checked.
    output:
        Where printed output goes.

    Notes
    -----
    Copied over from the numarray module prior to its removal.
    Adapted somewhat as only numpy is an option now.

    Called by info.


def info(object=None, maxwidth=<NUM_LIT>, output=sys.stdout, toplevel='<STR_LIT>'):

global _namedict, _dictlist<EOL>import pydoc<EOL>import inspect<EOL>if (hasattr(object, '<STR_LIT>') or<EOL>hasattr(object, '<STR_LIT>')):<EOL><INDENT>object = object._ppimport_module<EOL><DEDENT>elif hasattr(object, '<STR_LIT>'):<EOL><INDENT>object = object._ppimport_attr<EOL><DEDENT>if object is None:<EOL><INDENT>info(info)<EOL><DEDENT>elif isinstance(object, ndarray):<EOL><INDENT>_info(object, output=output)<EOL><DEDENT>elif isinstance(object, str):<EOL><INDENT>if _namedict is None:<EOL><INDENT>_namedict, _dictlist = _makenamedict(toplevel)<EOL><DEDENT>numfound = <NUM_LIT:0><EOL>objlist = []<EOL>for namestr in _dictlist:<EOL><INDENT>try:<EOL><INDENT>obj = _namedict[namestr][object]<EOL>if id(obj) in objlist:<EOL><INDENT>print("<STR_LIT>"<EOL>"<STR_LIT>" % namestr,<EOL>file=output<EOL>)<EOL><DEDENT>else:<EOL><INDENT>objlist.append(id(obj))<EOL>print("<STR_LIT>" % namestr, file=output)<EOL>info(obj)<EOL>print("<STR_LIT:->"*maxwidth, file=output)<EOL><DEDENT>numfound += <NUM_LIT:1><EOL><DEDENT>except KeyError:<EOL><INDENT>pass<EOL><DEDENT><DEDENT>if numfound == <NUM_LIT:0>:<EOL><INDENT>print("<STR_LIT>" % object, file=output)<EOL><DEDENT>else:<EOL><INDENT>print("<STR_LIT>"<EOL>"<STR_LIT>" % numfound,<EOL>file=output<EOL>)<EOL><DEDENT><DEDENT>elif inspect.isfunction(object):<EOL><INDENT>name = object.__name__<EOL>arguments = inspect.formatargspec(*inspect.getargspec(object))<EOL>if len(name+arguments) > maxwidth:<EOL><INDENT>argstr = _split_line(name, arguments, maxwidth)<EOL><DEDENT>else:<EOL><INDENT>argstr = name + arguments<EOL><DEDENT>print("<STR_LIT:U+0020>" + argstr + "<STR_LIT:\n>", file=output)<EOL>print(inspect.getdoc(object), file=output)<EOL><DEDENT>elif inspect.isclass(object):<EOL><INDENT>name = object.__name__<EOL>arguments = "<STR_LIT>"<EOL>try:<EOL><INDENT>if hasattr(object, '<STR_LIT>'):<EOL><INDENT>arguments = inspect.formatargspec(<EOL>*inspect.getargspec(object.__init__.__func__)<EOL>)<EOL>arglist = arguments.split('<STR_LIT:U+002CU+0020>')<EOL>if len(arglist) > <NUM_LIT:1>:<EOL><INDENT>arglist[<NUM_LIT:1>] = "<STR_LIT:(>"+arglist[<NUM_LIT:1>]<EOL>arguments = "<STR_LIT:U+002CU+0020>".join(arglist[<NUM_LIT:1>:])<EOL><DEDENT><DEDENT><DEDENT>except:<EOL><INDENT>pass<EOL><DEDENT>if len(name+arguments) > maxwidth:<EOL><INDENT>argstr = _split_line(name, arguments, maxwidth)<EOL><DEDENT>else:<EOL><INDENT>argstr = name + arguments<EOL><DEDENT>print("<STR_LIT:U+0020>" + argstr + "<STR_LIT:\n>", file=output)<EOL>doc1 = inspect.getdoc(object)<EOL>if doc1 is None:<EOL><INDENT>if hasattr(object, '<STR_LIT>'):<EOL><INDENT>print(inspect.getdoc(object.__init__), file=output)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>print(inspect.getdoc(object), file=output)<EOL><DEDENT>methods = pydoc.allmethods(object)<EOL>if methods != []:<EOL><INDENT>print("<STR_LIT>", file=output)<EOL>for meth in methods:<EOL><INDENT>if meth[<NUM_LIT:0>] == '<STR_LIT:_>':<EOL><INDENT>continue<EOL><DEDENT>thisobj = getattr(object, meth, None)<EOL>if thisobj is not None:<EOL><INDENT>methstr, other = pydoc.splitdoc(<EOL>inspect.getdoc(thisobj) or "<STR_LIT:None>"<EOL>)<EOL><DEDENT>print("<STR_LIT>" % (meth, methstr), file=output)<EOL><DEDENT><DEDENT><DEDENT>elif (sys.version_info[<NUM_LIT:0>] < <NUM_LIT:3><EOL>and isinstance(object, types.InstanceType)):<EOL><INDENT>print("<STR_LIT>", object.__class__.__name__, file=output)<EOL>print(file=output)<EOL>if hasattr(object, '<STR_LIT>'):<EOL><INDENT>arguments = inspect.formatargspec(<EOL>*inspect.getargspec(object.__call__.__func__)<EOL>)<EOL>arglist = arguments.split('<STR_LIT:U+002CU+0020>')<EOL>if len(arglist) > <NUM_LIT:1>:<EOL><INDENT>arglist[<NUM_LIT:1>] = "<STR_LIT:(>"+arglist[<NUM_LIT:1>]<EOL>arguments = "<STR_LIT:U+002CU+0020>".join(arglist[<NUM_LIT:1>:])<EOL><DEDENT>else:<EOL><INDENT>arguments = "<STR_LIT>"<EOL><DEDENT>if hasattr(object, '<STR_LIT:name>'):<EOL><INDENT>name = "<STR_LIT:%s>" % object.name<EOL><DEDENT>else:<EOL><INDENT>name = "<STR_LIT>"<EOL><DEDENT>if len(name+arguments) > maxwidth:<EOL><INDENT>argstr = _split_line(name, arguments, maxwidth)<EOL><DEDENT>else:<EOL><INDENT>argstr = name + arguments<EOL><DEDENT>print("<STR_LIT:U+0020>" + argstr + "<STR_LIT:\n>", file=output)<EOL>doc = inspect.getdoc(object.__call__)<EOL>if doc is not None:<EOL><INDENT>print(inspect.getdoc(object.__call__), file=output)<EOL><DEDENT>print(inspect.getdoc(object), file=output)<EOL><DEDENT>else:<EOL><INDENT>print(inspect.getdoc(object), file=output)<EOL><DEDENT><DEDENT>elif inspect.ismethod(object):<EOL><INDENT>name = object.__name__<EOL>arguments = inspect.formatargspec(<EOL>*inspect.getargspec(object.__func__)<EOL>)<EOL>arglist = arguments.split('<STR_LIT:U+002CU+0020>')<EOL>if len(arglist) > <NUM_LIT:1>:<EOL><INDENT>arglist[<NUM_LIT:1>] = "<STR_LIT:(>"+arglist[<NUM_LIT:1>]<EOL>arguments = "<STR_LIT:U+002CU+0020>".join(arglist[<NUM_LIT:1>:])<EOL><DEDENT>else:<EOL><INDENT>arguments = "<STR_LIT>"<EOL><DEDENT>if len(name+arguments) > maxwidth:<EOL><INDENT>argstr = _split_line(name, arguments, maxwidth)<EOL><DEDENT>else:<EOL><INDENT>argstr = name + arguments<EOL><DEDENT>print("<STR_LIT:U+0020>" + argstr + "<STR_LIT:\n>", file=output)<EOL>print(inspect.getdoc(object), file=output)<EOL><DEDENT>elif hasattr(object, '<STR_LIT>'):<EOL><INDENT>print(inspect.getdoc(object), file=output)<EOL><DEDENT>

Get help information for a function, class, or module.

Parameters
----------
object : object or str, optional
    Input object or name to get information about. If `object` is a
    numpy object, its docstring is given. If it is a string, available
    modules are searched for matching objects.  If None, information
    about `info` itself is returned.
maxwidth : int, optional
    Printing width.
output : file like object, optional
    File like object that the output is written to, default is
    ``stdout``.  The object has to be opened in 'w' or 'a' mode.
toplevel : str, optional
    Start search at this level.

See Also
--------
source, lookfor

Notes
-----
When used interactively with an object, ``np.info(obj)`` is equivalent
to ``help(obj)`` on the Python prompt or ``obj?`` on the IPython
prompt.

Examples
--------
>>> np.info(np.polyval) # doctest: +SKIP
   polyval(p, x)
     Evaluate the polynomial p at x.
     ...

When using a string for `object` it is possible to get multiple results.

>>> np.info('fft') # doctest: +SKIP
     *** Found in numpy ***
Core FFT routines
...
     *** Found in numpy.fft ***
 fft(a, n=None, axis=-1)
...
     *** Repeat reference found in numpy.fft.fftpack ***
     *** Total of 3 references found. ***


<EOL>import inspect<EOL>try:<EOL><INDENT>print("<STR_LIT>" % inspect.getsourcefile(object), file=output)<EOL>print(inspect.getsource(object), file=output)<EOL><DEDENT>except:<EOL><INDENT>print("<STR_LIT>", file=output)<EOL><DEDENT>

Print or write to a file the source code for a Numpy object.

The source code is only returned for objects written in Python. Many
functions and classes are defined in C and will therefore not return
useful information.

Parameters
----------
object : numpy object
    Input object. This can be any object (function, class, module,
    ...).
output : file object, optional
    If `output` not supplied then source code is printed to screen
    (sys.stdout).  File object must be created with either write 'w' or
    append 'a' modes.

See Also
--------
lookfor, info

Examples
--------
>>> np.source(np.interp)                        #doctest: +SKIP
In file: /usr/lib/python2.6/dist-packages/numpy/lib/function_base.py
def interp(x, xp, fp, left=None, right=None):
    \"\"\".... (full docstring printed)\"\"\"
    if isinstance(x, (float, int, number)):
        return compiled_interp([x], xp, fp, left, right).item()
    else:
        return compiled_interp(x, xp, fp, left, right)

The source code is only returned for objects written in Python.

>>> np.source(np.array)                         #doctest: +SKIP
Not available for this object.


def lookfor(what, module=None, import_modules=True, regenerate=False,<EOL>output=None):

import pydoc<EOL>cache = _lookfor_generate_cache(module, import_modules, regenerate)<EOL>found = []<EOL>whats = str(what).lower().split()<EOL>if not whats:<EOL><INDENT>return<EOL><DEDENT>for name, (docstring, kind, index) in cache.items():<EOL><INDENT>if kind in ('<STR_LIT>', '<STR_LIT:object>'):<EOL><INDENT>continue<EOL><DEDENT>ok = True<EOL>doc = docstring.lower()<EOL>for w in whats:<EOL><INDENT>if w not in doc:<EOL><INDENT>ok = False<EOL>break<EOL><DEDENT><DEDENT>if ok:<EOL><INDENT>found.append(name)<EOL><DEDENT><DEDENT>kind_relevance = {'<STR_LIT>': <NUM_LIT:1000>, '<STR_LIT:class>': <NUM_LIT:1000>,<EOL>'<STR_LIT>': -<NUM_LIT:1000>, '<STR_LIT:object>': -<NUM_LIT:1000>}<EOL>def relevance(name, docstr, kind, index):<EOL><INDENT>r = <NUM_LIT:0><EOL>first_doc = "<STR_LIT:\n>".join(docstr.lower().strip().split("<STR_LIT:\n>")[:<NUM_LIT:3>])<EOL>r += sum([<NUM_LIT:200> for w in whats if w in first_doc])<EOL>r += sum([<NUM_LIT:30> for w in whats if w in name])<EOL>r += -len(name) * <NUM_LIT:5><EOL>r += kind_relevance.get(kind, -<NUM_LIT:1000>)<EOL>r += -name.count('<STR_LIT:.>') * <NUM_LIT:10><EOL>r += max(-index / <NUM_LIT:100>, -<NUM_LIT:100>)<EOL>return r<EOL><DEDENT>def relevance_value(a):<EOL><INDENT>return relevance(a, *cache[a])<EOL><DEDENT>found.sort(key=relevance_value)<EOL>s = "<STR_LIT>" % ('<STR_LIT:U+0020>'.join(whats))<EOL>help_text = [s, "<STR_LIT:->"*len(s)]<EOL>for name in found[::-<NUM_LIT:1>]:<EOL><INDENT>doc, kind, ix = cache[name]<EOL>doclines = [line.strip() for line in doc.strip().split("<STR_LIT:\n>")<EOL>if line.strip()]<EOL>try:<EOL><INDENT>first_doc = doclines[<NUM_LIT:0>].strip()<EOL>if _function_signature_re.search(first_doc):<EOL><INDENT>first_doc = doclines[<NUM_LIT:1>].strip()<EOL><DEDENT><DEDENT>except IndexError:<EOL><INDENT>first_doc = "<STR_LIT>"<EOL><DEDENT>help_text.append("<STR_LIT>" % (name, first_doc))<EOL><DEDENT>if not found:<EOL><INDENT>help_text.append("<STR_LIT>")<EOL><DEDENT>if output is not None:<EOL><INDENT>output.write("<STR_LIT:\n>".join(help_text))<EOL><DEDENT>elif len(help_text) > <NUM_LIT:10>:<EOL><INDENT>pager = pydoc.getpager()<EOL>pager("<STR_LIT:\n>".join(help_text))<EOL><DEDENT>else:<EOL><INDENT>print("<STR_LIT:\n>".join(help_text))<EOL><DEDENT>

Do a keyword search on docstrings.

A list of of objects that matched the search is displayed,
sorted by relevance. All given keywords need to be found in the
docstring for it to be returned as a result, but the order does
not matter.

Parameters
----------
what : str
    String containing words to look for.
module : str or list, optional
    Name of module(s) whose docstrings to go through.
import_modules : bool, optional
    Whether to import sub-modules in packages. Default is True.
regenerate : bool, optional
    Whether to re-generate the docstring cache. Default is False.
output : file-like, optional
    File-like object to write the output to. If omitted, use a pager.

See Also
--------
source, info

Notes
-----
Relevance is determined only roughly, by checking if the keywords occur
in the function name, at the start of a docstring, etc.

Examples
--------
>>> np.lookfor('binary representation')
Search results for 'binary representation'
------------------------------------------
numpy.binary_repr
    Return the binary representation of the input number as a string.
numpy.core.setup_common.long_double_representation
    Given a binary dump as given by GNU od -b, look for long double
numpy.base_repr
    Return a string representation of a number in the given base system.
...


def _lookfor_generate_cache(module, import_modules, regenerate):

global _lookfor_caches<EOL>import inspect<EOL>if sys.version_info[<NUM_LIT:0>] >= <NUM_LIT:3>:<EOL><INDENT>from io import StringIO<EOL><DEDENT>else:<EOL><INDENT>from StringIO import StringIO<EOL><DEDENT>if module is None:<EOL><INDENT>module = "<STR_LIT>"<EOL><DEDENT>if isinstance(module, str):<EOL><INDENT>try:<EOL><INDENT>__import__(module)<EOL><DEDENT>except ImportError:<EOL><INDENT>return {}<EOL><DEDENT>module = sys.modules[module]<EOL><DEDENT>elif isinstance(module, list) or isinstance(module, tuple):<EOL><INDENT>cache = {}<EOL>for mod in module:<EOL><INDENT>cache.update(_lookfor_generate_cache(mod, import_modules,<EOL>regenerate))<EOL><DEDENT>return cache<EOL><DEDENT>if id(module) in _lookfor_caches and not regenerate:<EOL><INDENT>return _lookfor_caches[id(module)]<EOL><DEDENT>cache = {}<EOL>_lookfor_caches[id(module)] = cache<EOL>seen = {}<EOL>index = <NUM_LIT:0><EOL>stack = [(module.__name__, module)]<EOL>while stack:<EOL><INDENT>name, item = stack.pop(<NUM_LIT:0>)<EOL>if id(item) in seen:<EOL><INDENT>continue<EOL><DEDENT>seen[id(item)] = True<EOL>index += <NUM_LIT:1><EOL>kind = "<STR_LIT:object>"<EOL>if inspect.ismodule(item):<EOL><INDENT>kind = "<STR_LIT>"<EOL>try:<EOL><INDENT>_all = item.__all__<EOL><DEDENT>except AttributeError:<EOL><INDENT>_all = None<EOL><DEDENT>if import_modules and hasattr(item, '<STR_LIT>'):<EOL><INDENT>for pth in item.__path__:<EOL><INDENT>for mod_path in os.listdir(pth):<EOL><INDENT>this_py = os.path.join(pth, mod_path)<EOL>init_py = os.path.join(pth, mod_path, '<STR_LIT>')<EOL>if (os.path.isfile(this_py) and<EOL>mod_path.endswith('<STR_LIT>')):<EOL><INDENT>to_import = mod_path[:-<NUM_LIT:3>]<EOL><DEDENT>elif os.path.isfile(init_py):<EOL><INDENT>to_import = mod_path<EOL><DEDENT>else:<EOL><INDENT>continue<EOL><DEDENT>if to_import == '<STR_LIT>':<EOL><INDENT>continue<EOL><DEDENT>try:<EOL><INDENT>base_exc = BaseException<EOL><DEDENT>except NameError:<EOL><INDENT>base_exc = Exception<EOL><DEDENT>try:<EOL><INDENT>old_stdout = sys.stdout<EOL>old_stderr = sys.stderr<EOL>try:<EOL><INDENT>sys.stdout = StringIO()<EOL>sys.stderr = StringIO()<EOL>__import__("<STR_LIT>" % (name, to_import))<EOL><DEDENT>finally:<EOL><INDENT>sys.stdout = old_stdout<EOL>sys.stderr = old_stderr<EOL><DEDENT><DEDENT>except base_exc:<EOL><INDENT>continue<EOL><DEDENT><DEDENT><DEDENT><DEDENT>for n, v in _getmembers(item):<EOL><INDENT>try:<EOL><INDENT>item_name = getattr(v, '<STR_LIT>', "<STR_LIT>" % (name, n))<EOL>mod_name = getattr(v, '<STR_LIT>', None)<EOL><DEDENT>except NameError:<EOL><INDENT>item_name = "<STR_LIT>" % (name, n)<EOL>mod_name = None<EOL><DEDENT>if '<STR_LIT:.>' not in item_name and mod_name:<EOL><INDENT>item_name = "<STR_LIT>" % (mod_name, item_name)<EOL><DEDENT>if not item_name.startswith(name + '<STR_LIT:.>'):<EOL><INDENT>if isinstance(v, ufunc):<EOL><INDENT>pass<EOL><DEDENT>else:<EOL><INDENT>continue<EOL><DEDENT><DEDENT>elif not (inspect.ismodule(v) or _all is None or n in _all):<EOL><INDENT>continue<EOL><DEDENT>stack.append(("<STR_LIT>" % (name, n), v))<EOL><DEDENT><DEDENT>elif inspect.isclass(item):<EOL><INDENT>kind = "<STR_LIT:class>"<EOL>for n, v in _getmembers(item):<EOL><INDENT>stack.append(("<STR_LIT>" % (name, n), v))<EOL><DEDENT><DEDENT>elif hasattr(item, "<STR_LIT>"):<EOL><INDENT>kind = "<STR_LIT>"<EOL><DEDENT>try:<EOL><INDENT>doc = inspect.getdoc(item)<EOL><DEDENT>except NameError:<EOL><INDENT>doc = None<EOL><DEDENT>if doc is not None:<EOL><INDENT>cache[name] = (doc, kind, index)<EOL><DEDENT><DEDENT>return cache<EOL>

Generate docstring cache for given module.

Parameters
----------
module : str, None, module
    Module for which to generate docstring cache
import_modules : bool
    Whether to import sub-modules in packages.
regenerate : bool
    Re-generate the docstring cache

Returns
-------
cache : dict {obj_full_name: (docstring, kind, index), ...}
    Docstring cache for the module, either cached one (regenerate=False)
    or newly generated.


<EOL>import warnings<EOL>with warnings.catch_warnings():<EOL><INDENT>warnings.simplefilter('<STR_LIT:ignore>', DeprecationWarning)<EOL>try:<EOL><INDENT>import compiler<EOL><DEDENT>except ImportError:<EOL><INDENT>import ast as compiler<EOL><DEDENT><DEDENT>walker = SafeEval()<EOL>try:<EOL><INDENT>ast = compiler.parse(source, mode="<STR_LIT>")<EOL><DEDENT>except SyntaxError:<EOL><INDENT>raise<EOL><DEDENT>try:<EOL><INDENT>return walker.visit(ast)<EOL><DEDENT>except SyntaxError:<EOL><INDENT>raise<EOL><DEDENT>

Protected string evaluation.

Evaluate a string containing a Python literal expression without
allowing the execution of arbitrary non-literal code.

Parameters
----------
source : str
    The string to evaluate.

Returns
-------
obj : object
   The result of evaluating `source`.

Raises
------
SyntaxError
    If the code has invalid Python syntax, or if it contains
    non-literal code.

Examples
--------
>>> np.safe_eval('1')
1
>>> np.safe_eval('[1, 2, 3]')
[1, 2, 3]
>>> np.safe_eval('{"foo": ("bar", 10.0)}')
{'foo': ('bar', 10.0)}

>>> np.safe_eval('import os')
Traceback (most recent call last):
  ...
SyntaxError: invalid syntax

>>> np.safe_eval('open("/home/user/.ssh/id_dsa").read()')
Traceback (most recent call last):
  ...
SyntaxError: Unsupported source construct: compiler.ast.CallFunc


def __call__(self, func, *args, **kwargs):

old_name = self.old_name<EOL>new_name = self.new_name<EOL>message = self.message<EOL>import warnings<EOL>if old_name is None:<EOL><INDENT>try:<EOL><INDENT>old_name = func.__name__<EOL><DEDENT>except AttributeError:<EOL><INDENT>old_name = func.__name__<EOL><DEDENT><DEDENT>if new_name is None:<EOL><INDENT>depdoc = "<STR_LIT>" % old_name<EOL><DEDENT>else:<EOL><INDENT>depdoc = "<STR_LIT>" %(old_name, new_name)<EOL><DEDENT>if message is not None:<EOL><INDENT>depdoc += "<STR_LIT:\n>" + message<EOL><DEDENT>def newfunc(*args,**kwds):<EOL><INDENT>"""<STR_LIT>"""<EOL>warnings.warn(depdoc, DeprecationWarning)<EOL>return func(*args, **kwds)<EOL><DEDENT>newfunc = _set_function_name(newfunc, old_name)<EOL>doc = func.__doc__<EOL>if doc is None:<EOL><INDENT>doc = depdoc<EOL><DEDENT>else:<EOL><INDENT>doc = '<STR_LIT>'.join([depdoc, doc])<EOL><DEDENT>newfunc.__doc__ = doc<EOL>try:<EOL><INDENT>d = func.__dict__<EOL><DEDENT>except AttributeError:<EOL><INDENT>pass<EOL><DEDENT>else:<EOL><INDENT>newfunc.__dict__.update(d)<EOL><DEDENT>return newfunc<EOL>


def ediff1d(ary, to_end=None, to_begin=None):

ary = np.asanyarray(ary).flat<EOL>ed = ary[<NUM_LIT:1>:] - ary[:-<NUM_LIT:1>]<EOL>arrays = [ed]<EOL>if to_begin is not None:<EOL><INDENT>arrays.insert(<NUM_LIT:0>, to_begin)<EOL><DEDENT>if to_end is not None:<EOL><INDENT>arrays.append(to_end)<EOL><DEDENT>if len(arrays) != <NUM_LIT:1>:<EOL><INDENT>ed = np.hstack(arrays)<EOL><DEDENT>return ed<EOL>

The differences between consecutive elements of an array.

Parameters
----------
ary : array_like
    If necessary, will be flattened before the differences are taken.
to_end : array_like, optional
    Number(s) to append at the end of the returned differences.
to_begin : array_like, optional
    Number(s) to prepend at the beginning of the returned differences.

Returns
-------
ediff1d : ndarray
    The differences. Loosely, this is ``ary.flat[1:] - ary.flat[:-1]``.

See Also
--------
diff, gradient

Notes
-----
When applied to masked arrays, this function drops the mask information
if the `to_begin` and/or `to_end` parameters are used.

Examples
--------
>>> x = np.array([1, 2, 4, 7, 0])
>>> np.ediff1d(x)
array([ 1,  2,  3, -7])

>>> np.ediff1d(x, to_begin=-99, to_end=np.array([88, 99]))
array([-99,   1,   2,   3,  -7,  88,  99])

The returned array is always 1D.

>>> y = [[1, 2, 4], [1, 6, 24]]
>>> np.ediff1d(y)
array([ 1,  2, -3,  5, 18])


def unique(ar, return_index=False, return_inverse=False, return_counts=False):

ar = np.asanyarray(ar).flatten()<EOL>optional_indices = return_index or return_inverse<EOL>optional_returns = optional_indices or return_counts<EOL>if ar.size == <NUM_LIT:0>:<EOL><INDENT>if not optional_returns:<EOL><INDENT>ret = ar<EOL><DEDENT>else:<EOL><INDENT>ret = (ar,)<EOL>if return_index:<EOL><INDENT>ret += (np.empty(<NUM_LIT:0>, np.bool),)<EOL><DEDENT>if return_inverse:<EOL><INDENT>ret += (np.empty(<NUM_LIT:0>, np.bool),)<EOL><DEDENT>if return_counts:<EOL><INDENT>ret += (np.empty(<NUM_LIT:0>, np.intp),)<EOL><DEDENT><DEDENT>return ret<EOL><DEDENT>if optional_indices:<EOL><INDENT>perm = ar.argsort(kind='<STR_LIT>' if return_index else '<STR_LIT>')<EOL>aux = ar[perm]<EOL><DEDENT>else:<EOL><INDENT>ar.sort()<EOL>aux = ar<EOL><DEDENT>flag = np.concatenate(([True], aux[<NUM_LIT:1>:] != aux[:-<NUM_LIT:1>]))<EOL>if not optional_returns:<EOL><INDENT>ret = aux[flag]<EOL><DEDENT>else:<EOL><INDENT>ret = (aux[flag],)<EOL>if return_index:<EOL><INDENT>ret += (perm[flag],)<EOL><DEDENT>if return_inverse:<EOL><INDENT>iflag = np.cumsum(flag) - <NUM_LIT:1><EOL>iperm = perm.argsort()<EOL>ret += (np.take(iflag, iperm),)<EOL><DEDENT>if return_counts:<EOL><INDENT>idx = np.concatenate(np.nonzero(flag) + ([ar.size],))<EOL>ret += (np.diff(idx),)<EOL><DEDENT><DEDENT>return ret<EOL>

Find 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, and the number of times each unique value
comes up in the input array.

Parameters
----------
ar : array_like
    Input array. This will be flattened if it is not already 1-D.
return_index : bool, optional
    If True, also return the indices of `ar` that result in the unique
    array.
return_inverse : bool, optional
    If True, also return the indices of the unique array that can be used
    to reconstruct `ar`.
return_counts : bool, optional
    .. versionadded:: 1.9.0
    If True, also return the number of times each unique value comes up
    in `ar`.

Returns
-------
unique : ndarray
    The sorted unique values.
unique_indices : ndarray, optional
    The indices of the first occurrences of the unique values in the
    (flattened) original array. Only provided if `return_index` is True.
unique_inverse : ndarray, optional
    The indices to reconstruct the (flattened) original array from the
    unique array. Only provided if `return_inverse` is True.
unique_counts : ndarray, optional
    .. versionadded:: 1.9.0
    The number of times each of the unique values comes up in the
    original array. Only provided if `return_counts` is True.

See Also
--------
numpy.lib.arraysetops : Module with a number of other functions for
                        performing set operations on arrays.

Examples
--------
>>> np.unique([1, 1, 2, 2, 3, 3])
array([1, 2, 3])
>>> a = np.array([[1, 1], [2, 3]])
>>> np.unique(a)
array([1, 2, 3])

Return the indices of the original array that give the unique values:

>>> a = np.array(['a', 'b', 'b', 'c', 'a'])
>>> u, indices = np.unique(a, return_index=True)
>>> u
array(['a', 'b', 'c'],
       dtype='|S1')
>>> indices
array([0, 1, 3])
>>> a[indices]
array(['a', 'b', 'c'],
       dtype='|S1')

Reconstruct the input array from the unique values:

>>> a = np.array([1, 2, 6, 4, 2, 3, 2])
>>> u, indices = np.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])


def intersect1d(ar1, ar2, assume_unique=False):

if not assume_unique:<EOL><INDENT>ar1 = unique(ar1)<EOL>ar2 = unique(ar2)<EOL><DEDENT>aux = np.concatenate((ar1, ar2))<EOL>aux.sort()<EOL>return aux[:-<NUM_LIT:1>][aux[<NUM_LIT:1>:] == aux[:-<NUM_LIT:1>]]<EOL>

Find the intersection of two arrays.

Return the sorted, unique values that are in both of the input arrays.

Parameters
----------
ar1, ar2 : array_like
    Input arrays.
assume_unique : bool
    If True, the input arrays are both assumed to be unique, which
    can speed up the calculation.  Default is False.

Returns
-------
intersect1d : ndarray
    Sorted 1D array of common and unique elements.

See Also
--------
numpy.lib.arraysetops : Module with a number of other functions for
                        performing set operations on arrays.

Examples
--------
>>> np.intersect1d([1, 3, 4, 3], [3, 1, 2, 1])
array([1, 3])


def setxor1d(ar1, ar2, assume_unique=False):

if not assume_unique:<EOL><INDENT>ar1 = unique(ar1)<EOL>ar2 = unique(ar2)<EOL><DEDENT>aux = np.concatenate((ar1, ar2))<EOL>if aux.size == <NUM_LIT:0>:<EOL><INDENT>return aux<EOL><DEDENT>aux.sort()<EOL><INDENT>flag = ediff1d( aux, to_end = <NUM_LIT:1>, to_begin = <NUM_LIT:1> ) == <NUM_LIT:0><EOL><DEDENT>flag = np.concatenate(([True], aux[<NUM_LIT:1>:] != aux[:-<NUM_LIT:1>], [True]))<EOL><INDENT>flag2 = ediff1d( flag ) == <NUM_LIT:0><EOL><DEDENT>flag2 = flag[<NUM_LIT:1>:] == flag[:-<NUM_LIT:1>]<EOL>return aux[flag2]<EOL>

Find the set exclusive-or of two arrays.

Return the sorted, unique values that are in only one (not both) of the
input arrays.

Parameters
----------
ar1, ar2 : array_like
    Input arrays.
assume_unique : bool
    If True, the input arrays are both assumed to be unique, which
    can speed up the calculation.  Default is False.

Returns
-------
setxor1d : ndarray
    Sorted 1D array of unique values that are in only one of the input
    arrays.

Examples
--------
>>> a = np.array([1, 2, 3, 2, 4])
>>> b = np.array([2, 3, 5, 7, 5])
>>> np.setxor1d(a,b)
array([1, 4, 5, 7])


def in1d(ar1, ar2, assume_unique=False, invert=False):

<EOL>ar1 = np.asarray(ar1).ravel()<EOL>ar2 = np.asarray(ar2).ravel()<EOL>if len(ar2) < <NUM_LIT:10> * len(ar1) ** <NUM_LIT>:<EOL><INDENT>if invert:<EOL><INDENT>mask = np.ones(len(ar1), dtype=np.bool)<EOL>for a in ar2:<EOL><INDENT>mask &= (ar1 != a)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>mask = np.zeros(len(ar1), dtype=np.bool)<EOL>for a in ar2:<EOL><INDENT>mask |= (ar1 == a)<EOL><DEDENT><DEDENT>return mask<EOL><DEDENT>if not assume_unique:<EOL><INDENT>ar1, rev_idx = np.unique(ar1, return_inverse=True)<EOL>ar2 = np.unique(ar2)<EOL><DEDENT>ar = np.concatenate((ar1, ar2))<EOL>order = ar.argsort(kind='<STR_LIT>')<EOL>sar = ar[order]<EOL>if invert:<EOL><INDENT>bool_ar = (sar[<NUM_LIT:1>:] != sar[:-<NUM_LIT:1>])<EOL><DEDENT>else:<EOL><INDENT>bool_ar = (sar[<NUM_LIT:1>:] == sar[:-<NUM_LIT:1>])<EOL><DEDENT>flag = np.concatenate((bool_ar, [invert]))<EOL>indx = order.argsort(kind='<STR_LIT>')[:len(ar1)]<EOL>if assume_unique:<EOL><INDENT>return flag[indx]<EOL><DEDENT>else:<EOL><INDENT>return flag[indx][rev_idx]<EOL><DEDENT>

Test whether each element of a 1-D array is also present in a second array.

Returns a boolean array the same length as `ar1` that is True
where an element of `ar1` is in `ar2` and False otherwise.

Parameters
----------
ar1 : (M,) array_like
    Input array.
ar2 : array_like
    The values against which to test each value of `ar1`.
assume_unique : bool, optional
    If True, the input arrays are both assumed to be unique, which
    can speed up the calculation.  Default is False.
invert : bool, optional
    If True, the values in the returned array are inverted (that is,
    False where an element of `ar1` is in `ar2` and True otherwise).
    Default is False. ``np.in1d(a, b, invert=True)`` is equivalent
    to (but is faster than) ``np.invert(in1d(a, b))``.

    .. versionadded:: 1.8.0

Returns
-------
in1d : (M,) ndarray, bool
    The values `ar1[in1d]` are in `ar2`.

See Also
--------
numpy.lib.arraysetops : Module with a number of other functions for
                        performing set operations on arrays.

Notes
-----
`in1d` can be considered as an element-wise function version of the
python keyword `in`, for 1-D sequences. ``in1d(a, b)`` is roughly
equivalent to ``np.array([item in b for item in a])``.

.. versionadded:: 1.4.0

Examples
--------
>>> test = np.array([0, 1, 2, 5, 0])
>>> states = [0, 2]
>>> mask = np.in1d(test, states)
>>> mask
array([ True, False,  True, False,  True], dtype=bool)
>>> test[mask]
array([0, 2, 0])
>>> mask = np.in1d(test, states, invert=True)
>>> mask
array([False,  True, False,  True, False], dtype=bool)
>>> test[mask]
array([1, 5])


return unique(np.concatenate((ar1, ar2)))<EOL>

Find the union of two arrays.

Return the unique, sorted array of values that are in either of the two
input arrays.

Parameters
----------
ar1, ar2 : array_like
    Input arrays. They are flattened if they are not already 1D.

Returns
-------
union1d : ndarray
    Unique, sorted union of the input arrays.

See Also
--------
numpy.lib.arraysetops : Module with a number of other functions for
                        performing set operations on arrays.

Examples
--------
>>> np.union1d([-1, 0, 1], [-2, 0, 2])
array([-2, -1,  0,  1,  2])


def setdiff1d(ar1, ar2, assume_unique=False):

if not assume_unique:<EOL><INDENT>ar1 = unique(ar1)<EOL>ar2 = unique(ar2)<EOL><DEDENT>aux = in1d(ar1, ar2, assume_unique=True)<EOL>if aux.size == <NUM_LIT:0>:<EOL><INDENT>return aux<EOL><DEDENT>else:<EOL><INDENT>return np.asarray(ar1)[aux == <NUM_LIT:0>]<EOL><DEDENT>

Find the set difference of two arrays.

Return the sorted, unique values in `ar1` that are not in `ar2`.

Parameters
----------
ar1 : array_like
    Input array.
ar2 : array_like
    Input comparison array.
assume_unique : bool
    If True, the input arrays are both assumed to be unique, which
    can speed up the calculation.  Default is False.

Returns
-------
setdiff1d : ndarray
    Sorted 1D array of values in `ar1` that are not in `ar2`.

See Also
--------
numpy.lib.arraysetops : Module with a number of other functions for
                        performing set operations on arrays.

Examples
--------
>>> a = np.array([1, 2, 3, 2, 4, 1])
>>> b = np.array([3, 4, 5, 6])
>>> np.setdiff1d(a, b)
array([1, 2])


is_new = not isinstance(a, np.ndarray)<EOL>if is_new:<EOL><INDENT>a = np.array(a)<EOL><DEDENT>if not issubclass(a.dtype.type, np.inexact):<EOL><INDENT>return a, None<EOL><DEDENT>if not is_new:<EOL><INDENT>a = np.array(a, subok=True)<EOL><DEDENT>mask = np.isnan(a)<EOL>np.copyto(a, val, where=mask)<EOL>return a, mask<EOL>

If `a` is of inexact type, make a copy of `a`, replace NaNs with
the `val` value, and return the copy together with a boolean mask
marking the locations where NaNs were present. If `a` is not of
inexact type, do nothing and return `a` together with a mask of None.

Parameters
----------
a : array-like
    Input array.
val : float
    NaN values are set to val before doing the operation.

Returns
-------
y : ndarray
    If `a` is of inexact type, return a copy of `a` with the NaNs
    replaced by the fill value, otherwise return `a`.
mask: {bool, None}
    If `a` is of inexact type, return a boolean mask marking locations of
    NaNs, otherwise return None.


if isinstance(a, np.ndarray):<EOL><INDENT>np.copyto(a, val, where=mask, casting='<STR_LIT>')<EOL><DEDENT>else:<EOL><INDENT>a = a.dtype.type(val)<EOL><DEDENT>return a<EOL>

Replace values in `a` with NaN where `mask` is True.  This differs from
copyto in that it will deal with the case where `a` is a numpy scalar.

Parameters
----------
a : ndarray or numpy scalar
    Array or numpy scalar some of whose values are to be replaced
    by val.
val : numpy scalar
    Value used a replacement.
mask : ndarray, scalar
    Boolean array. Where True the corresponding element of `a` is
    replaced by `val`. Broadcasts.

Returns
-------
res : ndarray, scalar
    Array with elements replaced or scalar `val`.


with np.errstate(invalid='<STR_LIT:ignore>'):<EOL><INDENT>if isinstance(a, np.ndarray):<EOL><INDENT>if out is None:<EOL><INDENT>return np.divide(a, b, out=a, casting='<STR_LIT>')<EOL><DEDENT>else:<EOL><INDENT>return np.divide(a, b, out=out, casting='<STR_LIT>')<EOL><DEDENT><DEDENT>else:<EOL><INDENT>if out is None:<EOL><INDENT>return a.dtype.type(a / b)<EOL><DEDENT>else:<EOL><INDENT>return np.divide(a, b, out=out, casting='<STR_LIT>')<EOL><DEDENT><DEDENT><DEDENT>

Compute a/b ignoring invalid results. If `a` is an array the division
is done in place. If `a` is a scalar, then its type is preserved in the
output. If out is None, then then a is used instead so that the
division is in place. Note that this is only called with `a` an inexact
type.

Parameters
----------
a : {ndarray, numpy scalar}
    Numerator. Expected to be of inexact type but not checked.
b : {ndarray, numpy scalar}
    Denominator.
out : ndarray, optional
    Alternate output array in which to place the result.  The default
    is ``None``; if provided, it must have the same shape as the
    expected output, but the type will be cast if necessary.

Returns
-------
ret : {ndarray, numpy scalar}
    The return value is a/b. If `a` was an ndarray the division is done
    in place. If `a` is a numpy scalar, the division preserves its type.


def nanmin(a, axis=None, out=None, keepdims=False):

if not isinstance(a, np.ndarray) or type(a) is np.ndarray:<EOL><INDENT>res = np.fmin.reduce(a, axis=axis, out=out, keepdims=keepdims)<EOL>if np.isnan(res).any():<EOL><INDENT>warnings.warn("<STR_LIT>", RuntimeWarning)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>a, mask = _replace_nan(a, +np.inf)<EOL>res = np.amin(a, axis=axis, out=out, keepdims=keepdims)<EOL>if mask is None:<EOL><INDENT>return res<EOL><DEDENT>mask = np.all(mask, axis=axis, keepdims=keepdims)<EOL>if np.any(mask):<EOL><INDENT>res = _copyto(res, np.nan, mask)<EOL>warnings.warn("<STR_LIT>", RuntimeWarning)<EOL><DEDENT><DEDENT>return res<EOL>

Return minimum of an array or minimum along an axis, ignoring any NaNs.
When all-NaN slices are encountered a ``RuntimeWarning`` is raised and
Nan is returned for that slice.

Parameters
----------
a : array_like
    Array containing numbers whose minimum is desired. If `a` is not an
    array, a conversion is attempted.
axis : int, optional
    Axis along which the minimum is computed. The default is to compute
    the minimum of the flattened array.
out : ndarray, optional
    Alternate output array in which to place the result.  The default
    is ``None``; if provided, it must have the same shape as the
    expected output, but the type will be cast if necessary.  See
    `doc.ufuncs` for details.

    .. versionadded:: 1.8.0
keepdims : bool, optional
    If this is set to True, the axes which are reduced are left in the
    result as dimensions with size one. With this option, the result
    will broadcast correctly against the original `a`.

    .. versionadded:: 1.8.0

Returns
-------
nanmin : ndarray
    An array with the same shape as `a`, with the specified axis
    removed.  If `a` is a 0-d array, or if axis is None, an ndarray
    scalar is returned.  The same dtype as `a` is returned.

See Also
--------
nanmax :
    The maximum value of an array along a given axis, ignoring any NaNs.
amin :
    The minimum value of an array along a given axis, propagating any NaNs.
fmin :
    Element-wise minimum of two arrays, ignoring any NaNs.
minimum :
    Element-wise minimum of two arrays, propagating any NaNs.
isnan :
    Shows which elements are Not a Number (NaN).
isfinite:
    Shows which elements are neither NaN nor infinity.

amax, fmax, maximum

Notes
-----
Numpy uses the IEEE Standard for Binary Floating-Point for Arithmetic
(IEEE 754). This means that Not a Number is not equivalent to infinity.
Positive infinity is treated as a very large number and negative
infinity is treated as a very small (i.e. negative) number.

If the input has a integer type the function is equivalent to np.min.

Examples
--------
>>> a = np.array([[1, 2], [3, np.nan]])
>>> np.nanmin(a)
1.0
>>> np.nanmin(a, axis=0)
array([ 1.,  2.])
>>> np.nanmin(a, axis=1)
array([ 1.,  3.])

When positive infinity and negative infinity are present:

>>> np.nanmin([1, 2, np.nan, np.inf])
1.0
>>> np.nanmin([1, 2, np.nan, np.NINF])
-inf


def nanmax(a, axis=None, out=None, keepdims=False):

if not isinstance(a, np.ndarray) or type(a) is np.ndarray:<EOL><INDENT>res = np.fmax.reduce(a, axis=axis, out=out, keepdims=keepdims)<EOL>if np.isnan(res).any():<EOL><INDENT>warnings.warn("<STR_LIT>", RuntimeWarning)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>a, mask = _replace_nan(a, -np.inf)<EOL>res = np.amax(a, axis=axis, out=out, keepdims=keepdims)<EOL>if mask is None:<EOL><INDENT>return res<EOL><DEDENT>mask = np.all(mask, axis=axis, keepdims=keepdims)<EOL>if np.any(mask):<EOL><INDENT>res = _copyto(res, np.nan, mask)<EOL>warnings.warn("<STR_LIT>", RuntimeWarning)<EOL><DEDENT><DEDENT>return res<EOL>

Return the maximum of an array or maximum along an axis, ignoring any
NaNs.  When all-NaN slices are encountered a ``RuntimeWarning`` is
raised and NaN is returned for that slice.

Parameters
----------
a : array_like
    Array containing numbers whose maximum is desired. If `a` is not an
    array, a conversion is attempted.
axis : int, optional
    Axis along which the maximum is computed. The default is to compute
    the maximum of the flattened array.
out : ndarray, optional
    Alternate output array in which to place the result.  The default
    is ``None``; if provided, it must have the same shape as the
    expected output, but the type will be cast if necessary.  See
    `doc.ufuncs` for details.

    .. versionadded:: 1.8.0
keepdims : bool, optional
    If this is set to True, the axes which are reduced are left in the
    result as dimensions with size one. With this option, the result
    will broadcast correctly against the original `a`.

    .. versionadded:: 1.8.0

Returns
-------
nanmax : ndarray
    An array with the same shape as `a`, with the specified axis removed.
    If `a` is a 0-d array, or if axis is None, an ndarray scalar is
    returned.  The same dtype as `a` is returned.

See Also
--------
nanmin :
    The minimum value of an array along a given axis, ignoring any NaNs.
amax :
    The maximum value of an array along a given axis, propagating any NaNs.
fmax :
    Element-wise maximum of two arrays, ignoring any NaNs.
maximum :
    Element-wise maximum of two arrays, propagating any NaNs.
isnan :
    Shows which elements are Not a Number (NaN).
isfinite:
    Shows which elements are neither NaN nor infinity.

amin, fmin, minimum

Notes
-----
Numpy uses the IEEE Standard for Binary Floating-Point for Arithmetic
(IEEE 754). This means that Not a Number is not equivalent to infinity.
Positive infinity is treated as a very large number and negative
infinity is treated as a very small (i.e. negative) number.

If the input has a integer type the function is equivalent to np.max.

Examples
--------
>>> a = np.array([[1, 2], [3, np.nan]])
>>> np.nanmax(a)
3.0
>>> np.nanmax(a, axis=0)
array([ 3.,  2.])
>>> np.nanmax(a, axis=1)
array([ 2.,  3.])

When positive infinity and negative infinity are present:

>>> np.nanmax([1, 2, np.nan, np.NINF])
2.0
>>> np.nanmax([1, 2, np.nan, np.inf])
inf


a, mask = _replace_nan(a, np.inf)<EOL>res = np.argmin(a, axis=axis)<EOL>if mask is not None:<EOL><INDENT>mask = np.all(mask, axis=axis)<EOL>if np.any(mask):<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT><DEDENT>return res<EOL>

Return the indices of the minimum values in the specified axis ignoring
NaNs. For all-NaN slices ``ValueError`` is raised. Warning: the results
cannot be trusted if a slice contains only NaNs and Infs.

Parameters
----------
a : array_like
    Input data.
axis : int, optional
    Axis along which to operate.  By default flattened input is used.

Returns
-------
index_array : ndarray
    An array of indices or a single index value.

See Also
--------
argmin, nanargmax

Examples
--------
>>> a = np.array([[np.nan, 4], [2, 3]])
>>> np.argmin(a)
0
>>> np.nanargmin(a)
2
>>> np.nanargmin(a, axis=0)
array([1, 1])
>>> np.nanargmin(a, axis=1)
array([1, 0])


a, mask = _replace_nan(a, -np.inf)<EOL>res = np.argmax(a, axis=axis)<EOL>if mask is not None:<EOL><INDENT>mask = np.all(mask, axis=axis)<EOL>if np.any(mask):<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT><DEDENT>return res<EOL>

Return the indices of the maximum values in the specified axis ignoring
NaNs. For all-NaN slices ``ValueError`` is raised. Warning: the
results cannot be trusted if a slice contains only NaNs and -Infs.

Parameters
----------
a : array_like
    Input data.
axis : int, optional
    Axis along which to operate.  By default flattened input is used.

Returns
-------
index_array : ndarray
    An array of indices or a single index value.

See Also
--------
argmax, nanargmin

Examples
--------
>>> a = np.array([[np.nan, 4], [2, 3]])
>>> np.argmax(a)
0
>>> np.nanargmax(a)
1
>>> np.nanargmax(a, axis=0)
array([1, 0])
>>> np.nanargmax(a, axis=1)
array([1, 1])


def nansum(a, axis=None, dtype=None, out=None, keepdims=<NUM_LIT:0>):

a, mask = _replace_nan(a, <NUM_LIT:0>)<EOL>return np.sum(a, axis=axis, dtype=dtype, out=out, keepdims=keepdims)<EOL>

Return the sum of array elements over a given axis treating Not a
Numbers (NaNs) as zero.

In Numpy versions <= 1.8 Nan is returned for slices that are all-NaN or
empty. In later versions zero is returned.

Parameters
----------
a : array_like
    Array containing numbers whose sum is desired. If `a` is not an
    array, a conversion is attempted.
axis : int, optional
    Axis along which the sum is computed. The default is to compute the
    sum of the flattened array.
dtype : data-type, optional
    The type of the returned array and of the accumulator in which the
    elements are summed.  By default, the dtype of `a` is used.  An
    exception is when `a` has an integer type with less precision than
    the platform (u)intp. In that case, the default will be either
    (u)int32 or (u)int64 depending on whether the platform is 32 or 64
    bits. For inexact inputs, dtype must be inexact.

    .. versionadded:: 1.8.0
out : ndarray, optional
    Alternate output array in which to place the result.  The default
    is ``None``. If provided, it must have the same shape as the
    expected output, but the type will be cast if necessary.  See
    `doc.ufuncs` for details. The casting of NaN to integer can yield
    unexpected results.

    .. versionadded:: 1.8.0
keepdims : bool, optional
    If True, the axes which are reduced are left in the result as
    dimensions with size one. With this option, the result will
    broadcast correctly against the original `arr`.

    .. versionadded:: 1.8.0

Returns
-------
y : ndarray or numpy scalar

See Also
--------
numpy.sum : Sum across array propagating NaNs.
isnan : Show which elements are NaN.
isfinite: Show which elements are not NaN or +/-inf.

Notes
-----
If both positive and negative infinity are present, the sum will be Not
A Number (NaN).

Numpy integer arithmetic is modular. If the size of a sum exceeds the
size of an integer accumulator, its value will wrap around and the
result will be incorrect. Specifying ``dtype=double`` can alleviate
that problem.

Examples
--------
>>> np.nansum(1)
1
>>> np.nansum([1])
1
>>> np.nansum([1, np.nan])
1.0
>>> a = np.array([[1, 1], [1, np.nan]])
>>> np.nansum(a)
3.0
>>> np.nansum(a, axis=0)
array([ 2.,  1.])
>>> np.nansum([1, np.nan, np.inf])
inf
>>> np.nansum([1, np.nan, np.NINF])
-inf
>>> np.nansum([1, np.nan, np.inf, -np.inf]) # both +/- infinity present
nan


def nanmean(a, axis=None, dtype=None, out=None, keepdims=False):

arr, mask = _replace_nan(a, <NUM_LIT:0>)<EOL>if mask is None:<EOL><INDENT>return np.mean(arr, axis=axis, dtype=dtype, out=out, keepdims=keepdims)<EOL><DEDENT>if dtype is not None:<EOL><INDENT>dtype = np.dtype(dtype)<EOL><DEDENT>if dtype is not None and not issubclass(dtype.type, np.inexact):<EOL><INDENT>raise TypeError("<STR_LIT>")<EOL><DEDENT>if out is not None and not issubclass(out.dtype.type, np.inexact):<EOL><INDENT>raise TypeError("<STR_LIT>")<EOL><DEDENT>with warnings.catch_warnings():<EOL><INDENT>warnings.simplefilter('<STR_LIT:ignore>')<EOL>cnt = np.sum(~mask, axis=axis, dtype=np.intp, keepdims=keepdims)<EOL>tot = np.sum(arr, axis=axis, dtype=dtype, out=out, keepdims=keepdims)<EOL>avg = _divide_by_count(tot, cnt, out=out)<EOL><DEDENT>isbad = (cnt == <NUM_LIT:0>)<EOL>if isbad.any():<EOL><INDENT>warnings.warn("<STR_LIT>", RuntimeWarning)<EOL><DEDENT>return avg<EOL>

Compute the arithmetic mean along the specified axis, ignoring NaNs.

Returns the average of the array elements.  The average is taken over
the flattened array by default, otherwise over the specified axis.
`float64` intermediate and return values are used for integer inputs.

For all-NaN slices, NaN is returned and a `RuntimeWarning` is raised.

.. versionadded:: 1.8.0

Parameters
----------
a : array_like
    Array containing numbers whose mean is desired. If `a` is not an
    array, a conversion is attempted.
axis : int, optional
    Axis along which the means are computed. The default is to compute
    the mean of the flattened array.
dtype : data-type, optional
    Type to use in computing the mean.  For integer inputs, the default
    is `float64`; for inexact inputs, it is the same as the input
    dtype.
out : ndarray, optional
    Alternate output array in which to place the result.  The default
    is ``None``; if provided, it must have the same shape as the
    expected output, but the type will be cast if necessary.  See
    `doc.ufuncs` for details.
keepdims : bool, optional
    If this is set to True, the axes which are reduced are left in the
    result as dimensions with size one. With this option, the result
    will broadcast correctly against the original `arr`.

Returns
-------
m : ndarray, see dtype parameter above
    If `out=None`, returns a new array containing the mean values,
    otherwise a reference to the output array is returned. Nan is
    returned for slices that contain only NaNs.

See Also
--------
average : Weighted average
mean : Arithmetic mean taken while not ignoring NaNs
var, nanvar

Notes
-----
The arithmetic mean is the sum of the non-NaN elements along the axis
divided by the number of non-NaN elements.

Note that for floating-point input, the mean is computed using the same
precision the input has.  Depending on the input data, this can cause
the results to be inaccurate, especially for `float32`.  Specifying a
higher-precision accumulator using the `dtype` keyword can alleviate
this issue.

Examples
--------
>>> a = np.array([[1, np.nan], [3, 4]])
>>> np.nanmean(a)
2.6666666666666665
>>> np.nanmean(a, axis=0)
array([ 2.,  4.])
>>> np.nanmean(a, axis=1)
array([ 1.,  3.5])


c = np.isnan(arr1d)<EOL>s = np.where(c)[<NUM_LIT:0>]<EOL>if s.size == arr1d.size:<EOL><INDENT>warnings.warn("<STR_LIT>", RuntimeWarning)<EOL>return np.nan<EOL><DEDENT>elif s.size == <NUM_LIT:0>:<EOL><INDENT>return np.median(arr1d, overwrite_input=overwrite_input)<EOL><DEDENT>else:<EOL><INDENT>if overwrite_input:<EOL><INDENT>x = arr1d<EOL><DEDENT>else:<EOL><INDENT>x = arr1d.copy()<EOL><DEDENT>enonan = arr1d[-s.size:][~c[-s.size:]]<EOL>x[s[:enonan.size]] = enonan<EOL>return np.median(x[:-s.size], overwrite_input=True)<EOL><DEDENT>

Private function for rank 1 arrays. Compute the median ignoring NaNs.
See nanmedian for parameter usage


def _nanmedian(a, axis=None, out=None, overwrite_input=False):

if axis is None or a.ndim == <NUM_LIT:1>:<EOL><INDENT>part = a.ravel()<EOL>if out is None:<EOL><INDENT>return _nanmedian1d(part, overwrite_input)<EOL><DEDENT>else:<EOL><INDENT>out[...] = _nanmedian1d(part, overwrite_input)<EOL>return out<EOL><DEDENT><DEDENT>else:<EOL><INDENT>if a.shape[axis] < <NUM_LIT>:<EOL><INDENT>return _nanmedian_small(a, axis, out, overwrite_input)<EOL><DEDENT>result = np.apply_along_axis(_nanmedian1d, axis, a, overwrite_input)<EOL>if out is not None:<EOL><INDENT>out[...] = result<EOL><DEDENT>return result<EOL><DEDENT>

Private function that doesn't support extended axis or keepdims.
These methods are extended to this function using _ureduce
See nanmedian for parameter usage


def _nanmedian_small(a, axis=None, out=None, overwrite_input=False):

a = np.ma.masked_array(a, np.isnan(a))<EOL>m = np.ma.median(a, axis=axis, overwrite_input=overwrite_input)<EOL>for i in range(np.count_nonzero(m.mask.ravel())):<EOL><INDENT>warnings.warn("<STR_LIT>", RuntimeWarning)<EOL><DEDENT>if out is not None:<EOL><INDENT>out[...] = m.filled(np.nan)<EOL>return out<EOL><DEDENT>return m.filled(np.nan)<EOL>

sort + indexing median, faster for small medians along multiple dimensions
due to the high overhead of apply_along_axis
see nanmedian for parameter usage


def nanmedian(a, axis=None, out=None, overwrite_input=False, keepdims=False):

a = np.asanyarray(a)<EOL>if a.size == <NUM_LIT:0>:<EOL><INDENT>return np.nanmean(a, axis, out=out, keepdims=keepdims)<EOL><DEDENT>r, k = _ureduce(a, func=_nanmedian, axis=axis, out=out,<EOL>overwrite_input=overwrite_input)<EOL>if keepdims:<EOL><INDENT>return r.reshape(k)<EOL><DEDENT>else:<EOL><INDENT>return r<EOL><DEDENT>

Compute the median along the specified axis, while ignoring NaNs.

Returns the median of the array elements.

.. versionadded:: 1.9.0

Parameters
----------
a : array_like
    Input array or object that can be converted to an array.
axis : int, optional
    Axis along which the medians are computed. The default (axis=None)
    is to compute the median along a flattened version of the array.
    A sequence of axes is supported since version 1.9.0.
out : ndarray, optional
    Alternative output array in which to place the result. It must have
    the same shape and buffer length as the expected output, but the
    type (of the output) will be cast if necessary.
overwrite_input : bool, optional
   If True, then allow use of memory of input array (a) for
   calculations. The input array will be modified by the call to
   median. This will save memory when you do not need to preserve
   the contents of the input array. Treat the input as undefined,
   but it will probably be fully or partially sorted. Default is
   False. Note that, if `overwrite_input` is True and the input
   is not already an ndarray, an error will be raised.
keepdims : bool, optional
    If this is set to True, the axes which are reduced are left
    in the result as dimensions with size one. With this option,
    the result will broadcast correctly against the original `arr`.

Returns
-------
median : ndarray
    A new array holding the result. If the input contains integers, or
    floats of smaller precision than 64, then the output data-type is
    float64.  Otherwise, the output data-type is the same as that of the
    input.

See Also
--------
mean, median, percentile

Notes
-----
Given a vector V of length N, the median of V is the middle value of
a sorted copy of V, ``V_sorted`` - i.e., ``V_sorted[(N-1)/2]``, when N is
odd.  When N is even, it is the average of the two middle values of
``V_sorted``.

Examples
--------
>>> a = np.array([[10.0, 7, 4], [3, 2, 1]])
>>> a[0, 1] = np.nan
>>> a
array([[ 10.,  nan,   4.],
   [  3.,   2.,   1.]])
>>> np.median(a)
nan
>>> np.nanmedian(a)
3.0
>>> np.nanmedian(a, axis=0)
array([ 6.5,  2.,  2.5])
>>> np.median(a, axis=1)
array([ 7.,  2.])
>>> b = a.copy()
>>> np.nanmedian(b, axis=1, overwrite_input=True)
array([ 7.,  2.])
>>> assert not np.all(a==b)
>>> b = a.copy()
>>> np.nanmedian(b, axis=None, overwrite_input=True)
3.0
>>> assert not np.all(a==b)


def nanpercentile(a, q, axis=None, out=None, overwrite_input=False,<EOL>interpolation='<STR_LIT>', keepdims=False):

a = np.asanyarray(a)<EOL>q = np.asanyarray(q)<EOL>if a.size == <NUM_LIT:0>:<EOL><INDENT>return np.nanmean(a, axis, out=out, keepdims=keepdims)<EOL><DEDENT>r, k = _ureduce(a, func=_nanpercentile, q=q, axis=axis, out=out,<EOL>overwrite_input=overwrite_input,<EOL>interpolation=interpolation)<EOL>if keepdims:<EOL><INDENT>if q.ndim == <NUM_LIT:0>:<EOL><INDENT>return r.reshape(k)<EOL><DEDENT>else:<EOL><INDENT>return r.reshape([len(q)] + k)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>return r<EOL><DEDENT>

Compute the qth percentile of the data along the specified axis, while
ignoring nan values.

Returns the qth percentile of the array elements.

Parameters
----------
a : array_like
    Input array or object that can be converted to an array.
q : float in range of [0,100] (or sequence of floats)
    Percentile to compute which must be between 0 and 100 inclusive.
axis : int or sequence of int, optional
    Axis along which the percentiles are computed. The default (None)
    is to compute the percentiles along a flattened version of the array.
    A sequence of axes is supported since version 1.9.0.
out : ndarray, optional
    Alternative output array in which to place the result. It must
    have the same shape and buffer length as the expected output,
    but the type (of the output) will be cast if necessary.
overwrite_input : bool, optional
    If True, then allow use of memory of input array `a` for
    calculations. The input array will be modified by the call to
    percentile. This will save memory when you do not need to preserve
    the contents of the input array. In this case you should not make
    any assumptions about the content of the passed in array `a` after
    this function completes -- treat it as undefined. Default is False.
    Note that, if the `a` input is not already an array this parameter
    will have no effect, `a` will be converted to an array internally
    regardless of the value of this parameter.
interpolation : {'linear', 'lower', 'higher', 'midpoint', 'nearest'}
    This optional parameter specifies the interpolation method to use,
    when the desired quantile lies between two data points `i` and `j`:
        * linear: `i + (j - i) * fraction`, where `fraction` is the
          fractional part of the index surrounded by `i` and `j`.
        * lower: `i`.
        * higher: `j`.
        * nearest: `i` or `j` whichever is nearest.
        * midpoint: (`i` + `j`) / 2.

keepdims : bool, optional
    If this is set to True, the axes which are reduced are left
    in the result as dimensions with size one. With this option,
    the result will broadcast correctly against the original `arr`.

Returns
-------
nanpercentile : scalar or ndarray
    If a single percentile `q` is given and axis=None a scalar is
    returned.  If multiple percentiles `q` are given an array holding
    the result is returned. The results are listed in the first axis.
    (If `out` is specified, in which case that array is returned
    instead).  If the input contains integers, or floats of smaller
    precision than 64, then the output data-type is float64. Otherwise,
    the output data-type is the same as that of the input.

See Also
--------
nanmean, nanmedian, percentile, median, mean

Notes
-----
Given a vector V of length N, the q-th percentile of V is the q-th ranked
value in a sorted copy of V.  The values and distances of the two
nearest neighbors as well as the `interpolation` parameter will
determine the percentile if the normalized ranking does not match q
exactly. This function is the same as the median if ``q=50``, the same
as the minimum if ``q=0``and the same as the maximum if ``q=100``.

Examples
--------
>>> a = np.array([[10., 7., 4.], [3., 2., 1.]])
>>> a[0][1] = np.nan
>>> a
array([[ 10.,  nan,   4.],
   [  3.,   2.,   1.]])
>>> np.percentile(a, 50)
nan
>>> np.nanpercentile(a, 50)
3.5
>>> np.nanpercentile(a, 50, axis=0)
array([[ 6.5,  4.5,  2.5]])
>>> np.nanpercentile(a, 50, axis=1)
array([[ 7.],
       [ 2.]])
>>> m = np.nanpercentile(a, 50, axis=0)
>>> out = np.zeros_like(m)
>>> np.nanpercentile(a, 50, axis=0, out=m)
array([[ 6.5,  4.5,  2.5]])
>>> m
array([[ 6.5,  4.5,  2.5]])
>>> b = a.copy()
>>> np.nanpercentile(b, 50, axis=1, overwrite_input=True)
array([[ 7.],
       [ 2.]])
>>> assert not np.all(a==b)
>>> b = a.copy()
>>> np.nanpercentile(b, 50, axis=None, overwrite_input=True)
array([ 3.5])