try:<EOL><INDENT>squeeze = a.squeeze<EOL><DEDENT>except AttributeError:<EOL><INDENT>return _wrapit(a, '<STR_LIT>')<EOL><DEDENT>try:<EOL><INDENT>return squeeze(axis=axis)<EOL><DEDENT>except TypeError:<EOL><INDENT>return squeeze()<EOL><DEDENT>

Remove single-dimensional entries from the shape of an array.

Parameters
----------
a : array_like
    Input data.
axis : None or int or tuple of ints, optional
    .. versionadded:: 1.7.0

    Selects a subset of the single-dimensional entries in the
    shape. If an axis is selected with shape entry greater than
    one, an error is raised.

Returns
-------
squeezed : ndarray
    The input array, but with all or a subset of the
    dimensions of length 1 removed. This is always `a` itself
    or a view into `a`.

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


return asarray(a).ravel(order)<EOL>

Return a flattened array.

A 1-D array, containing the elements of the input, is returned.  A copy is
made only if needed.

Parameters
----------
a : array_like
    Input array.  The elements in `a` are read in the order specified by
    `order`, and packed as a 1-D array.
order : {'C','F', 'A', 'K'}, optional
    The elements of `a` are read using this index order. 'C' means to
    index the elements in C-like order, with the last axis index changing
    fastest, back to the first axis index changing slowest.   'F' means to
    index the elements in Fortran-like index order, with the first index
    changing fastest, and the last index changing slowest. Note that the 'C'
    and 'F' options take no account of the memory layout of the underlying
    array, and only refer to the order of axis indexing.  'A' means to read
    the elements in Fortran-like index order if `a` is Fortran *contiguous*
    in memory, C-like order otherwise.  'K' means to read the elements in
    the order they occur in memory, except for reversing the data when
    strides are negative.  By default, 'C' index order is used.

Returns
-------
1d_array : ndarray
    Output of the same dtype as `a`, and of shape ``(a.size,)``.

See Also
--------
ndarray.flat : 1-D iterator over an array.
ndarray.flatten : 1-D array copy of the elements of an array
                  in row-major order.

Notes
-----
In C-like (row-major) order, in two dimensions, the row index varies the
slowest, and the column index the quickest.  This can be generalized to
multiple dimensions, where row-major order implies that the index along the
first axis varies slowest, and the index along the last quickest.  The
opposite holds for Fortran-like, or column-major, index ordering.

Examples
--------
It is equivalent to ``reshape(-1, order=order)``.

>>> x = np.array([[1, 2, 3], [4, 5, 6]])
>>> print np.ravel(x)
[1 2 3 4 5 6]

>>> print x.reshape(-1)
[1 2 3 4 5 6]

>>> print np.ravel(x, order='F')
[1 4 2 5 3 6]

When ``order`` is 'A', it will preserve the array's 'C' or 'F' ordering:

>>> print np.ravel(x.T)
[1 4 2 5 3 6]
>>> print np.ravel(x.T, order='A')
[1 2 3 4 5 6]

When ``order`` is 'K', it will preserve orderings that are neither 'C'
nor 'F', but won't reverse axes:

>>> a = np.arange(3)[::-1]; a
array([2, 1, 0])
>>> a.ravel(order='C')
array([2, 1, 0])
>>> a.ravel(order='K')
array([2, 1, 0])

>>> a = np.arange(12).reshape(2,3,2).swapaxes(1,2); a
array([[[ 0,  2,  4],
        [ 1,  3,  5]],
       [[ 6,  8, 10],
        [ 7,  9, 11]]])
>>> a.ravel(order='C')
array([ 0,  2,  4,  1,  3,  5,  6,  8, 10,  7,  9, 11])
>>> a.ravel(order='K')
array([ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11])


def choose(a, choices, out=None, mode='<STR_LIT>'):

try:<EOL><INDENT>choose = a.choose<EOL><DEDENT>except AttributeError:<EOL><INDENT>return _wrapit(a, '<STR_LIT>', choices, out=out, mode=mode)<EOL><DEDENT>return choose(choices, out=out, mode=mode)<EOL>

Construct an array from an index array and a set of arrays to choose from.

First of all, if confused or uncertain, definitely look at the Examples -
in its full generality, this function is less simple than it might
seem from the following code description (below ndi =
`numpy.lib.index_tricks`):

``np.choose(a,c) == np.array([c[a[I]][I] for I in ndi.ndindex(a.shape)])``.

But this omits some subtleties.  Here is a fully general summary:

Given an "index" array (`a`) of integers and a sequence of `n` arrays
(`choices`), `a` and each choice array are first broadcast, as necessary,
to arrays of a common shape; calling these *Ba* and *Bchoices[i], i =
0,...,n-1* we have that, necessarily, ``Ba.shape == Bchoices[i].shape``
for each `i`.  Then, a new array with shape ``Ba.shape`` is created as
follows:

* if ``mode=raise`` (the default), then, first of all, each element of
  `a` (and thus `Ba`) must be in the range `[0, n-1]`; now, suppose that
  `i` (in that range) is the value at the `(j0, j1, ..., jm)` position
  in `Ba` - then the value at the same position in the new array is the
  value in `Bchoices[i]` at that same position;

* if ``mode=wrap``, values in `a` (and thus `Ba`) may be any (signed)
  integer; modular arithmetic is used to map integers outside the range
  `[0, n-1]` back into that range; and then the new array is constructed
  as above;

* if ``mode=clip``, values in `a` (and thus `Ba`) may be any (signed)
  integer; negative integers are mapped to 0; values greater than `n-1`
  are mapped to `n-1`; and then the new array is constructed as above.

Parameters
----------
a : int array
    This array must contain integers in `[0, n-1]`, where `n` is the number
    of choices, unless ``mode=wrap`` or ``mode=clip``, in which cases any
    integers are permissible.
choices : sequence of arrays
    Choice arrays. `a` and all of the choices must be broadcastable to the
    same shape.  If `choices` is itself an array (not recommended), then
    its outermost dimension (i.e., the one corresponding to
    ``choices.shape[0]``) is taken as defining the "sequence".
out : array, optional
    If provided, the result will be inserted into this array. It should
    be of the appropriate shape and dtype.
mode : {'raise' (default), 'wrap', 'clip'}, optional
    Specifies how indices outside `[0, n-1]` will be treated:

      * 'raise' : an exception is raised
      * 'wrap' : value becomes value mod `n`
      * 'clip' : values < 0 are mapped to 0, values > n-1 are mapped to n-1

Returns
-------
merged_array : array
    The merged result.

Raises
------
ValueError: shape mismatch
    If `a` and each choice array are not all broadcastable to the same
    shape.

See Also
--------
ndarray.choose : equivalent method

Notes
-----
To reduce the chance of misinterpretation, even though the following
"abuse" is nominally supported, `choices` should neither be, nor be
thought of as, a single array, i.e., the outermost sequence-like container
should be either a list or a tuple.

Examples
--------

>>> choices = [[0, 1, 2, 3], [10, 11, 12, 13],
...   [20, 21, 22, 23], [30, 31, 32, 33]]
>>> np.choose([2, 3, 1, 0], choices
... # the first element of the result will be the first element of the
... # third (2+1) "array" in choices, namely, 20; the second element
... # will be the second element of the fourth (3+1) choice array, i.e.,
... # 31, etc.
... )
array([20, 31, 12,  3])
>>> np.choose([2, 4, 1, 0], choices, mode='clip') # 4 goes to 3 (4-1)
array([20, 31, 12,  3])
>>> # because there are 4 choice arrays
>>> np.choose([2, 4, 1, 0], choices, mode='wrap') # 4 goes to (4 mod 4)
array([20,  1, 12,  3])
>>> # i.e., 0

A couple examples illustrating how choose broadcasts:

>>> a = [[1, 0, 1], [0, 1, 0], [1, 0, 1]]
>>> choices = [-10, 10]
>>> np.choose(a, choices)
array([[ 10, -10,  10],
       [-10,  10, -10],
       [ 10, -10,  10]])

>>> # With thanks to Anne Archibald
>>> a = np.array([0, 1]).reshape((2,1,1))
>>> c1 = np.array([1, 2, 3]).reshape((1,3,1))
>>> c2 = np.array([-1, -2, -3, -4, -5]).reshape((1,1,5))
>>> np.choose(a, (c1, c2)) # result is 2x3x5, res[0,:,:]=c1, res[1,:,:]=c2
array([[[ 1,  1,  1,  1,  1],
        [ 2,  2,  2,  2,  2],
        [ 3,  3,  3,  3,  3]],
       [[-1, -2, -3, -4, -5],
        [-1, -2, -3, -4, -5],
        [-1, -2, -3, -4, -5]]])


warnings.warn(<EOL>"<STR_LIT>"<EOL>"<STR_LIT>",<EOL>VisibleDeprecationWarning)<EOL>try:<EOL><INDENT>return a.ndim<EOL><DEDENT>except AttributeError:<EOL><INDENT>return asarray(a).ndim<EOL><DEDENT>

Return the number of dimensions of an array.

If `a` is not already an array, a conversion is attempted.
Scalars are zero dimensional.

.. note::
    This function is deprecated in NumPy 1.9 to avoid confusion with
    `numpy.linalg.matrix_rank`. The ``ndim`` attribute or function
    should be used instead.

Parameters
----------
a : array_like
    Array whose number of dimensions is desired. If `a` is not an array,
    a conversion is attempted.

Returns
-------
number_of_dimensions : int
    The number of dimensions in the array.

See Also
--------
ndim : equivalent function
ndarray.ndim : equivalent property
shape : dimensions of array
ndarray.shape : dimensions of array

Notes
-----
In the old Numeric package, `rank` was the term used for the number of
dimensions, but in Numpy `ndim` is used instead.

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


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

arr = asanyarray(a)<EOL>try:<EOL><INDENT>return arr.all(axis=axis, out=out, keepdims=keepdims)<EOL><DEDENT>except TypeError:<EOL><INDENT>return arr.all(axis=axis, out=out)<EOL><DEDENT>

Test whether all array elements along a given axis evaluate to True.

Parameters
----------
a : array_like
    Input array or object that can be converted to an array.
axis : None or int or tuple of ints, optional
    Axis or axes along which a logical AND reduction is performed.
    The default (`axis` = `None`) is to perform a logical AND over all
    the dimensions of the input array. `axis` may be negative, in
    which case it counts from the last to the first axis.

    .. versionadded:: 1.7.0

    If this is a tuple of ints, a reduction is performed on multiple
    axes, instead of a single axis or all the axes as before.
out : ndarray, optional
    Alternate output array in which to place the result.
    It must have the same shape as the expected output and its
    type is preserved (e.g., if ``dtype(out)`` is float, the result
    will consist of 0.0's and 1.0's).  See `doc.ufuncs` (Section
    "Output arguments") for more 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
-------
all : ndarray, bool
    A new boolean or array is returned unless `out` is specified,
    in which case a reference to `out` is returned.

See Also
--------
ndarray.all : equivalent method

any : Test whether any element along a given axis evaluates to True.

Notes
-----
Not a Number (NaN), positive infinity and negative infinity
evaluate to `True` because these are not equal to zero.

Examples
--------
>>> np.all([[True,False],[True,True]])
False

>>> np.all([[True,False],[True,True]], axis=0)
array([ True, False], dtype=bool)

>>> np.all([-1, 4, 5])
True

>>> np.all([1.0, np.nan])
True

>>> o=np.array([False])
>>> z=np.all([-1, 4, 5], out=o)
>>> id(z), id(o), z                             # doctest: +SKIP
(28293632, 28293632, array([ True], dtype=bool))


try:<EOL><INDENT>return a.ndim<EOL><DEDENT>except AttributeError:<EOL><INDENT>return asarray(a).ndim<EOL><DEDENT>

Return the number of dimensions of an array.

Parameters
----------
a : array_like
    Input array.  If it is not already an ndarray, a conversion is
    attempted.

Returns
-------
number_of_dimensions : int
    The number of dimensions in `a`.  Scalars are zero-dimensional.

See Also
--------
ndarray.ndim : equivalent method
shape : dimensions of array
ndarray.shape : dimensions of array

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


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

if type(a) is not mu.ndarray:<EOL><INDENT>try:<EOL><INDENT>prod = a.prod<EOL><DEDENT>except AttributeError:<EOL><INDENT>return _methods._prod(a, axis=axis, dtype=dtype,<EOL>out=out, keepdims=keepdims)<EOL><DEDENT>return prod(axis=axis, dtype=dtype, out=out)<EOL><DEDENT>else:<EOL><INDENT>return _methods._prod(a, axis=axis, dtype=dtype,<EOL>out=out, keepdims=keepdims)<EOL><DEDENT>

Return the product of array elements over a given axis.

Parameters
----------
a : array_like
    Input data.
axis : None or int or tuple of ints, optional
    Axis or axes along which a product is performed.
    The default (`axis` = `None`) is perform a product over all
    the dimensions of the input array. `axis` may be negative, in
    which case it counts from the last to the first axis.

    .. versionadded:: 1.7.0

    If this is a tuple of ints, a product is performed on multiple
    axes, instead of a single axis or all the axes as before.
dtype : data-type, optional
    The data-type of the returned array, as well as of the accumulator
    in which the elements are multiplied.  By default, if `a` is of
    integer type, `dtype` is the default platform integer. (Note: if
    the type of `a` is unsigned, then so is `dtype`.)  Otherwise,
    the dtype is the same as that of `a`.
out : ndarray, optional
    Alternative output array in which to place the result. It must have
    the same shape as the expected output, but the type of the
    output values will be cast if necessary.
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
-------
product_along_axis : ndarray, see `dtype` parameter above.
    An array shaped as `a` but with the specified axis removed.
    Returns a reference to `out` if specified.

See Also
--------
ndarray.prod : equivalent method
numpy.doc.ufuncs : Section "Output arguments"

Notes
-----
Arithmetic is modular when using integer types, and no error is
raised on overflow.  That means that, on a 32-bit platform:

>>> x = np.array([536870910, 536870910, 536870910, 536870910])
>>> np.prod(x) #random
16

Examples
--------
By default, calculate the product of all elements:

>>> np.prod([1.,2.])
2.0

Even when the input array is two-dimensional:

>>> np.prod([[1.,2.],[3.,4.]])
24.0

But we can also specify the axis over which to multiply:

>>> np.prod([[1.,2.],[3.,4.]], axis=1)
array([  2.,  12.])

If the type of `x` is unsigned, then the output type is
the unsigned platform integer:

>>> x = np.array([1, 2, 3], dtype=np.uint8)
>>> np.prod(x).dtype == np.uint
True

If `x` is of a signed integer type, then the output type
is the default platform integer:

>>> x = np.array([1, 2, 3], dtype=np.int8)
>>> np.prod(x).dtype == np.int
True


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

Check if all elements of input array are true.

See Also
--------
numpy.all : Equivalent function; see for details.


try:<EOL><INDENT>ptp = a.ptp<EOL><DEDENT>except AttributeError:<EOL><INDENT>return _wrapit(a, '<STR_LIT>', axis, out)<EOL><DEDENT>return ptp(axis, out)<EOL>

Range of values (maximum - minimum) along an axis.

The name of the function comes from the acronym for 'peak to peak'.

Parameters
----------
a : array_like
    Input values.
axis : int, optional
    Axis along which to find the peaks.  By default, flatten the
    array.
out : array_like
    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 values will be cast if necessary.

Returns
-------
ptp : ndarray
    A new array holding the result, unless `out` was
    specified, in which case a reference to `out` is returned.

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

>>> np.ptp(x, axis=0)
array([2, 2])

>>> np.ptp(x, axis=1)
array([1, 1])


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

return um.multiply.reduce(a, axis=axis, dtype=dtype, out=out, keepdims=keepdims)<EOL>

Return the product of array elements over a given axis.

See Also
--------
prod : equivalent function; see for details.


def take(a, indices, axis=None, out=None, mode='<STR_LIT>'):

try:<EOL><INDENT>take = a.take<EOL><DEDENT>except AttributeError:<EOL><INDENT>return _wrapit(a, '<STR_LIT>', indices, axis, out, mode)<EOL><DEDENT>return take(indices, axis, out, mode)<EOL>

Take elements from an array along an axis.

This function does the same thing as "fancy" indexing (indexing arrays
using arrays); however, it can be easier to use if you need elements
along a given axis.

Parameters
----------
a : array_like
    The source array.
indices : array_like
    The indices of the values to extract.

    .. versionadded:: 1.8.0

    Also allow scalars for indices.
axis : int, optional
    The axis over which to select values. By default, the flattened
    input array is used.
out : ndarray, optional
    If provided, the result will be placed in this array. It should
    be of the appropriate shape and dtype.
mode : {'raise', 'wrap', 'clip'}, optional
    Specifies how out-of-bounds indices will behave.

    * 'raise' -- raise an error (default)
    * 'wrap' -- wrap around
    * 'clip' -- clip to the range

    'clip' mode means that all indices that are too large are replaced
    by the index that addresses the last element along that axis. Note
    that this disables indexing with negative numbers.

Returns
-------
subarray : ndarray
    The returned array has the same type as `a`.

See Also
--------
compress : Take elements using a boolean mask
ndarray.take : equivalent method

Examples
--------
>>> a = [4, 3, 5, 7, 6, 8]
>>> indices = [0, 1, 4]
>>> np.take(a, indices)
array([4, 3, 6])

In this example if `a` is an ndarray, "fancy" indexing can be used.

>>> a = np.array(a)
>>> a[indices]
array([4, 3, 6])

If `indices` is not one dimensional, the output also has these dimensions.

>>> np.take(a, [[0, 1], [2, 3]])
array([[4, 3],
       [5, 7]])


if isinstance(new_shape, (int, nt.integer)):<EOL><INDENT>new_shape = (new_shape,)<EOL><DEDENT>a = ravel(a)<EOL>Na = len(a)<EOL>if not Na: return mu.zeros(new_shape, a.dtype.char)<EOL>total_size = um.multiply.reduce(new_shape)<EOL>n_copies = int(total_size / Na)<EOL>extra = total_size % Na<EOL>if total_size == <NUM_LIT:0>:<EOL><INDENT>return a[:<NUM_LIT:0>]<EOL><DEDENT>if extra != <NUM_LIT:0>:<EOL><INDENT>n_copies = n_copies+<NUM_LIT:1><EOL>extra = Na-extra<EOL><DEDENT>a = concatenate( (a,)*n_copies)<EOL>if extra > <NUM_LIT:0>:<EOL><INDENT>a = a[:-extra]<EOL><DEDENT>return reshape(a, new_shape)<EOL>

Return a new array with the specified shape.

If the new array is larger than the original array, then the new
array is filled with repeated copies of `a`.  Note that this behavior
is different from a.resize(new_shape) which fills with zeros instead
of repeated copies of `a`.

Parameters
----------
a : array_like
    Array to be resized.

new_shape : int or tuple of int
    Shape of resized array.

Returns
-------
reshaped_array : ndarray
    The new array is formed from the data in the old array, repeated
    if necessary to fill out the required number of elements.  The
    data are repeated in the order that they are stored in memory.

See Also
--------
ndarray.resize : resize an array in-place.

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


name = obj.__name__<EOL>base = '<STR_LIT>'<EOL>char = '<STR_LIT>'<EOL>try:<EOL><INDENT>if name[-<NUM_LIT:1>] == '<STR_LIT:_>':<EOL><INDENT>newname = name[:-<NUM_LIT:1>]<EOL><DEDENT>else:<EOL><INDENT>newname = name<EOL><DEDENT>info = typeinfo[english_upper(newname)]<EOL>assert(info[-<NUM_LIT:1>] == obj)  <EOL>bits = info[<NUM_LIT:2>]<EOL><DEDENT>except KeyError:     <EOL><INDENT>base, bits = _evalname(name)<EOL>char = base[<NUM_LIT:0>]<EOL><DEDENT>if name == '<STR_LIT>':<EOL><INDENT>char = '<STR_LIT:b>'<EOL>base = '<STR_LIT:bool>'<EOL><DEDENT>elif name=='<STR_LIT>':<EOL><INDENT>char = '<STR_LIT>'<EOL>base = '<STR_LIT>'<EOL><DEDENT>elif name=='<STR_LIT>':<EOL><INDENT>char = '<STR_LIT:O>'<EOL>base = '<STR_LIT:object>'<EOL>bits = <NUM_LIT:0><EOL><DEDENT>elif name=='<STR_LIT>':<EOL><INDENT>char = '<STR_LIT:M>'<EOL><DEDENT>elif name=='<STR_LIT>':<EOL><INDENT>char = '<STR_LIT:m>'<EOL><DEDENT>if sys.version_info[<NUM_LIT:0>] >= <NUM_LIT:3>:<EOL><INDENT>if name=='<STR_LIT>':<EOL><INDENT>char = '<STR_LIT:S>'<EOL>base = '<STR_LIT>'<EOL><DEDENT>elif name=='<STR_LIT>':<EOL><INDENT>char = '<STR_LIT>'<EOL>base = '<STR_LIT:str>'<EOL><DEDENT><DEDENT>else:<EOL><INDENT>if name=='<STR_LIT>':<EOL><INDENT>char = '<STR_LIT:S>'<EOL>base = '<STR_LIT:string>'<EOL><DEDENT>elif name=='<STR_LIT>':<EOL><INDENT>char = '<STR_LIT>'<EOL>base = '<STR_LIT>'<EOL><DEDENT><DEDENT>bytes = bits // <NUM_LIT:8><EOL>if char != '<STR_LIT>' and bytes != <NUM_LIT:0>:<EOL><INDENT>char = "<STR_LIT>" % (char, bytes)<EOL><DEDENT>return base, bits, char<EOL>

Return a bit-width name for a given type object


try:<EOL><INDENT>return issubclass(arg1, arg2)<EOL><DEDENT>except TypeError:<EOL><INDENT>return False<EOL><DEDENT>

Determine if a class is a subclass of a second class.

`issubclass_` is equivalent to the Python built-in ``issubclass``,
except that it returns False instead of raising a TypeError is one
of the arguments is not a class.

Parameters
----------
arg1 : class
    Input class. True is returned if `arg1` is a subclass of `arg2`.
arg2 : class or tuple of classes.
    Input class. If a tuple of classes, True is returned if `arg1` is a
    subclass of any of the tuple elements.

Returns
-------
out : bool
    Whether `arg1` is a subclass of `arg2` or not.

See Also
--------
issubsctype, issubdtype, issctype

Examples
--------
>>> np.issubclass_(np.int32, np.int)
True
>>> np.issubclass_(np.int32, np.float)
False


try:<EOL><INDENT>if issubclass(rep, generic):<EOL><INDENT>return rep<EOL><DEDENT><DEDENT>except TypeError:<EOL><INDENT>pass<EOL><DEDENT>if isinstance(rep, dtype):<EOL><INDENT>return rep.type<EOL><DEDENT>if isinstance(rep, type):<EOL><INDENT>return _python_type(rep)<EOL><DEDENT>if isinstance(rep, ndarray):<EOL><INDENT>return rep.dtype.type<EOL><DEDENT>try:<EOL><INDENT>res = dtype(rep)<EOL><DEDENT>except:<EOL><INDENT>return default<EOL><DEDENT>return res.type<EOL>

Return the scalar dtype or NumPy equivalent of Python type of an object.

Parameters
----------
rep : any
    The object of which the type is returned.
default : any, optional
    If given, this is returned for objects whose types can not be
    determined. If not given, None is returned for those objects.

Returns
-------
dtype : dtype or Python type
    The data type of `rep`.

See Also
--------
sctype2char, issctype, issubsctype, issubdtype, maximum_sctype

Examples
--------
>>> np.obj2sctype(np.int32)
<type 'numpy.int32'>
>>> np.obj2sctype(np.array([1., 2.]))
<type 'numpy.float64'>
>>> np.obj2sctype(np.array([1.j]))
<type 'numpy.complex128'>

>>> np.obj2sctype(dict)
<type 'numpy.object_'>
>>> np.obj2sctype('string')
<type 'numpy.string_'>

>>> np.obj2sctype(1, default=list)
<type 'list'>


def fromrecords(recList, dtype=None, shape=None, formats=None, names=None,<EOL>titles=None, aligned=False, byteorder=None):

nfields = len(recList[<NUM_LIT:0>])<EOL>if formats is None and dtype is None:  <EOL><INDENT>obj = sb.array(recList, dtype=object)<EOL>arrlist = [sb.array(obj[..., i].tolist()) for i in range(nfields)]<EOL>return fromarrays(arrlist, formats=formats, shape=shape, names=names,<EOL>titles=titles, aligned=aligned, byteorder=byteorder)<EOL><DEDENT>if dtype is not None:<EOL><INDENT>descr = sb.dtype((record, dtype))<EOL><DEDENT>else:<EOL><INDENT>descr = format_parser(formats, names, titles, aligned, byteorder)._descr<EOL><DEDENT>try:<EOL><INDENT>retval = sb.array(recList, dtype=descr)<EOL><DEDENT>except TypeError:  <EOL><INDENT>if (shape is None or shape == <NUM_LIT:0>):<EOL><INDENT>shape = len(recList)<EOL><DEDENT>if isinstance(shape, (int, long)):<EOL><INDENT>shape = (shape,)<EOL><DEDENT>if len(shape) > <NUM_LIT:1>:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>_array = recarray(shape, descr)<EOL>for k in range(_array.size):<EOL><INDENT>_array[k] = tuple(recList[k])<EOL><DEDENT>return _array<EOL><DEDENT>else:<EOL><INDENT>if shape is not None and retval.shape != shape:<EOL><INDENT>retval.shape = shape<EOL><DEDENT><DEDENT>res = retval.view(recarray)<EOL>return res<EOL>

create a recarray from a list of records in text form

        The data in the same field can be heterogeneous, they will be promoted
        to the highest data type.  This method is intended for creating
        smaller record arrays.  If used to create large array without formats
        defined

        r=fromrecords([(2,3.,'abc')]*100000)

        it can be slow.

        If formats is None, then this will auto-detect formats. Use list of
        tuples rather than list of lists for faster processing.

    >>> r=np.core.records.fromrecords([(456,'dbe',1.2),(2,'de',1.3)],
    ... names='col1,col2,col3')
    >>> print r[0]
    (456, 'dbe', 1.2)
    >>> r.col1
    array([456,   2])
    >>> r.col2
    chararray(['dbe', 'de'],
          dtype='|S3')
    >>> import pickle
    >>> print pickle.loads(pickle.dumps(r))
    [(456, 'dbe', 1.2) (2, 'de', 1.3)]


def fromarrays(arrayList, dtype=None, shape=None, formats=None,<EOL>names=None, titles=None, aligned=False, byteorder=None):

arrayList = [sb.asarray(x) for x in arrayList]<EOL>if shape is None or shape == <NUM_LIT:0>:<EOL><INDENT>shape = arrayList[<NUM_LIT:0>].shape<EOL><DEDENT>if isinstance(shape, int):<EOL><INDENT>shape = (shape,)<EOL><DEDENT>if formats is None and dtype is None:<EOL><INDENT>formats = []<EOL>for obj in arrayList:<EOL><INDENT>if not isinstance(obj, ndarray):<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>formats.append(obj.dtype.str)<EOL><DEDENT>formats = '<STR_LIT:U+002C>'.join(formats)<EOL><DEDENT>if dtype is not None:<EOL><INDENT>descr = sb.dtype(dtype)<EOL>_names = descr.names<EOL><DEDENT>else:<EOL><INDENT>parsed = format_parser(formats, names, titles, aligned, byteorder)<EOL>_names = parsed._names<EOL>descr = parsed._descr<EOL><DEDENT>if len(descr) != len(arrayList):<EOL><INDENT>raise ValueError("<STR_LIT>"<EOL>"<STR_LIT>")<EOL><DEDENT>d0 = descr[<NUM_LIT:0>].shape<EOL>nn = len(d0)<EOL>if nn > <NUM_LIT:0>:<EOL><INDENT>shape = shape[:-nn]<EOL><DEDENT>for k, obj in enumerate(arrayList):<EOL><INDENT>nn = len(descr[k].shape)<EOL>testshape = obj.shape[:len(obj.shape) - nn]<EOL>if testshape != shape:<EOL><INDENT>raise ValueError("<STR_LIT>" % k)<EOL><DEDENT><DEDENT>_array = recarray(shape, descr)<EOL>for i in range(len(arrayList)):<EOL><INDENT>_array[_names[i]] = arrayList[i]<EOL><DEDENT>return _array<EOL>


def __init__(self, float_conv=float,int_conv=int,<EOL>float_to_float=float,<EOL>float_to_str = lambda v:'<STR_LIT>' % v,<EOL>title = '<STR_LIT>'):

<EOL>with errstate(under='<STR_LIT:ignore>'):<EOL><INDENT>self._do_init(float_conv, int_conv, float_to_float, float_to_str, title)<EOL><DEDENT>

float_conv - convert integer to float (array)
int_conv   - convert float (array) to integer
float_to_float - convert float array to float
float_to_str - convert array float to str
title        - description of used floating point numbers


if a.ndim == <NUM_LIT:0>: a.shape = (<NUM_LIT:1>,)<EOL>return a<EOL>


a_arr = numpy.asarray(a)<EOL>return _vec_string(a_arr, a_arr.dtype, '<STR_LIT:title>')<EOL>

Return element-wise title cased version of string or unicode.

Title case words start with uppercase characters, all remaining cased
characters are lowercase.

Calls `str.title` element-wise.

For 8-bit strings, this method is locale-dependent.

Parameters
----------
a : array_like, {str, unicode}
    Input array.

Returns
-------
out : ndarray
    Output array of str or unicode, depending on input type

See also
--------
str.title

Examples
--------
>>> c=np.array(['a1b c','1b ca','b ca1','ca1b'],'S5'); c
array(['a1b c', '1b ca', 'b ca1', 'ca1b'],
    dtype='|S5')
>>> np.char.title(c)
array(['A1B C', '1B Ca', 'B Ca1', 'Ca1B'],
    dtype='|S5')


def center(self, width, fillchar='<STR_LIT:U+0020>'):

return asarray(center(self, width, fillchar))<EOL>

Return a copy of `self` with its elements centered in a
string of length `width`.

See also
--------
center


return join(self, seq)<EOL>

Return a string which is the concatenation of the strings in the
sequence `seq`.

See also
--------
char.join


a_arr = numpy.asarray(a)<EOL>width_arr = numpy.asarray(width)<EOL>size = long(numpy.max(width_arr.flat))<EOL>return _vec_string(<EOL>a_arr, (a_arr.dtype.type, size), '<STR_LIT>', (width_arr,))<EOL>

Return the numeric string left-filled with zeros

Calls `str.zfill` element-wise.

Parameters
----------
a : array_like, {str, unicode}
    Input array.
width : int
    Width of string to left-fill elements in `a`.

Returns
-------
out : ndarray, {str, unicode}
    Output array of str or unicode, depending on input type

See also
--------
str.zfill


return _to_string_or_unicode_array(<EOL>_vec_string(<EOL>a, object_, '<STR_LIT:replace>', [old, new] +_clean_args(count)))<EOL>

For each element in `a`, return a copy of the string with all
occurrences of substring `old` replaced by `new`.

Calls `str.replace` element-wise.

Parameters
----------
a : array-like of str or unicode

old, new : str or unicode

count : int, optional
    If the optional argument `count` is given, only the first
    `count` occurrences are replaced.

Returns
-------
out : ndarray
    Output array of str or unicode, depending on input type

See also
--------
str.replace


return asarray(zfill(self, width))<EOL>

Return the numeric string left-filled with zeros in a string of
length `width`.

See also
--------
char.zfill


return _vec_string(a, bool_, '<STR_LIT>')<EOL>

Returns true for each element if all characters in the string are
digits and there is at least one character, false otherwise.

Calls `str.isdigit` element-wise.

For 8-bit strings, this method is locale-dependent.

Parameters
----------
a : array_like of str or unicode

Returns
-------
out : ndarray
    Output array of bools

See also
--------
str.isdigit


Returns true for each element if the element is a titlecased
string and there is at least one character, false otherwise.

Call `str.istitle` element-wise.

For 8-bit strings, this method is locale-dependent.

Parameters
----------
a : array_like of str or unicode

Returns
-------
out : ndarray
    Output array of bools

See also
--------
str.istitle


return asarray(lower(self))<EOL>

Return an array with the elements of `self` converted to
lowercase.

See also
--------
char.lower


arr1 = numpy.asarray(x1)<EOL>arr2 = numpy.asarray(x2)<EOL>out_size = _get_num_chars(arr1) + _get_num_chars(arr2)<EOL>dtype = _use_unicode(arr1, arr2)<EOL>return _vec_string(arr1, (dtype, out_size), '<STR_LIT>', (arr2,))<EOL>

Return element-wise string concatenation for two arrays of str or unicode.

Arrays `x1` and `x2` must have the same shape.

Parameters
----------
x1 : array_like of str or unicode
    Input array.
x2 : array_like of str or unicode
    Input array.

Returns
-------
add : ndarray
    Output array of `string_` or `unicode_`, depending on input types
    of the same shape as `x1` and `x2`.


return isdecimal(self)<EOL>

For each element in `self`, return True if there are only
decimal characters in the element.

See also
--------
char.isdecimal


a_arr = numpy.asarray(a)<EOL>return _vec_string(a_arr, a_arr.dtype, '<STR_LIT>')<EOL>

Return an array with the elements converted to uppercase.

Calls `str.upper` element-wise.

For 8-bit strings, this method is locale-dependent.

Parameters
----------
a : array_like, {str, unicode}
    Input array.

Returns
-------
out : ndarray, {str, unicode}
    Output array of str or unicode, depending on input type

See also
--------
str.upper

Examples
--------
>>> c = np.array(['a1b c', '1bca', 'bca1']); c
array(['a1b c', '1bca', 'bca1'],
    dtype='|S5')
>>> np.char.upper(c)
array(['A1B C', '1BCA', 'BCA1'],
    dtype='|S5')


return less_equal(self, other)<EOL>

Return (self <= other) element-wise.

See also
--------
less_equal


a_arr = numpy.asarray(a)<EOL>return _vec_string(a_arr, a_arr.dtype, '<STR_LIT>', (chars,))<EOL>

For each element in `a`, return a copy with the leading characters
removed.

Calls `str.lstrip` element-wise.

Parameters
----------
a : array-like, {str, unicode}
    Input array.

chars : {str, unicode}, optional
    The `chars` argument is a string specifying the set of
    characters to be removed. If omitted or None, the `chars`
    argument defaults to removing whitespace. The `chars` argument
    is not a prefix; rather, all combinations of its values are
    stripped.

Returns
-------
out : ndarray, {str, unicode}
    Output array of str or unicode, depending on input type

See also
--------
str.lstrip

Examples
--------
>>> c = np.array(['aAaAaA', '  aA  ', 'abBABba'])
>>> c
array(['aAaAaA', '  aA  ', 'abBABba'],
    dtype='|S7')

The 'a' variable is unstripped from c[1] because whitespace leading.

>>> np.char.lstrip(c, 'a')
array(['AaAaA', '  aA  ', 'bBABba'],
    dtype='|S7')

>>> np.char.lstrip(c, 'A') # leaves c unchanged
array(['aAaAaA', '  aA  ', 'abBABba'],
    dtype='|S7')
>>> (np.char.lstrip(c, ' ') == np.char.lstrip(c, '')).all()
... # XXX: is this a regression? this line now returns False
... # np.char.lstrip(c,'') does not modify c at all.
True
>>> (np.char.lstrip(c, ' ') == np.char.lstrip(c, None)).all()
True


if issubclass(a.dtype.type, unicode_):<EOL><INDENT>return a.itemsize // <NUM_LIT:4><EOL><DEDENT>return a.itemsize<EOL>

Helper function that returns the number of characters per field in
a string or unicode array.  This is to abstract out the fact that
for a unicode array this is itemsize / 4.


def startswith(a, prefix, start=<NUM_LIT:0>, end=None):

return _vec_string(<EOL>a, bool_, '<STR_LIT>', [prefix, start] + _clean_args(end))<EOL>

Returns a boolean array which is `True` where the string element
in `a` starts with `prefix`, otherwise `False`.

Calls `str.startswith` element-wise.

Parameters
----------
a : array_like of str or unicode

prefix : str

start, end : int, optional
    With optional `start`, test beginning at that position. With
    optional `end`, stop comparing at that position.

Returns
-------
out : ndarray
    Array of booleans

See also
--------
str.startswith


<EOL>return _vec_string(<EOL>a, object_, '<STR_LIT>', [sep] + _clean_args(maxsplit))<EOL>

For each element in `a`, return a list of the words in the
string, using `sep` as the delimiter string.

Calls `str.rsplit` element-wise.

Parameters
----------
a : array_like of str or unicode

sep : str or unicode, optional
   If `sep` is not specified or `None`, any whitespace string is a
   separator.

maxsplit : int, optional
    If `maxsplit` is given, at most `maxsplit` splits are done.

Returns
-------
out : ndarray
    Array of list objects

See also
--------
str.split, rsplit


return asarray(lstrip(self, chars))<EOL>

For each element in `self`, return a copy with the leading characters
removed.

See also
--------
char.lstrip


def replace(self, old, new, count=None):

return asarray(replace(self, old, new, count))<EOL>

For each element in `self`, return a copy of the string with all
occurrences of substring `old` replaced by `new`.

See also
--------
char.replace


return asarray(mod(self, i))<EOL>

Return (self % i), that is pre-Python 2.6 string formatting
(iterpolation), element-wise for a pair of array_likes of `string_`
or `unicode_`.

See also
--------
mod


return asarray(add(numpy.asarray(other), self))<EOL>

Return (other + self), that is string concatenation,
element-wise for a pair of array_likes of `string_` or `unicode_`.

See also
--------
add


return isupper(self)<EOL>

Returns true for each element if all cased characters in the
string are uppercase and there is at least one character, false
otherwise.

See also
--------
char.isupper


return asarray(upper(self))<EOL>

Return an array with the elements of `self` converted to
uppercase.

See also
--------
char.upper


def asarray(obj, itemsize=None, unicode=None, order=None):

return array(obj, itemsize, copy=False,<EOL>unicode=unicode, order=order)<EOL>

Convert the input to a `chararray`, copying the data only if
necessary.

Versus a regular Numpy array of type `str` or `unicode`, this
class adds the following functionality:

  1) values automatically have whitespace removed from the end
     when indexed

  2) comparison operators automatically remove whitespace from the
     end when comparing values

  3) vectorized string operations are provided as methods
     (e.g. `str.endswith`) and infix operators (e.g. +, *, %)

Parameters
----------
obj : array of str or unicode-like

itemsize : int, optional
    `itemsize` is the number of characters per scalar in the
    resulting array.  If `itemsize` is None, and `obj` is an
    object array or a Python list, the `itemsize` will be
    automatically determined.  If `itemsize` is provided and `obj`
    is of type str or unicode, then the `obj` string will be
    chunked into `itemsize` pieces.

unicode : bool, optional
    When true, the resulting `chararray` can contain Unicode
    characters, when false only 8-bit characters.  If unicode is
    `None` and `obj` is one of the following:

      - a `chararray`,
      - an ndarray of type `str` or 'unicode`
      - a Python str or unicode object,

    then the unicode setting of the output array will be
    automatically determined.

order : {'C', 'F'}, optional
    Specify the order of the array.  If order is 'C' (default), then the
    array will be in C-contiguous order (last-index varies the
    fastest).  If order is 'F', then the returned array
    will be in Fortran-contiguous order (first-index varies the
    fastest).


return greater_equal(self, other)<EOL>

Return (self >= other) element-wise.

See also
--------
greater_equal


For each element in `a`, return a copy with the trailing
characters removed.

Calls `str.rstrip` element-wise.

Parameters
----------
a : array-like of str or unicode

chars : str or unicode, optional
   The `chars` argument is a string specifying the set of
   characters to be removed. If omitted or None, the `chars`
   argument defaults to removing whitespace. The `chars` argument
   is not a suffix; rather, all combinations of its values are
   stripped.

Returns
-------
out : ndarray
    Output array of str or unicode, depending on input type

See also
--------
str.rstrip

Examples
--------
>>> c = np.array(['aAaAaA', 'abBABba'], dtype='S7'); c
array(['aAaAaA', 'abBABba'],
    dtype='|S7')
>>> np.char.rstrip(c, 'a')
array(['aAaAaA', 'abBABb'],
    dtype='|S7')
>>> np.char.rstrip(c, 'A')
array(['aAaAa', 'abBABba'],
    dtype='|S7')


def rfind(self, sub, start=<NUM_LIT:0>, end=None):

return rfind(self, sub, start, end)<EOL>

For each element in `self`, return the highest index in the string
where substring `sub` is found, such that `sub` is contained
within [`start`, `end`].

See also
--------
char.rfind


return isalnum(self)<EOL>

Returns true for each element if all characters in the string
are alphanumeric and there is at least one character, false
otherwise.

See also
--------
char.isalnum


return compare_chararrays(x1, x2, '<STR_LIT>', True)<EOL>

Return (x1 >= x2) element-wise.

Unlike `numpy.greater_equal`, this comparison is performed by
first stripping whitespace characters from the end of the string.
This behavior is provided for backward-compatibility with
numarray.

Parameters
----------
x1, x2 : array_like of str or unicode
    Input arrays of the same shape.

Returns
-------
out : {ndarray, bool}
    Output array of bools, or a single bool if x1 and x2 are scalars.

See Also
--------
equal, not_equal, less_equal, greater, less


def encode(a, encoding=None, errors=None):

return _to_string_or_unicode_array(<EOL>_vec_string(a, object_, '<STR_LIT>', _clean_args(encoding, errors)))<EOL>

Calls `str.encode` element-wise.

The set of available codecs comes from the Python standard library,
and may be extended at runtime. For more information, see the codecs
module.

Parameters
----------
a : array_like of str or unicode

encoding : str, optional
   The name of an encoding

errors : str, optional
   Specifies how to handle encoding errors

Returns
-------
out : ndarray

See also
--------
str.encode

Notes
-----
The type of the result will depend on the encoding specified.


return istitle(self)<EOL>

Returns true for each element if the element is a titlecased
string and there is at least one character, false otherwise.

See also
--------
char.istitle


def endswith(a, suffix, start=<NUM_LIT:0>, end=None):

return _vec_string(<EOL>a, bool_, '<STR_LIT>', [suffix, start] + _clean_args(end))<EOL>

Returns a boolean array which is `True` where the string element
in `a` ends with `suffix`, otherwise `False`.

Calls `str.endswith` element-wise.

Parameters
----------
a : array_like of str or unicode

suffix : str

start, end : int, optional
    With optional `start`, test beginning at that position. With
    optional `end`, stop comparing at that position.

Returns
-------
out : ndarray
    Outputs an array of bools.

See also
--------
str.endswith

Examples
--------
>>> s = np.array(['foo', 'bar'])
>>> s[0] = 'foo'
>>> s[1] = 'bar'
>>> s
array(['foo', 'bar'],
    dtype='|S3')
>>> np.char.endswith(s, 'ar')
array([False,  True], dtype=bool)
>>> np.char.endswith(s, 'a', start=1, end=2)
array([False,  True], dtype=bool)


if _use_unicode(a) != unicode_:<EOL><INDENT>raise TypeError("<STR_LIT>")<EOL><DEDENT>return _vec_string(a, bool_, '<STR_LIT>')<EOL>

For each element, return True if there are only decimal
characters in the element.

Calls `unicode.isdecimal` element-wise.

Decimal characters include digit characters, and all characters
that that can be used to form decimal-radix numbers,
e.g. ``U+0660, ARABIC-INDIC DIGIT ZERO``.

Parameters
----------
a : array_like, unicode
    Input array.

Returns
-------
out : ndarray, bool
    Array of booleans identical in shape to `a`.

See also
--------
unicode.isdecimal


def decode(a, encoding=None, errors=None):

Calls `str.decode` element-wise.

The set of available codecs comes from the Python standard library,
and may be extended at runtime.  For more information, see the
:mod:`codecs` module.

Parameters
----------
a : array_like of str or unicode

encoding : str, optional
   The name of an encoding

errors : str, optional
   Specifies how to handle encoding errors

Returns
-------
out : ndarray

See also
--------
str.decode

Notes
-----
The type of the result will depend on the encoding specified.

Examples
--------
>>> c = np.array(['aAaAaA', '  aA  ', 'abBABba'])
>>> c
array(['aAaAaA', '  aA  ', 'abBABba'],
    dtype='|S7')
>>> np.char.encode(c, encoding='cp037')
array(['\\x81\\xc1\\x81\\xc1\\x81\\xc1', '@@\\x81\\xc1@@',
    '\\x81\\x82\\xc2\\xc1\\xc2\\x82\\x81'],
    dtype='|S7')


from distutils.version import LooseVersion<EOL>v = config.get_version('<STR_LIT>')<EOL>if v is None:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>pv = LooseVersion(vstring=v).version<EOL>if len(pv) > <NUM_LIT:3>:<EOL><INDENT>return False<EOL><DEDENT>return True<EOL>

Return True if a released version of numpy is detected.


curapi_hash, api_hash = get_api_versions(apiversion, codegen_dir)<EOL>if not curapi_hash == api_hash:<EOL><INDENT>msg = "<STR_LIT>""<STR_LIT>""<STR_LIT>""<STR_LIT>""<STR_LIT>"<EOL>warnings.warn(msg % (apiversion, curapi_hash, apiversion, api_hash,<EOL>__file__),<EOL>MismatchCAPIWarning)<EOL><DEDENT>

Emits a MismacthCAPIWarning if the C API version needs updating.


from numpy.core.multiarray import dtype<EOL>if value.fields is None:<EOL><INDENT>vfields = {'<STR_LIT>': (value, <NUM_LIT:0>)}<EOL><DEDENT>else:<EOL><INDENT>vfields = dict(value.fields)<EOL><DEDENT>if value.names and value.names[-<NUM_LIT:1>] == '<STR_LIT>' andvalue['<STR_LIT>'].char == '<STR_LIT>':<EOL><INDENT>vfields['<STR_LIT>'] = ('<STR_LIT>' % (vfields['<STR_LIT>'][<NUM_LIT:0>].itemsize + padding),<EOL>vfields['<STR_LIT>'][<NUM_LIT:1>])<EOL>value = dtype(vfields)<EOL><DEDENT>else:<EOL><INDENT>j = <NUM_LIT:0><EOL>while True:<EOL><INDENT>name = '<STR_LIT>' % j<EOL>if name not in vfields:<EOL><INDENT>vfields[name] = ('<STR_LIT>' % padding, value.itemsize)<EOL>break<EOL><DEDENT>j += <NUM_LIT:1><EOL><DEDENT>value = dtype(vfields)<EOL>if '<STR_LIT>' not in vfields:<EOL><INDENT>names = list(value.names)<EOL>names[-<NUM_LIT:1>] = '<STR_LIT>'<EOL>value.names = tuple(names)<EOL><DEDENT><DEDENT>return value<EOL>

Inject the specified number of padding bytes at the end of a dtype


dimensions = tuple(dimensions)<EOL>N = len(dimensions)<EOL>if N == <NUM_LIT:0>:<EOL><INDENT>return array([], dtype=dtype)<EOL><DEDENT>res = empty((N,)+dimensions, dtype=dtype)<EOL>for i, dim in enumerate(dimensions):<EOL><INDENT>tmp = arange(dim, dtype=dtype)<EOL>tmp.shape = (<NUM_LIT:1>,)*i + (dim,)+(<NUM_LIT:1>,)*(N-i-<NUM_LIT:1>)<EOL>newdim = dimensions[:i] + (<NUM_LIT:1>,)+ dimensions[i+<NUM_LIT:1>:]<EOL>val = zeros(newdim, dtype)<EOL>add(tmp, val, res[i])<EOL><DEDENT>return res<EOL>

Return an array representing the indices of a grid.

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

Parameters
----------
dimensions : sequence of ints
    The shape of the grid.
dtype : dtype, optional
    Data type of the result.

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

See Also
--------
mgrid, meshgrid

Notes
-----
The output shape is obtained by prepending the number of dimensions
in front of the tuple of dimensions, i.e. if `dimensions` is a tuple
``(r0, ..., rN-1)`` of length ``N``, the output shape is
``(N,r0,...,rN-1)``.

The subarrays ``grid[k]`` contains the N-D array of indices along the
``k-th`` axis. Explicitly::

    grid[k,i0,i1,...,iN-1] = ik

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

The indices can be used as an index into an array.

>>> x = np.arange(20).reshape(5, 4)
>>> row, col = np.indices((2, 3))
>>> x[row, col]
array([[0, 1, 2],
       [4, 5, 6]])

Note that it would be more straightforward in the above example to
extract the required elements directly with ``x[:2, :3]``.


def correlate(a, v, mode='<STR_LIT>', old_behavior=False):

mode = _mode_from_name(mode)<EOL>e old behavior should be made available under a different name, see thread<EOL>tp://thread.gmane.org/gmane.comp.python.numeric.general/<NUM_LIT>/focus=<NUM_LIT><EOL>if old_behavior:<EOL><INDENT>warnings.warn("""<STR_LIT>""",<EOL>DeprecationWarning)<EOL>return multiarray.correlate(a, v, mode)<EOL><DEDENT>else:<EOL><INDENT>return multiarray.correlate2(a, v, mode)<EOL><DEDENT>

Cross-correlation of two 1-dimensional sequences.

This function computes the correlation as generally defined in signal
processing texts::

    c_{av}[k] = sum_n a[n+k] * conj(v[n])

with a and v sequences being zero-padded where necessary and conj being
the conjugate.

Parameters
----------
a, v : array_like
    Input sequences.
mode : {'valid', 'same', 'full'}, optional
    Refer to the `convolve` docstring.  Note that the default
    is `valid`, unlike `convolve`, which uses `full`.
old_behavior : bool
    If True, uses the old behavior from Numeric,
    (correlate(a,v) == correlate(v,a), and the conjugate is not taken
    for complex arrays). If False, uses the conventional signal
    processing definition.

Returns
-------
out : ndarray
    Discrete cross-correlation of `a` and `v`.

See Also
--------
convolve : Discrete, linear convolution of two one-dimensional sequences.

Notes
-----
The definition of correlation above is not unique and sometimes correlation
may be defined differently. Another common definition is::

    c'_{av}[k] = sum_n a[n] conj(v[n+k])

which is related to ``c_{av}[k]`` by ``c'_{av}[k] = c_{av}[-k]``.

Examples
--------
>>> np.correlate([1, 2, 3], [0, 1, 0.5])
array([ 3.5])
>>> np.correlate([1, 2, 3], [0, 1, 0.5], "same")
array([ 2. ,  3.5,  3. ])
>>> np.correlate([1, 2, 3], [0, 1, 0.5], "full")
array([ 0.5,  2. ,  3.5,  3. ,  0. ])

Using complex sequences:

>>> np.correlate([1+1j, 2, 3-1j], [0, 1, 0.5j], 'full')
array([ 0.5-0.5j,  1.0+0.j ,  1.5-1.5j,  3.0-1.j ,  0.0+0.j ])

Note that you get the time reversed, complex conjugated result
when the two input sequences change places, i.e.,
``c_{va}[k] = c^{*}_{av}[-k]``:

>>> np.correlate([0, 1, 0.5j], [1+1j, 2, 3-1j], 'full')
array([ 0.0+0.j ,  3.0+1.j ,  1.5+1.5j,  1.0+0.j ,  0.5+0.5j])


if size > <NUM_LIT>:<EOL><INDENT>raise ValueError("<STR_LIT>" % size)<EOL><DEDENT>if size < <NUM_LIT:5>:<EOL><INDENT>raise ValueError("<STR_LIT>" %size)<EOL><DEDENT>if size % <NUM_LIT:16> != <NUM_LIT:0>:<EOL><INDENT>raise ValueError("<STR_LIT>" %size)<EOL><DEDENT>pyvals = umath.geterrobj()<EOL>old = getbufsize()<EOL>pyvals[<NUM_LIT:0>] = size<EOL>umath.seterrobj(pyvals)<EOL>return old<EOL>

Set the size of the buffer used in ufuncs.

Parameters
----------
size : int
    Size of buffer.


return a.flags.fnc<EOL>

Returns True if array is arranged in Fortran-order in memory
and not C-order.

Parameters
----------
a : ndarray
    Input array.

Examples
--------

np.array allows to specify whether the array is written in C-contiguous
order (last index varies the fastest), or FORTRAN-contiguous order in
memory (first index varies the fastest).

>>> a = np.array([[1, 2, 3], [4, 5, 6]], order='C')
>>> a
array([[1, 2, 3],
       [4, 5, 6]])
>>> np.isfortran(a)
False

>>> b = np.array([[1, 2, 3], [4, 5, 6]], order='FORTRAN')
>>> b
array([[1, 2, 3],
       [4, 5, 6]])
>>> np.isfortran(b)
True

The transpose of a C-ordered array is a FORTRAN-ordered array.

>>> a = np.array([[1, 2, 3], [4, 5, 6]], order='C')
>>> a
array([[1, 2, 3],
       [4, 5, 6]])
>>> np.isfortran(a)
False
>>> b = a.T
>>> b
array([[1, 4],
       [2, 5],
       [3, 6]])
>>> np.isfortran(b)
True

C-ordered arrays evaluate as False even if they are also FORTRAN-ordered.

>>> np.isfortran(np.array([1, 2], order='FORTRAN'))
False


<EOL>sign = '<STR_LIT>'<EOL>if num < <NUM_LIT:0>:<EOL><INDENT>if width is None:<EOL><INDENT>sign = '<STR_LIT:->'<EOL>num = -num<EOL><DEDENT>else:<EOL><INDENT>num = <NUM_LIT:2>**width + num<EOL><DEDENT><DEDENT>elif num == <NUM_LIT:0>:<EOL><INDENT>return '<STR_LIT:0>'*(width or <NUM_LIT:1>)<EOL><DEDENT>ostr = hex(num)<EOL>bin = '<STR_LIT>'.join([_lkup[ch] for ch in ostr[<NUM_LIT:2>:]])<EOL>bin = bin.lstrip('<STR_LIT:0>')<EOL>if width is not None:<EOL><INDENT>bin = bin.zfill(width)<EOL><DEDENT>return sign + bin<EOL>

Return the binary representation of the input number as a string.

For negative numbers, if width is not given, a minus sign is added to the
front. If width is given, the two's complement of the number is
returned, with respect to that width.

In a two's-complement system negative numbers are represented by the two's
complement of the absolute value. This is the most common method of
representing signed integers on computers [1]_. A N-bit two's-complement
system can represent every integer in the range
:math:`-2^{N-1}` to :math:`+2^{N-1}-1`.

Parameters
----------
num : int
    Only an integer decimal number can be used.
width : int, optional
    The length of the returned string if `num` is positive, the length of
    the two's complement if `num` is negative.

Returns
-------
bin : str
    Binary representation of `num` or two's complement of `num`.

See Also
--------
base_repr: Return a string representation of a number in the given base
           system.

Notes
-----
`binary_repr` is equivalent to using `base_repr` with base 2, but about 25x
faster.

References
----------
.. [1] Wikipedia, "Two's complement",
    http://en.wikipedia.org/wiki/Two's_complement

Examples
--------
>>> np.binary_repr(3)
'11'
>>> np.binary_repr(-3)
'-11'
>>> np.binary_repr(3, width=4)
'0011'

The two's complement is returned when the input number is negative and
width is specified:

>>> np.binary_repr(-3, width=4)
'1101'


if isinstance(file, type("<STR_LIT>")):<EOL><INDENT>file = open(file, "<STR_LIT:rb>")<EOL><DEDENT>return pickle.load(file)<EOL>

Wrapper around cPickle.load which accepts either a file-like object or
a filename.

Note that the NumPy binary format is not based on pickle/cPickle anymore.
For details on the preferred way of loading and saving files, see `load`
and `save`.

See Also
--------
load, save


if f is None:<EOL><INDENT>if repr:<EOL><INDENT>return multiarray.set_string_function(array_repr, <NUM_LIT:1>)<EOL><DEDENT>else:<EOL><INDENT>return multiarray.set_string_function(array_str, <NUM_LIT:0>)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>return multiarray.set_string_function(f, repr)<EOL><DEDENT>

Set a Python function to be used when pretty printing arrays.

Parameters
----------
f : function or None
    Function to be used to pretty print arrays. The function should expect
    a single array argument and return a string of the representation of
    the array. If None, the function is reset to the default NumPy function
    to print arrays.
repr : bool, optional
    If True (default), the function for pretty printing (``__repr__``)
    is set, if False the function that returns the default string
    representation (``__str__``) is set.

See Also
--------
set_printoptions, get_printoptions

Examples
--------
>>> def pprint(arr):
...     return 'HA! - What are you going to do now?'
...
>>> np.set_string_function(pprint)
>>> a = np.arange(10)
>>> a
HA! - What are you going to do now?
>>> print a
[0 1 2 3 4 5 6 7 8 9]

We can reset the function to the default:

>>> np.set_string_function(None)
>>> a
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])

`repr` affects either pretty printing or normal string representation.
Note that ``__repr__`` is still affected by setting ``__str__``
because the width of each array element in the returned string becomes
equal to the length of the result of ``__str__()``.

>>> x = np.arange(4)
>>> np.set_string_function(lambda x:'random', repr=False)
>>> x.__str__()
'random'
>>> x.__repr__()
'array([     0,      1,      2,      3])'


return umath.geterrobj()[<NUM_LIT:0>]<EOL>

Return the size of the buffer used in ufuncs.

Returns
-------
getbufsize : int
    Size of ufunc buffer in bytes.


try:<EOL><INDENT>a1, a2 = asarray(a1), asarray(a2)<EOL><DEDENT>except:<EOL><INDENT>return False<EOL><DEDENT>if a1.shape != a2.shape:<EOL><INDENT>return False<EOL><DEDENT>return bool(asarray(a1 == a2).all())<EOL>

True if two arrays have the same shape and elements, False otherwise.

Parameters
----------
a1, a2 : array_like
    Input arrays.

Returns
-------
b : bool
    Returns True if the arrays are equal.

See Also
--------
allclose: Returns True if two arrays are element-wise equal within a
          tolerance.
array_equiv: Returns True if input arrays are shape consistent and all
             elements equal.

Examples
--------
>>> np.array_equal([1, 2], [1, 2])
True
>>> np.array_equal(np.array([1, 2]), np.array([1, 2]))
True
>>> np.array_equal([1, 2], [1, 2, 3])
False
>>> np.array_equal([1, 2], [1, 4])
False


maskvalue = umath.geterrobj()[<NUM_LIT:1>]<EOL>mask = <NUM_LIT:7><EOL>res = {}<EOL>val = (maskvalue >> SHIFT_DIVIDEBYZERO) & mask<EOL>res['<STR_LIT>'] = _errdict_rev[val]<EOL>val = (maskvalue >> SHIFT_OVERFLOW) & mask<EOL>res['<STR_LIT>'] = _errdict_rev[val]<EOL>val = (maskvalue >> SHIFT_UNDERFLOW) & mask<EOL>res['<STR_LIT>'] = _errdict_rev[val]<EOL>val = (maskvalue >> SHIFT_INVALID) & mask<EOL>res['<STR_LIT>'] = _errdict_rev[val]<EOL>return res<EOL>

Get the current way of handling floating-point errors.

Returns
-------
res : dict
    A dictionary with keys "divide", "over", "under", and "invalid",
    whose values are from the strings "ignore", "print", "log", "warn",
    "raise", and "call". The keys represent possible floating-point
    exceptions, and the values define how these exceptions are handled.

See Also
--------
geterrcall, seterr, seterrcall

Notes
-----
For complete documentation of the types of floating-point exceptions and
treatment options, see `seterr`.

Examples
--------
>>> np.geterr()
{'over': 'warn', 'divide': 'warn', 'invalid': 'warn',
'under': 'ignore'}
>>> np.arange(3.) / np.arange(3.)
array([ NaN,   1.,   1.])

>>> oldsettings = np.seterr(all='warn', over='raise')
>>> np.geterr()
{'over': 'raise', 'divide': 'warn', 'invalid': 'warn', 'under': 'warn'}
>>> np.arange(3.) / np.arange(3.)
__main__:1: RuntimeWarning: invalid value encountered in divide
array([ NaN,   1.,   1.])


a = asarray(a).astype(complex)<EOL>s, axes = _cook_nd_args(a, s, axes, invreal=<NUM_LIT:1>)<EOL>for ii in range(len(axes)-<NUM_LIT:1>):<EOL><INDENT>a = ifft(a, s[ii], axes[ii])<EOL><DEDENT>a = irfft(a, s[-<NUM_LIT:1>], axes[-<NUM_LIT:1>])<EOL>return a<EOL>

Compute the inverse of the N-dimensional FFT of real input.

This function computes the inverse of the N-dimensional discrete
Fourier Transform for real input over any number of axes in an
M-dimensional array by means of the Fast Fourier Transform (FFT).  In
other words, ``irfftn(rfftn(a), a.shape) == a`` to within numerical
accuracy. (The ``a.shape`` is necessary like ``len(a)`` is for `irfft`,
and for the same reason.)

The input should be ordered in the same way as is returned by `rfftn`,
i.e. as for `irfft` for the final transformation axis, and as for `ifftn`
along all the other axes.

Parameters
----------
a : array_like
    Input array.
s : sequence of ints, optional
    Shape (length of each transformed axis) of the output
    (``s[0]`` refers to axis 0, ``s[1]`` to axis 1, etc.). `s` is also the
    number of input points used along this axis, except for the last axis,
    where ``s[-1]//2+1`` points of the input are used.
    Along any axis, if the shape indicated by `s` is smaller than that of
    the input, the input is cropped.  If it is larger, the input is padded
    with zeros. If `s` is not given, the shape of the input along the
    axes specified by `axes` is used.
axes : sequence of ints, optional
    Axes over which to compute the inverse FFT. If not given, the last
    `len(s)` axes are used, or all axes if `s` is also not specified.
    Repeated indices in `axes` means that the inverse transform over that
    axis is performed multiple times.

Returns
-------
out : ndarray
    The truncated or zero-padded input, transformed along the axes
    indicated by `axes`, or by a combination of `s` or `a`,
    as explained in the parameters section above.
    The length of each transformed axis is as given by the corresponding
    element of `s`, or the length of the input in every axis except for the
    last one if `s` is not given.  In the final transformed axis the length
    of the output when `s` is not given is ``2*(m-1)`` where ``m`` is the
    length of the final transformed axis of the input.  To get an odd
    number of output points in the final axis, `s` must be specified.

Raises
------
ValueError
    If `s` and `axes` have different length.
IndexError
    If an element of `axes` is larger than than the number of axes of `a`.

See Also
--------
rfftn : The forward n-dimensional FFT of real input,
        of which `ifftn` is the inverse.
fft : The one-dimensional FFT, with definitions and conventions used.
irfft : The inverse of the one-dimensional FFT of real input.
irfft2 : The inverse of the two-dimensional FFT of real input.

Notes
-----
See `fft` for definitions and conventions used.

See `rfft` for definitions and conventions used for real input.

Examples
--------
>>> a = np.zeros((3, 2, 2))
>>> a[0, 0, 0] = 3 * 2 * 2
>>> np.fft.irfftn(a)
array([[[ 1.,  1.],
        [ 1.,  1.]],
       [[ 1.,  1.],
        [ 1.,  1.]],
       [[ 1.,  1.],
        [ 1.,  1.]]])


a = asarray(a).astype(complex)<EOL>if n is None:<EOL><INDENT>n = shape(a)[axis]<EOL><DEDENT>return _raw_fft(a, n, axis, fftpack.cffti, fftpack.cfftb, _fft_cache) / n<EOL>

Compute the one-dimensional inverse discrete Fourier Transform.

This function computes the inverse of the one-dimensional *n*-point
discrete Fourier transform computed by `fft`.  In other words,
``ifft(fft(a)) == a`` to within numerical accuracy.
For a general description of the algorithm and definitions,
see `numpy.fft`.

The input should be ordered in the same way as is returned by `fft`,
i.e., ``a[0]`` should contain the zero frequency term,
``a[1:n/2+1]`` should contain the positive-frequency terms, and
``a[n/2+1:]`` should contain the negative-frequency terms, in order of
decreasingly negative frequency.  See `numpy.fft` for details.

Parameters
----------
a : array_like
    Input array, can be complex.
n : int, optional
    Length of the transformed axis of the output.
    If `n` is smaller than the length of the input, the input is cropped.
    If it is larger, the input is padded with zeros.  If `n` is not given,
    the length of the input along the axis specified by `axis` is used.
    See notes about padding issues.
axis : int, optional
    Axis over which to compute the inverse DFT.  If not given, the last
    axis is used.

Returns
-------
out : complex ndarray
    The truncated or zero-padded input, transformed along the axis
    indicated by `axis`, or the last one if `axis` is not specified.

Raises
------
IndexError
    If `axes` is larger than the last axis of `a`.

See Also
--------
numpy.fft : An introduction, with definitions and general explanations.
fft : The one-dimensional (forward) FFT, of which `ifft` is the inverse
ifft2 : The two-dimensional inverse FFT.
ifftn : The n-dimensional inverse FFT.

Notes
-----
If the input parameter `n` is larger than the size of the input, the input
is padded by appending zeros at the end.  Even though this is the common
approach, it might lead to surprising results.  If a different padding is
desired, it must be performed before calling `ifft`.

Examples
--------
>>> np.fft.ifft([0, 4, 0, 0])
array([ 1.+0.j,  0.+1.j, -1.+0.j,  0.-1.j])

Create and plot a band-limited signal with random phases:

>>> import matplotlib.pyplot as plt
>>> t = np.arange(400)
>>> n = np.zeros((400,), dtype=complex)
>>> n[40:60] = np.exp(1j*np.random.uniform(0, 2*np.pi, (20,)))
>>> s = np.fft.ifft(n)
>>> plt.plot(t, s.real, 'b-', t, s.imag, 'r--')
[<matplotlib.lines.Line2D object at 0x...>, <matplotlib.lines.Line2D object at 0x...>]
>>> plt.legend(('real', 'imaginary'))
<matplotlib.legend.Legend object at 0x...>
>>> plt.show()


x = _fix_real_lt_zero(x)<EOL>return nx.log(x)<EOL>

Compute the natural logarithm of `x`.

Return the "principal value" (for a description of this, see `numpy.log`)
of :math:`log_e(x)`. For real `x > 0`, this is a real number (``log(0)``
returns ``-inf`` and ``log(np.inf)`` returns ``inf``). Otherwise, the
complex principle value is returned.

Parameters
----------
x : array_like
   The value(s) whose log is (are) required.

Returns
-------
out : ndarray or scalar
   The log of the `x` value(s). If `x` was a scalar, so is `out`,
   otherwise an array is returned.

See Also
--------
numpy.log

Notes
-----
For a log() that returns ``NAN`` when real `x < 0`, use `numpy.log`
(note, however, that otherwise `numpy.log` and this `log` are identical,
i.e., both return ``-inf`` for `x = 0`, ``inf`` for `x = inf`, and,
notably, the complex principle value if ``x.imag != 0``).

Examples
--------
>>> np.emath.log(np.exp(1))
1.0

Negative arguments are handled "correctly" (recall that
``exp(log(x)) == x`` does *not* hold for real ``x < 0``):

>>> np.emath.log(-np.exp(1)) == (1 + np.pi * 1j)
True


x = asarray(x)<EOL>if any(isreal(x) & (abs(x) > <NUM_LIT:1>)):<EOL><INDENT>x = _tocomplex(x)<EOL><DEDENT>return x<EOL>

Convert `x` to complex if it has real components x_i with abs(x_i)>1.

    Otherwise, output is just the array version of the input (via asarray).

    Parameters
    ----------
    x : array_like

    Returns
    -------
    array

    Examples
    --------
    >>> np.lib.scimath._fix_real_abs_gt_1([0,1])
    array([0, 1])

    >>> np.lib.scimath._fix_real_abs_gt_1([0,2])
    array([ 0.+0.j,  2.+0.j])


x = _fix_real_abs_gt_1(x)<EOL>return nx.arcsin(x)<EOL>

Compute the inverse sine of x.

Return the "principal value" (for a description of this, see
`numpy.arcsin`) of the inverse sine of `x`. For real `x` such that
`abs(x) <= 1`, this is a real number in the closed interval
:math:`[-\\pi/2, \\pi/2]`.  Otherwise, the complex principle value is
returned.

Parameters
----------
x : array_like or scalar
   The value(s) whose arcsin is (are) required.

Returns
-------
out : ndarray or scalar
   The inverse sine(s) of the `x` value(s). If `x` was a scalar, so
   is `out`, otherwise an array object is returned.

See Also
--------
numpy.arcsin

Notes
-----
For an arcsin() that returns ``NAN`` when real `x` is not in the
interval ``[-1,1]``, use `numpy.arcsin`.

Examples
--------
>>> np.set_printoptions(precision=4)

>>> np.emath.arcsin(0)
0.0

>>> np.emath.arcsin([0,1])
array([ 0.    ,  1.5708])


x = _fix_real_lt_zero(x)<EOL>return nx.sqrt(x)<EOL>

Compute the square root of x.

For negative input elements, a complex value is returned
(unlike `numpy.sqrt` which returns NaN).

Parameters
----------
x : array_like
   The input value(s).

Returns
-------
out : ndarray or scalar
   The square root of `x`. If `x` was a scalar, so is `out`,
   otherwise an array is returned.

See Also
--------
numpy.sqrt

Examples
--------
For real, non-negative inputs this works just like `numpy.sqrt`:

>>> np.lib.scimath.sqrt(1)
1.0
>>> np.lib.scimath.sqrt([1, 4])
array([ 1.,  2.])

But it automatically handles negative inputs:

>>> np.lib.scimath.sqrt(-1)
(0.0+1.0j)
>>> np.lib.scimath.sqrt([-1,4])
array([ 0.+1.j,  2.+0.j])


x = _fix_real_lt_zero(x)<EOL>return nx.log10(x)<EOL>

Compute the logarithm base 10 of `x`.

Return the "principal value" (for a description of this, see
`numpy.log10`) of :math:`log_{10}(x)`. For real `x > 0`, this
is a real number (``log10(0)`` returns ``-inf`` and ``log10(np.inf)``
returns ``inf``). Otherwise, the complex principle value is returned.

Parameters
----------
x : array_like or scalar
   The value(s) whose log base 10 is (are) required.

Returns
-------
out : ndarray or scalar
   The log base 10 of the `x` value(s). If `x` was a scalar, so is `out`,
   otherwise an array object is returned.

See Also
--------
numpy.log10

Notes
-----
For a log10() that returns ``NAN`` when real `x < 0`, use `numpy.log10`
(note, however, that otherwise `numpy.log10` and this `log10` are
identical, i.e., both return ``-inf`` for `x = 0`, ``inf`` for `x = inf`,
and, notably, the complex principle value if ``x.imag != 0``).

Examples
--------

(We set the printing precision so the example can be auto-tested)

>>> np.set_printoptions(precision=4)

>>> np.emath.log10(10**1)
1.0

>>> np.emath.log10([-10**1, -10**2, 10**2])
array([ 1.+1.3644j,  2.+1.3644j,  2.+0.j    ])


x = asarray(x)<EOL>if any(isreal(x) & (x < <NUM_LIT:0>)):<EOL><INDENT>x = _tocomplex(x)<EOL><DEDENT>return x<EOL>

Convert `x` to complex if it has real, negative components.

    Otherwise, output is just the array version of the input (via asarray).

    Parameters
    ----------
    x : array_like

    Returns
    -------
    array

    Examples
    --------
    >>> np.lib.scimath._fix_real_lt_zero([1,2])
    array([1, 2])

    >>> np.lib.scimath._fix_real_lt_zero([-1,2])
    array([-1.+0.j,  2.+0.j])


x = _fix_real_lt_zero(x)<EOL>n = _fix_real_lt_zero(n)<EOL>return nx.log(x)/nx.log(n)<EOL>

Take log base n of x.

If `x` contains negative inputs, the answer is computed and returned in the
complex domain.

Parameters
----------
n : int
   The base in which the log is taken.
x : array_like
   The value(s) whose log base `n` is (are) required.

Returns
-------
out : ndarray or scalar
   The log base `n` of the `x` value(s). If `x` was a scalar, so is
   `out`, otherwise an array is returned.

Examples
--------
>>> np.set_printoptions(precision=4)

>>> np.lib.scimath.logn(2, [4, 8])
array([ 2.,  3.])
>>> np.lib.scimath.logn(2, [-4, -8, 8])
array([ 2.+4.5324j,  3.+4.5324j,  3.+0.j    ])


def __init__(self, baseurl, destpath=os.curdir):

DataSource.__init__(self, destpath=destpath)<EOL>self._baseurl = baseurl<EOL>

Create a Repository with a shared url or directory of baseurl.


last = None<EOL>path = os.path.normpath(path)<EOL>while path != last:<EOL><INDENT>last = path<EOL>path = path.lstrip(os.sep).lstrip('<STR_LIT:/>')<EOL>path = path.lstrip(os.pardir).lstrip('<STR_LIT:..>')<EOL>drive, path = os.path.splitdrive(path)  <EOL><DEDENT>return path<EOL>

Return a sanitised relative path for which
        os.path.abspath(os.path.join(base, path)).startswith(base)


splitpath = path.split(self._baseurl, <NUM_LIT:2>)<EOL>if len(splitpath) == <NUM_LIT:1>:<EOL><INDENT>result = os.path.join(self._baseurl, path)<EOL><DEDENT>else:<EOL><INDENT>result = path    <EOL><DEDENT>return result<EOL>

Return complete path for path.  Prepends baseurl if necessary.


return DataSource.abspath(self, self._fullpath(path))<EOL>

Return absolute path of file in the Repository directory.

If `path` is an URL, then `abspath` will return either the location
the file exists locally or the location it would exist when opened
using the `open` method.

Parameters
----------
path : str
    Can be a local file or a remote URL. This may, but does not
    have to, include the `baseurl` with which the `Repository` was
    initialized.

Returns
-------
out : str
    Complete path, including the `DataSource` destination directory.


<EOL>if not self._isurl(path):<EOL><INDENT>filelist = self._possible_names(path)<EOL>filelist += self._possible_names(self.abspath(path))<EOL><DEDENT>else:<EOL><INDENT>filelist = self._possible_names(self.abspath(path))<EOL>filelist = filelist + self._possible_names(path)<EOL><DEDENT>for name in filelist:<EOL><INDENT>if self.exists(name):<EOL><INDENT>if self._isurl(name):<EOL><INDENT>name = self._cache(name)<EOL><DEDENT>return name<EOL><DEDENT><DEDENT>return None<EOL>

Searches for ``path`` and returns full path if found.

        If path is an URL, _findfile will cache a local copy and return the
        path to the cached file.  If path is a local file, _findfile will
        return a path to that local file.

        The search will include possible compressed versions of the file
        and return the first occurence found.


<EOL>if sys.version_info[<NUM_LIT:0>] >= <NUM_LIT:3>:<EOL><INDENT>from urllib.parse import urlparse<EOL><DEDENT>else:<EOL><INDENT>from urlparse import urlparse<EOL><DEDENT>splitpath = path.split(self._destpath, <NUM_LIT:2>)<EOL>if len(splitpath) > <NUM_LIT:1>:<EOL><INDENT>path = splitpath[<NUM_LIT:1>]<EOL><DEDENT>scheme, netloc, upath, uparams, uquery, ufrag = urlparse(path)<EOL>netloc = self._sanitize_relative_path(netloc)<EOL>upath = self._sanitize_relative_path(upath)<EOL>return os.path.join(self._destpath, netloc, upath)<EOL>

Return absolute path of file in the DataSource directory.

If `path` is an URL, then `abspath` will return either the location
the file exists locally or the location it would exist when opened
using the `open` method.

Parameters
----------
path : str
    Can be a local file or a remote URL.

Returns
-------
out : str
    Complete path, including the `DataSource` destination directory.

Notes
-----
The functionality is based on `os.path.abspath`.


<EOL>_writemodes = ("<STR_LIT:w>", "<STR_LIT:+>")<EOL>for c in mode:<EOL><INDENT>if c in _writemodes:<EOL><INDENT>return True<EOL><DEDENT><DEDENT>return False<EOL>

Test if the given mode will open a file for writing.


<EOL>if sys.version_info[<NUM_LIT:0>] >= <NUM_LIT:3>:<EOL><INDENT>from urllib.request import urlopen<EOL>from urllib.error import URLError<EOL><DEDENT>else:<EOL><INDENT>from urllib2 import urlopen<EOL>from urllib2 import URLError<EOL><DEDENT>if os.path.exists(path):<EOL><INDENT>return True<EOL><DEDENT>upath = self.abspath(path)<EOL>if os.path.exists(upath):<EOL><INDENT>return True<EOL><DEDENT>if self._isurl(path):<EOL><INDENT>try:<EOL><INDENT>netfile = urlopen(path)<EOL>netfile.close()<EOL>del(netfile)<EOL>return True<EOL><DEDENT>except URLError:<EOL><INDENT>return False<EOL><DEDENT><DEDENT>return False<EOL>

Test if path exists.

Test if `path` exists as (and in this order):

- a local file.
- a remote URL that has been downloaded and stored locally in the
  `DataSource` directory.
- a remote URL that has not been downloaded, but is valid and
  accessible.

Parameters
----------
path : str
    Can be a local file or a remote URL.

Returns
-------
out : bool
    True if `path` exists.

Notes
-----
When `path` is an URL, `exists` will return True if it's either
stored locally in the `DataSource` directory, or is a valid remote
URL.  `DataSource` does not discriminate between the two, the file
is accessible if it exists in either location.


def roundtrip(self, save_func, *args, **kwargs):

save_kwds = kwargs.get('<STR_LIT>', {})<EOL>load_kwds = kwargs.get('<STR_LIT>', {})<EOL>file_on_disk = kwargs.get('<STR_LIT>', False)<EOL>if file_on_disk:<EOL><INDENT>target_file = NamedTemporaryFile(delete=False)<EOL>load_file = target_file.name<EOL><DEDENT>else:<EOL><INDENT>target_file = BytesIO()<EOL>load_file = target_file<EOL><DEDENT>try:<EOL><INDENT>arr = args<EOL>save_func(target_file, *arr, **save_kwds)<EOL>target_file.flush()<EOL>target_file.seek(<NUM_LIT:0>)<EOL>if sys.platform == '<STR_LIT:win32>' and not isinstance(target_file, BytesIO):<EOL><INDENT>target_file.close()<EOL><DEDENT>arr_reloaded = np.load(load_file, **load_kwds)<EOL>self.arr = arr<EOL>self.arr_reloaded = arr_reloaded<EOL><DEDENT>finally:<EOL><INDENT>if not isinstance(target_file, BytesIO):<EOL><INDENT>target_file.close()<EOL>if not isinstance(arr_reloaded, np.lib.npyio.NpzFile):<EOL><INDENT>os.remove(target_file.name)<EOL><DEDENT><DEDENT><DEDENT>

save_func : callable
    Function used to save arrays to file.
file_on_disk : bool
    If true, store the file on disk, instead of in a
    string buffer.
save_kwds : dict
    Parameters passed to `save_func`.
load_kwds : dict
    Parameters passed to `numpy.load`.
args : tuple of arrays
    Arrays stored to file.


next(self._it)<EOL>return self._it.multi_index<EOL>

Standard iterator method, updates the index and returns the index
tuple.

Returns
-------
val : tuple of ints
    Returns a tuple containing the indices of the current
    iteration.


if a.ndim < <NUM_LIT:2>:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>end = None<EOL>if a.ndim == <NUM_LIT:2>:<EOL><INDENT>step = a.shape[<NUM_LIT:1>] + <NUM_LIT:1><EOL>if not wrap:<EOL><INDENT>end = a.shape[<NUM_LIT:1>] * a.shape[<NUM_LIT:1>]<EOL><DEDENT><DEDENT>else:<EOL><INDENT>if not alltrue(diff(a.shape) == <NUM_LIT:0>):<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>step = <NUM_LIT:1> + (cumprod(a.shape[:-<NUM_LIT:1>])).sum()<EOL><DEDENT>a.flat[:end:step] = val<EOL>

Fill the main diagonal of the given array of any dimensionality.

    For an array `a` with ``a.ndim > 2``, the diagonal is the list of
    locations with indices ``a[i, i, ..., i]`` all identical. This function
    modifies the input array in-place, it does not return a value.

    Parameters
    ----------
    a : array, at least 2-D.
      Array whose diagonal is to be filled, it gets modified in-place.

    val : scalar
      Value to be written on the diagonal, its type must be compatible with
      that of the array a.

    wrap : bool
      For tall matrices in NumPy version up to 1.6.2, the
      diagonal "wrapped" after N columns. You can have this behavior
      with this option. This affect only tall matrices.

    See also
    --------
    diag_indices, diag_indices_from

    Notes
    -----
    .. versionadded:: 1.4.0

    This functionality can be obtained via `diag_indices`, but internally
    this version uses a much faster implementation that never constructs the
    indices and uses simple slicing.

    Examples
    --------
    >>> a = np.zeros((3, 3), int)
    >>> np.fill_diagonal(a, 5)
    >>> a
    array([[5, 0, 0],
           [0, 5, 0],
           [0, 0, 5]])

    The same function can operate on a 4-D array:

    >>> a = np.zeros((3, 3, 3, 3), int)
    >>> np.fill_diagonal(a, 4)

    We only show a few blocks for clarity:

    >>> a[0, 0]
    array([[4, 0, 0],
           [0, 0, 0],
           [0, 0, 0]])
    >>> a[1, 1]
    array([[0, 0, 0],
           [0, 4, 0],
           [0, 0, 0]])
    >>> a[2, 2]
    array([[0, 0, 0],
           [0, 0, 0],
           [0, 0, 4]])

    # tall matrices no wrap
    >>> a = np.zeros((5, 3),int)
    >>> fill_diagonal(a, 4)
    array([[4, 0, 0],
           [0, 4, 0],
           [0, 0, 4],
           [0, 0, 0],
           [0, 0, 0]])

    # tall matrices wrap
    >>> a = np.zeros((5, 3),int)
    >>> fill_diagonal(a, 4)
    array([[4, 0, 0],
           [0, 4, 0],
           [0, 0, 4],
           [0, 0, 0],
           [4, 0, 0]])

    # wide matrices
    >>> a = np.zeros((3, 5),int)
    >>> fill_diagonal(a, 4)
    array([[4, 0, 0, 0, 0],
           [0, 4, 0, 0, 0],
           [0, 0, 4, 0, 0]])


def _pad_sym(arr, pad_amt, method, axis=-<NUM_LIT:1>):

<EOL>if pad_amt[<NUM_LIT:0>] == <NUM_LIT:0> and pad_amt[<NUM_LIT:1>] == <NUM_LIT:0>:<EOL><INDENT>return arr<EOL><DEDENT>sym_slice = tuple(slice(None) if i != axis else slice(<NUM_LIT:0>, pad_amt[<NUM_LIT:0>])<EOL>for (i, x) in enumerate(arr.shape))<EOL>rev_idx = tuple(slice(None) if i != axis else slice(None, None, -<NUM_LIT:1>)<EOL>for (i, x) in enumerate(arr.shape))<EOL>sym_chunk1 = arr[sym_slice][rev_idx]<EOL>pad_singleton = tuple(x if i != axis else <NUM_LIT:1><EOL>for (i, x) in enumerate(arr.shape))<EOL>if pad_amt[<NUM_LIT:0>] == <NUM_LIT:1>:<EOL><INDENT>sym_chunk1 = sym_chunk1.reshape(pad_singleton)<EOL><DEDENT>if '<STR_LIT>' in method and pad_amt[<NUM_LIT:0>] > <NUM_LIT:0>:<EOL><INDENT>edge_slice1 = tuple(slice(None) if i != axis else <NUM_LIT:0><EOL>for (i, x) in enumerate(arr.shape))<EOL>edge_chunk = arr[edge_slice1].reshape(pad_singleton)<EOL>sym_chunk1 = <NUM_LIT:2> * edge_chunk - sym_chunk1<EOL>del edge_chunk<EOL><DEDENT>start = arr.shape[axis] - pad_amt[<NUM_LIT:1>]<EOL>end = arr.shape[axis]<EOL>sym_slice = tuple(slice(None) if i != axis else slice(start, end)<EOL>for (i, x) in enumerate(arr.shape))<EOL>sym_chunk2 = arr[sym_slice][rev_idx]<EOL>if pad_amt[<NUM_LIT:1>] == <NUM_LIT:1>:<EOL><INDENT>sym_chunk2 = sym_chunk2.reshape(pad_singleton)<EOL><DEDENT>if '<STR_LIT>' in method:<EOL><INDENT>edge_slice2 = tuple(slice(None) if i != axis else -<NUM_LIT:1><EOL>for (i, x) in enumerate(arr.shape))<EOL>edge_chunk = arr[edge_slice2].reshape(pad_singleton)<EOL>sym_chunk2 = <NUM_LIT:2> * edge_chunk - sym_chunk2<EOL>del edge_chunk<EOL><DEDENT>return np.concatenate((sym_chunk1, arr, sym_chunk2), axis=axis)<EOL>

Pad `axis` of `arr` by symmetry.

Parameters
----------
arr : ndarray
    Input array of arbitrary shape.
pad_amt : tuple of ints, length 2
    Padding to (prepend, append) along `axis`.
method : str
    Controls method of symmetry; options are 'even' or 'odd'.
axis : int
    Axis along which to pad `arr`.

Returns
-------
padarr : ndarray
    Output array, with `pad_amt[0]` values prepended and `pad_amt[1]`
    values appended along `axis`. Both regions are padded with symmetric
    values from the original array.

Notes
-----
This algorithm DOES pad with repetition, i.e. the edges are repeated.
For a method that does not repeat edges, use `method='reflect'`.

The modes 'reflect', 'symmetric', and 'wrap' must be padded with a
single function, lest the indexing tricks in non-integer multiples of the
original shape would violate repetition in the final iteration.


def _append_med(arr, pad_amt, num, axis=-<NUM_LIT:1>):

if pad_amt == <NUM_LIT:0>:<EOL><INDENT>return arr<EOL><DEDENT>if num == <NUM_LIT:1>:<EOL><INDENT>return _append_edge(arr, pad_amt, axis)<EOL><DEDENT>if num is not None:<EOL><INDENT>if num >= arr.shape[axis]:<EOL><INDENT>num = None<EOL><DEDENT><DEDENT>end = arr.shape[axis] - <NUM_LIT:1><EOL>if num is not None:<EOL><INDENT>med_slice = tuple(<EOL>slice(None) if i != axis else slice(end, end - num, -<NUM_LIT:1>)<EOL>for (i, x) in enumerate(arr.shape))<EOL><DEDENT>else:<EOL><INDENT>med_slice = tuple(slice(None) for x in arr.shape)<EOL><DEDENT>pad_singleton = tuple(x if i != axis else <NUM_LIT:1><EOL>for (i, x) in enumerate(arr.shape))<EOL>med_chunk = np.median(arr[med_slice], axis=axis).reshape(pad_singleton)<EOL>_round_ifneeded(med_chunk, arr.dtype)<EOL>return np.concatenate(<EOL>(arr, med_chunk.repeat(pad_amt, axis).astype(arr.dtype)), axis=axis)<EOL>

Append `pad_amt` median values along `axis`.

Parameters
----------
arr : ndarray
    Input array of arbitrary shape.
pad_amt : int
    Amount of padding to append.
num : int
    Depth into `arr` along `axis` to calculate median.
    Range: [1, `arr.shape[axis]`] or None (entire axis)
axis : int
    Axis along which to pad `arr`.

Returns
-------
padarr : ndarray
    Output array, with `pad_amt` values appended along `axis`. The
    appended region is the median of the final `num` values along `axis`.


def _prepend_mean(arr, pad_amt, num, axis=-<NUM_LIT:1>):

if pad_amt == <NUM_LIT:0>:<EOL><INDENT>return arr<EOL><DEDENT>if num == <NUM_LIT:1>:<EOL><INDENT>return _prepend_edge(arr, pad_amt, axis)<EOL><DEDENT>if num is not None:<EOL><INDENT>if num >= arr.shape[axis]:<EOL><INDENT>num = None<EOL><DEDENT><DEDENT>mean_slice = tuple(slice(None) if i != axis else slice(num)<EOL>for (i, x) in enumerate(arr.shape))<EOL>pad_singleton = tuple(x if i != axis else <NUM_LIT:1><EOL>for (i, x) in enumerate(arr.shape))<EOL>mean_chunk = arr[mean_slice].mean(axis).reshape(pad_singleton)<EOL>_round_ifneeded(mean_chunk, arr.dtype)<EOL>return np.concatenate((mean_chunk.repeat(pad_amt, axis).astype(arr.dtype),<EOL>arr), axis=axis)<EOL>

Prepend `pad_amt` mean values along `axis`.

Parameters
----------
arr : ndarray
    Input array of arbitrary shape.
pad_amt : int
    Amount of padding to prepend.
num : int
    Depth into `arr` along `axis` to calculate mean.
    Range: [1, `arr.shape[axis]`] or None (entire axis)
axis : int
    Axis along which to pad `arr`.

Returns
-------
padarr : ndarray
    Output array, with `pad_amt` values prepended along `axis`. The
    prepended region is the mean of the first `num` values along `axis`.


def _prepend_min(arr, pad_amt, num, axis=-<NUM_LIT:1>):

if pad_amt == <NUM_LIT:0>:<EOL><INDENT>return arr<EOL><DEDENT>if num == <NUM_LIT:1>:<EOL><INDENT>return _prepend_edge(arr, pad_amt, axis)<EOL><DEDENT>if num is not None:<EOL><INDENT>if num >= arr.shape[axis]:<EOL><INDENT>num = None<EOL><DEDENT><DEDENT>min_slice = tuple(slice(None) if i != axis else slice(num)<EOL>for (i, x) in enumerate(arr.shape))<EOL>pad_singleton = tuple(x if i != axis else <NUM_LIT:1><EOL>for (i, x) in enumerate(arr.shape))<EOL>min_chunk = arr[min_slice].min(axis=axis).reshape(pad_singleton)<EOL>return np.concatenate((min_chunk.repeat(pad_amt, axis=axis), arr),<EOL>axis=axis)<EOL>

Prepend `pad_amt` minimum values along `axis`.

Parameters
----------
arr : ndarray
    Input array of arbitrary shape.
pad_amt : int
    Amount of padding to prepend.
num : int
    Depth into `arr` along `axis` to calculate minimum.
    Range: [1, `arr.shape[axis]`] or None (entire axis)
axis : int
    Axis along which to pad `arr`.

Returns
-------
padarr : ndarray
    Output array, with `pad_amt` values prepended along `axis`. The
    prepended region is the minimum of the first `num` values along
    `axis`.


def _append_const(arr, pad_amt, val, axis=-<NUM_LIT:1>):

if pad_amt == <NUM_LIT:0>:<EOL><INDENT>return arr<EOL><DEDENT>padshape = tuple(x if i != axis else pad_amt<EOL>for (i, x) in enumerate(arr.shape))<EOL>if val == <NUM_LIT:0>:<EOL><INDENT>return np.concatenate((arr, np.zeros(padshape, dtype=arr.dtype)),<EOL>axis=axis)<EOL><DEDENT>else:<EOL><INDENT>return np.concatenate(<EOL>(arr, (np.zeros(padshape) + val).astype(arr.dtype)), axis=axis)<EOL><DEDENT>

Append constant `val` along `axis` of `arr`.

Parameters
----------
arr : ndarray
    Input array of arbitrary shape.
pad_amt : int
    Amount of padding to append.
val : scalar
    Constant value to use. For best results should be of type `arr.dtype`;
    if not `arr.dtype` will be cast to `arr.dtype`.
axis : int
    Axis along which to pad `arr`.

Returns
-------
padarr : ndarray
    Output array, with `pad_amt` constant `val` appended along `axis`.


if high <= i1.max and low >= i1.min:<EOL><INDENT>return int8<EOL><DEDENT>if high <= i2.max and low >= i2.min:<EOL><INDENT>return int16<EOL><DEDENT>if high <= i4.max and low >= i4.min:<EOL><INDENT>return int32<EOL><DEDENT>return int64<EOL>


v = asarray(v)<EOL>s = v.shape<EOL>if len(s) == <NUM_LIT:1>:<EOL><INDENT>n = s[<NUM_LIT:0>]+abs(k)<EOL>res = zeros((n, n), v.dtype)<EOL>if k >= <NUM_LIT:0>:<EOL><INDENT>i = k<EOL><DEDENT>else:<EOL><INDENT>i = (-k) * n<EOL><DEDENT>res[:n-k].flat[i::n+<NUM_LIT:1>] = v<EOL>return res<EOL><DEDENT>elif len(s) == <NUM_LIT:2>:<EOL><INDENT>return v.diagonal(k)<EOL><DEDENT>else:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>

Extract a diagonal or construct a diagonal array.

See the more detailed documentation for ``numpy.diagonal`` if you use this
function to extract a diagonal and wish to write to the resulting array;
whether it returns a copy or a view depends on what version of numpy you
are using.

Parameters
----------
v : array_like
    If `v` is a 2-D array, return a copy of its `k`-th diagonal.
    If `v` is a 1-D array, return a 2-D array with `v` on the `k`-th
    diagonal.
k : int, optional
    Diagonal in question. The default is 0. Use `k>0` for diagonals
    above the main diagonal, and `k<0` for diagonals below the main
    diagonal.

Returns
-------
out : ndarray
    The extracted diagonal or constructed diagonal array.

See Also
--------
diagonal : Return specified diagonals.
diagflat : Create a 2-D array with the flattened input as a diagonal.
trace : Sum along diagonals.
triu : Upper triangle of an array.
tril : Lower triangle of an array.

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

>>> np.diag(x)
array([0, 4, 8])
>>> np.diag(x, k=1)
array([1, 5])
>>> np.diag(x, k=-1)
array([3, 7])

>>> np.diag(np.diag(x))
array([[0, 0, 0],
       [0, 4, 0],
       [0, 0, 8]])


def vander(x, N=None, increasing=False):

x = asarray(x)<EOL>if x.ndim != <NUM_LIT:1>:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if N is None:<EOL><INDENT>N = len(x)<EOL><DEDENT>v = empty((len(x), N), dtype=promote_types(x.dtype, int))<EOL>tmp = v[:, ::-<NUM_LIT:1>] if not increasing else v<EOL>if N > <NUM_LIT:0>:<EOL><INDENT>tmp[:, <NUM_LIT:0>] = <NUM_LIT:1><EOL><DEDENT>if N > <NUM_LIT:1>:<EOL><INDENT>tmp[:, <NUM_LIT:1>:] = x[:, None]<EOL>multiply.accumulate(tmp[:, <NUM_LIT:1>:], out=tmp[:, <NUM_LIT:1>:], axis=<NUM_LIT:1>)<EOL><DEDENT>return v<EOL>

Generate a Vandermonde matrix.

The columns of the output matrix are powers of the input vector. The
order of the powers is determined by the `increasing` boolean argument.
Specifically, when `increasing` is False, the `i`-th output column is
the input vector raised element-wise to the power of ``N - i - 1``. Such
a matrix with a geometric progression in each row is named for Alexandre-
Theophile Vandermonde.

Parameters
----------
x : array_like
    1-D input array.
N : int, optional
    Number of columns in the output.  If `N` is not specified, a square
    array is returned (``N = len(x)``).
increasing : bool, optional
    Order of the powers of the columns.  If True, the powers increase
    from left to right, if False (the default) they are reversed.

    .. versionadded:: 1.9.0

Returns
-------
out : ndarray
    Vandermonde matrix.  If `increasing` is False, the first column is
    ``x^(N-1)``, the second ``x^(N-2)`` and so forth. If `increasing` is
    True, the columns are ``x^0, x^1, ..., x^(N-1)``.

See Also
--------
polynomial.polynomial.polyvander

Examples
--------
>>> x = np.array([1, 2, 3, 5])
>>> N = 3
>>> np.vander(x, N)
array([[ 1,  1,  1],
       [ 4,  2,  1],
       [ 9,  3,  1],
       [25,  5,  1]])

>>> np.column_stack([x**(N-1-i) for i in range(N)])
array([[ 1,  1,  1],
       [ 4,  2,  1],
       [ 9,  3,  1],
       [25,  5,  1]])

>>> x = np.array([1, 2, 3, 5])
>>> np.vander(x)
array([[  1,   1,   1,   1],
       [  8,   4,   2,   1],
       [ 27,   9,   3,   1],
       [125,  25,   5,   1]])
>>> np.vander(x, increasing=True)
array([[  1,   1,   1,   1],
       [  1,   2,   4,   8],
       [  1,   3,   9,  27],
       [  1,   5,  25, 125]])

The determinant of a square Vandermonde matrix is the product
of the differences between the values of the input vector:

>>> np.linalg.det(np.vander(x))
48.000000000000043
>>> (5-3)*(5-2)*(5-1)*(3-2)*(3-1)*(2-1)
48


m = asanyarray(m)<EOL>mask = tri(*m.shape[-<NUM_LIT:2>:], k=k-<NUM_LIT:1>, dtype=bool)<EOL>return where(mask, zeros(<NUM_LIT:1>, m.dtype), m)<EOL>

Upper triangle of an array.

Return a copy of a matrix with the elements below the `k`-th diagonal
zeroed.

Please refer to the documentation for `tril` for further details.

See Also
--------
tril : lower triangle of an array

Examples
--------
>>> np.triu([[1,2,3],[4,5,6],[7,8,9],[10,11,12]], -1)
array([[ 1,  2,  3],
       [ 4,  5,  6],
       [ 0,  8,  9],
       [ 0,  0, 12]])


def as_strided(x, shape=None, strides=None):

interface = dict(x.__array_interface__)<EOL>if shape is not None:<EOL><INDENT>interface['<STR_LIT>'] = tuple(shape)<EOL><DEDENT>if strides is not None:<EOL><INDENT>interface['<STR_LIT>'] = tuple(strides)<EOL><DEDENT>array = np.asarray(DummyArray(interface, base=x))<EOL>if array.dtype.kind == '<STR_LIT>':<EOL><INDENT>array.dtype = x.dtype<EOL><DEDENT>return array<EOL>

Make an ndarray from the given array with the given shape and strides.


return np.array(val).dtype<EOL>

Returns the dtype of the input variable.


return np.array(val).dtype.type<EOL>

Returns the type of the dtype of the input variable.


values = np.asarray(values)<EOL>return (values / (<NUM_LIT:1>+rate)**np.arange(<NUM_LIT:0>, len(values))).sum(axis=<NUM_LIT:0>)<EOL>

Returns the NPV (Net Present Value) of a cash flow series.

Parameters
----------
rate : scalar
    The discount rate.
values : array_like, shape(M, )
    The values of the time series of cash flows.  The (fixed) time
    interval between cash flow "events" must be the same as that for
    which `rate` is given (i.e., if `rate` is per year, then precisely
    a year is understood to elapse between each cash flow event).  By
    convention, investments or "deposits" are negative, income or
    "withdrawals" are positive; `values` must begin with the initial
    investment, thus `values[0]` will typically be negative.

Returns
-------
out : float
    The NPV of the input cash flow series `values` at the discount
    `rate`.

Notes
-----
Returns the result of: [G]_

.. math :: \\sum_{t=0}^{M-1}{\\frac{values_t}{(1+rate)^{t}}}

References
----------
.. [G] L. J. Gitman, "Principles of Managerial Finance, Brief," 3rd ed.,
   Addison-Wesley, 2003, pg. 346.

Examples
--------
>>> np.npv(0.281,[-100, 39, 59, 55, 20])
-0.0084785916384548798

(Compare with the Example given for numpy.lib.financial.irr)


def rate(nper, pmt, pv, fv, when='<STR_LIT:end>', guess=<NUM_LIT>, tol=<NUM_LIT>, maxiter=<NUM_LIT:100>):

when = _convert_when(when)<EOL>(nper, pmt, pv, fv, when) = map(np.asarray, [nper, pmt, pv, fv, when])<EOL>rn = guess<EOL>iter = <NUM_LIT:0><EOL>close = False<EOL>while (iter < maxiter) and not close:<EOL><INDENT>rnp1 = rn - _g_div_gp(rn, nper, pmt, pv, fv, when)<EOL>diff = abs(rnp1-rn)<EOL>close = np.all(diff < tol)<EOL>iter += <NUM_LIT:1><EOL>rn = rnp1<EOL><DEDENT>if not close:<EOL><INDENT>return np.nan + rn<EOL><DEDENT>else:<EOL><INDENT>return rn<EOL><DEDENT>

Compute the rate of interest per period.

Parameters
----------
nper : array_like
    Number of compounding periods
pmt : array_like
    Payment
pv : array_like
    Present value
fv : array_like
    Future value
when : {{'begin', 1}, {'end', 0}}, {string, int}, optional
    When payments are due ('begin' (1) or 'end' (0))
guess : float, optional
    Starting guess for solving the rate of interest
tol : float, optional
    Required tolerance for the solution
maxiter : int, optional
    Maximum iterations in finding the solution

Notes
-----
The rate of interest is computed by iteratively solving the
(non-linear) equation::

 fv + pv*(1+rate)**nper + pmt*(1+rate*when)/rate * ((1+rate)**nper - 1) = 0

for ``rate``.

References
----------
Wheeler, D. A., E. Rathke, and R. Weir (Eds.) (2009, May). Open Document
Format for Office Applications (OpenDocument)v1.2, Part 2: Recalculated
Formula (OpenFormula) Format - Annotated Version, Pre-Draft 12.
Organization for the Advancement of Structured Information Standards
(OASIS). Billerica, MA, USA. [ODT Document]. Available:
http://www.oasis-open.org/committees/documents.php?wg_abbrev=office-formula
OpenDocument-formula-20090508.odt


if self.pre_release == other.pre_release:<EOL><INDENT>vercmp = <NUM_LIT:0><EOL><DEDENT>elif self.pre_release == '<STR_LIT>':<EOL><INDENT>vercmp = <NUM_LIT:1><EOL><DEDENT>elif other.pre_release == '<STR_LIT>':<EOL><INDENT>vercmp = -<NUM_LIT:1><EOL><DEDENT>elif self.pre_release > other.pre_release:<EOL><INDENT>vercmp = <NUM_LIT:1><EOL><DEDENT>else:<EOL><INDENT>vercmp = -<NUM_LIT:1><EOL><DEDENT>return vercmp<EOL>


if self.zip is not None:<EOL><INDENT>self.zip.close()<EOL>self.zip = None<EOL><DEDENT>if self.fid is not None:<EOL><INDENT>self.fid.close()<EOL>self.fid = None<EOL><DEDENT>self.f = None<EOL>


<EOL>kwargs.setdefault("<STR_LIT>", "<STR_LIT>")<EOL>kwargs.setdefault("<STR_LIT>", True)<EOL>kwargs.setdefault("<STR_LIT>", "<STR_LIT:U+002C>")<EOL>kwargs.setdefault("<STR_LIT>", None)<EOL>output = genfromtxt(fname, **kwargs)<EOL>usemask = kwargs.get("<STR_LIT>", False)<EOL>if usemask:<EOL><INDENT>from numpy.ma.mrecords import MaskedRecords<EOL>output = output.view(MaskedRecords)<EOL><DEDENT>else:<EOL><INDENT>output = output.view(np.recarray)<EOL><DEDENT>return output<EOL>

Load ASCII data stored in a comma-separated file.

The returned array is a record array (if ``usemask=False``, see
`recarray`) or a masked record array (if ``usemask=True``,
see `ma.mrecords.MaskedRecords`).

Parameters
----------
fname, kwargs : For a description of input parameters, see `genfromtxt`.

See Also
--------
numpy.genfromtxt : generic function to load ASCII data.

Notes
-----
By default, `dtype` is None, which means that the data-type of the output
array will be determined from the data.