def _pad_ref(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>ref_slice = tuple(slice(None) if i != axis else slice(pad_amt[<NUM_LIT:0>], <NUM_LIT:0>, -<NUM_LIT:1>)<EOL>for (i, x) in enumerate(arr.shape))<EOL>ref_chunk1 = arr[ref_slice]<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>ref_chunk1 = ref_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>ref_chunk1 = <NUM_LIT:2> * edge_chunk - ref_chunk1<EOL>del edge_chunk<EOL><DEDENT>start = arr.shape[axis] - pad_amt[<NUM_LIT:1>] - <NUM_LIT:1><EOL>end = arr.shape[axis] - <NUM_LIT:1><EOL>ref_slice = tuple(slice(None) if i != axis else slice(start, end)<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>ref_chunk2 = arr[ref_slice][rev_idx]<EOL>if pad_amt[<NUM_LIT:1>] == <NUM_LIT:1>:<EOL><INDENT>ref_chunk2 = ref_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>ref_chunk2 = <NUM_LIT:2> * edge_chunk - ref_chunk2<EOL>del edge_chunk<EOL><DEDENT>return np.concatenate((ref_chunk1, arr, ref_chunk2), axis=axis)<EOL>

Pad `axis` of `arr` by reflection.

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 reflection; 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 reflected
    values from the original array.

Notes
-----
This algorithm does not pad with repetition, i.e. the edges are not
repeated in the reflection. For that behavior, use `method='symmetric'`.

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 _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 _pad_wrap(arr, pad_amt, 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>start = arr.shape[axis] - pad_amt[<NUM_LIT:0>]<EOL>end = arr.shape[axis]<EOL>wrap_slice = tuple(slice(None) if i != axis else slice(start, end)<EOL>for (i, x) in enumerate(arr.shape))<EOL>wrap_chunk1 = arr[wrap_slice]<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>wrap_chunk1 = wrap_chunk1.reshape(pad_singleton)<EOL><DEDENT>wrap_slice = tuple(slice(None) if i != axis else slice(<NUM_LIT:0>, pad_amt[<NUM_LIT:1>])<EOL>for (i, x) in enumerate(arr.shape))<EOL>wrap_chunk2 = arr[wrap_slice]<EOL>if pad_amt[<NUM_LIT:1>] == <NUM_LIT:1>:<EOL><INDENT>wrap_chunk2 = wrap_chunk2.reshape(pad_singleton)<EOL><DEDENT>return np.concatenate((wrap_chunk1, arr, wrap_chunk2), axis=axis)<EOL>

Pad `axis` of `arr` via wrapping.

Parameters
----------
arr : ndarray
    Input array of arbitrary shape.
pad_amt : tuple of ints, length 2
    Padding to (prepend, append) along `axis`.
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 wrapped values
    from the opposite end of `axis`.

Notes
-----
This method of padding is also known as 'tile' or 'tiling'.

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.


normshp = None<EOL>shapelen = len(np.shape(narray))<EOL>if (isinstance(shape, int)) or shape is None:<EOL><INDENT>normshp = ((shape, shape), ) * shapelen<EOL><DEDENT>elif (isinstance(shape, (tuple, list))<EOL>and isinstance(shape[<NUM_LIT:0>], (tuple, list))<EOL>and len(shape) == shapelen):<EOL><INDENT>normshp = shape<EOL>for i in normshp:<EOL><INDENT>if len(i) != <NUM_LIT:2>:<EOL><INDENT>fmt = "<STR_LIT>"<EOL>raise ValueError(fmt % (normshp,))<EOL><DEDENT><DEDENT><DEDENT>elif (isinstance(shape, (tuple, list))<EOL>and isinstance(shape[<NUM_LIT:0>], (int, float, long))<EOL>and len(shape) == <NUM_LIT:1>):<EOL><INDENT>normshp = ((shape[<NUM_LIT:0>], shape[<NUM_LIT:0>]), ) * shapelen<EOL><DEDENT>elif (isinstance(shape, (tuple, list))<EOL>and isinstance(shape[<NUM_LIT:0>], (int, float, long))<EOL>and len(shape) == <NUM_LIT:2>):<EOL><INDENT>normshp = (shape, ) * shapelen<EOL><DEDENT>if normshp is None:<EOL><INDENT>fmt = "<STR_LIT>"<EOL>raise ValueError(fmt % (shape,))<EOL><DEDENT>return normshp<EOL>

Private function which does some checks and normalizes the possibly
much simpler representations of 'pad_width', 'stat_length',
'constant_values', 'end_values'.

Parameters
----------
narray : ndarray
    Input ndarray
shape : {sequence, int}, optional
    The width of padding (pad_width) or the number of elements on the
    edge of the narray used for statistics (stat_length).
    ((before_1, after_1), ... (before_N, after_N)) unique number of
    elements for each axis where `N` is rank of `narray`.
    ((before, after),) yields same before and after constants for each
    axis.
    (constant,) or int is a shortcut for before = after = constant for
    all axes.

Returns
-------
_normalize_shape : tuple of tuples
    int                               => ((int, int), (int, int), ...)
    [[int1, int2], [int3, int4], ...] => ((int1, int2), (int3, int4), ...)
    ((int1, int2), (int3, int4), ...) => no change
    [[int1, int2], ]                  => ((int1, int2), (int1, int2), ...)
    ((int1, int2), )                  => ((int1, int2), (int1, int2), ...)
    [[int ,     ], ]                  => ((int, int), (int, int), ...)
    ((int ,     ), )                  => ((int, int), (int, int), ...)


normshp = _normalize_shape(narray, number_elements)<EOL>for i in normshp:<EOL><INDENT>chk = [<NUM_LIT:1> if x is None else x for x in i]<EOL>chk = [<NUM_LIT:1> if x >= <NUM_LIT:0> else -<NUM_LIT:1> for x in chk]<EOL>if (chk[<NUM_LIT:0>] < <NUM_LIT:0>) or (chk[<NUM_LIT:1>] < <NUM_LIT:0>):<EOL><INDENT>fmt = "<STR_LIT>"<EOL>raise ValueError(fmt % (number_elements,))<EOL><DEDENT><DEDENT>return normshp<EOL>

Private function which does some checks and reformats pad_width and
stat_length using _normalize_shape.

Parameters
----------
narray : ndarray
    Input ndarray
number_elements : {sequence, int}, optional
    The width of padding (pad_width) or the number of elements on the edge
    of the narray used for statistics (stat_length).
    ((before_1, after_1), ... (before_N, after_N)) unique number of
    elements for each axis.
    ((before, after),) yields same before and after constants for each
    axis.
    (constant,) or int is a shortcut for before = after = constant for all
    axes.

Returns
-------
_validate_lengths : tuple of tuples
    int                               => ((int, int), (int, int), ...)
    [[int1, int2], [int3, int4], ...] => ((int1, int2), (int3, int4), ...)
    ((int1, int2), (int3, int4), ...) => no change
    [[int1, int2], ]                  => ((int1, int2), (int1, int2), ...)
    ((int1, int2), )                  => ((int1, int2), (int1, int2), ...)
    [[int ,     ], ]                  => ((int, int), (int, int), ...)
    ((int ,     ), )                  => ((int, int), (int, int), ...)


def pad(array, pad_width, mode=None, **kwargs):

narray = np.array(array)<EOL>pad_width = _validate_lengths(narray, pad_width)<EOL>allowedkwargs = {<EOL>'<STR_LIT>': ['<STR_LIT>'],<EOL>'<STR_LIT>': [],<EOL>'<STR_LIT>': ['<STR_LIT>'],<EOL>'<STR_LIT>': ['<STR_LIT>'],<EOL>'<STR_LIT>': ['<STR_LIT>'],<EOL>'<STR_LIT>': ['<STR_LIT>'],<EOL>'<STR_LIT>': ['<STR_LIT>'],<EOL>'<STR_LIT>': ['<STR_LIT>'],<EOL>'<STR_LIT>': ['<STR_LIT>'],<EOL>'<STR_LIT>': [],<EOL>}<EOL>kwdefaults = {<EOL>'<STR_LIT>': None,<EOL>'<STR_LIT>': <NUM_LIT:0>,<EOL>'<STR_LIT>': <NUM_LIT:0>,<EOL>'<STR_LIT>': '<STR_LIT>',<EOL>}<EOL>if isinstance(mode, str):<EOL><INDENT>for key in kwargs:<EOL><INDENT>if key not in allowedkwargs[mode]:<EOL><INDENT>raise ValueError('<STR_LIT>' %<EOL>(key, allowedkwargs[mode]))<EOL><DEDENT><DEDENT>for kw in allowedkwargs[mode]:<EOL><INDENT>kwargs.setdefault(kw, kwdefaults[kw])<EOL><DEDENT>for i in kwargs:<EOL><INDENT>if i == '<STR_LIT>':<EOL><INDENT>kwargs[i] = _validate_lengths(narray, kwargs[i])<EOL><DEDENT>if i in ['<STR_LIT>', '<STR_LIT>']:<EOL><INDENT>kwargs[i] = _normalize_shape(narray, kwargs[i])<EOL><DEDENT><DEDENT><DEDENT>elif mode is None:<EOL><INDENT>raise ValueError('<STR_LIT>' %<EOL>(list(allowedkwargs.keys()),))<EOL><DEDENT>else:<EOL><INDENT>function = mode<EOL>rank = list(range(len(narray.shape)))<EOL>total_dim_increase = [np.sum(pad_width[i]) for i in rank]<EOL>offset_slices = [slice(pad_width[i][<NUM_LIT:0>],<EOL>pad_width[i][<NUM_LIT:0>] + narray.shape[i])<EOL>for i in rank]<EOL>new_shape = np.array(narray.shape) + total_dim_increase<EOL>newmat = np.zeros(new_shape, narray.dtype)<EOL>newmat[offset_slices] = narray<EOL>for iaxis in rank:<EOL><INDENT>np.apply_along_axis(function,<EOL>iaxis,<EOL>newmat,<EOL>pad_width[iaxis],<EOL>iaxis,<EOL>kwargs)<EOL><DEDENT>return newmat<EOL><DEDENT>newmat = narray.copy()<EOL>if mode == '<STR_LIT>':<EOL><INDENT>for axis, ((pad_before, pad_after), (before_val, after_val))in enumerate(zip(pad_width, kwargs['<STR_LIT>'])):<EOL><INDENT>newmat = _prepend_const(newmat, pad_before, before_val, axis)<EOL>newmat = _append_const(newmat, pad_after, after_val, axis)<EOL><DEDENT><DEDENT>elif mode == '<STR_LIT>':<EOL><INDENT>for axis, (pad_before, pad_after) in enumerate(pad_width):<EOL><INDENT>newmat = _prepend_edge(newmat, pad_before, axis)<EOL>newmat = _append_edge(newmat, pad_after, axis)<EOL><DEDENT><DEDENT>elif mode == '<STR_LIT>':<EOL><INDENT>for axis, ((pad_before, pad_after), (before_val, after_val))in enumerate(zip(pad_width, kwargs['<STR_LIT>'])):<EOL><INDENT>newmat = _prepend_ramp(newmat, pad_before, before_val, axis)<EOL>newmat = _append_ramp(newmat, pad_after, after_val, axis)<EOL><DEDENT><DEDENT>elif mode == '<STR_LIT>':<EOL><INDENT>for axis, ((pad_before, pad_after), (chunk_before, chunk_after))in enumerate(zip(pad_width, kwargs['<STR_LIT>'])):<EOL><INDENT>newmat = _prepend_max(newmat, pad_before, chunk_before, axis)<EOL>newmat = _append_max(newmat, pad_after, chunk_after, axis)<EOL><DEDENT><DEDENT>elif mode == '<STR_LIT>':<EOL><INDENT>for axis, ((pad_before, pad_after), (chunk_before, chunk_after))in enumerate(zip(pad_width, kwargs['<STR_LIT>'])):<EOL><INDENT>newmat = _prepend_mean(newmat, pad_before, chunk_before, axis)<EOL>newmat = _append_mean(newmat, pad_after, chunk_after, axis)<EOL><DEDENT><DEDENT>elif mode == '<STR_LIT>':<EOL><INDENT>for axis, ((pad_before, pad_after), (chunk_before, chunk_after))in enumerate(zip(pad_width, kwargs['<STR_LIT>'])):<EOL><INDENT>newmat = _prepend_med(newmat, pad_before, chunk_before, axis)<EOL>newmat = _append_med(newmat, pad_after, chunk_after, axis)<EOL><DEDENT><DEDENT>elif mode == '<STR_LIT>':<EOL><INDENT>for axis, ((pad_before, pad_after), (chunk_before, chunk_after))in enumerate(zip(pad_width, kwargs['<STR_LIT>'])):<EOL><INDENT>newmat = _prepend_min(newmat, pad_before, chunk_before, axis)<EOL>newmat = _append_min(newmat, pad_after, chunk_after, axis)<EOL><DEDENT><DEDENT>elif mode == '<STR_LIT>':<EOL><INDENT>for axis, (pad_before, pad_after) in enumerate(pad_width):<EOL><INDENT>if ((pad_before > <NUM_LIT:0>) or<EOL>(pad_after > <NUM_LIT:0>)) and newmat.shape[axis] == <NUM_LIT:1>:<EOL><INDENT>newmat = _prepend_edge(newmat, pad_before, axis)<EOL>newmat = _append_edge(newmat, pad_after, axis)<EOL>continue<EOL><DEDENT>method = kwargs['<STR_LIT>']<EOL>safe_pad = newmat.shape[axis] - <NUM_LIT:1><EOL>while ((pad_before > safe_pad) or (pad_after > safe_pad)):<EOL><INDENT>offset = <NUM_LIT:0><EOL>pad_iter_b = min(safe_pad,<EOL>safe_pad * (pad_before // safe_pad))<EOL>pad_iter_a = min(safe_pad, safe_pad * (pad_after // safe_pad))<EOL>newmat = _pad_ref(newmat, (pad_iter_b,<EOL>pad_iter_a), method, axis)<EOL>pad_before -= pad_iter_b<EOL>pad_after -= pad_iter_a<EOL>if pad_iter_b > <NUM_LIT:0>:<EOL><INDENT>offset += <NUM_LIT:1><EOL><DEDENT>if pad_iter_a > <NUM_LIT:0>:<EOL><INDENT>offset += <NUM_LIT:1><EOL><DEDENT>safe_pad += pad_iter_b + pad_iter_a<EOL><DEDENT>newmat = _pad_ref(newmat, (pad_before, pad_after), method, axis)<EOL><DEDENT><DEDENT>elif mode == '<STR_LIT>':<EOL><INDENT>for axis, (pad_before, pad_after) in enumerate(pad_width):<EOL><INDENT>method = kwargs['<STR_LIT>']<EOL>safe_pad = newmat.shape[axis]<EOL>while ((pad_before > safe_pad) or<EOL>(pad_after > safe_pad)):<EOL><INDENT>pad_iter_b = min(safe_pad,<EOL>safe_pad * (pad_before // safe_pad))<EOL>pad_iter_a = min(safe_pad, safe_pad * (pad_after // safe_pad))<EOL>newmat = _pad_sym(newmat, (pad_iter_b,<EOL>pad_iter_a), method, axis)<EOL>pad_before -= pad_iter_b<EOL>pad_after -= pad_iter_a<EOL>safe_pad += pad_iter_b + pad_iter_a<EOL><DEDENT>newmat = _pad_sym(newmat, (pad_before, pad_after), method, axis)<EOL><DEDENT><DEDENT>elif mode == '<STR_LIT>':<EOL><INDENT>for axis, (pad_before, pad_after) in enumerate(pad_width):<EOL><INDENT>safe_pad = newmat.shape[axis]<EOL>while ((pad_before > safe_pad) or<EOL>(pad_after > safe_pad)):<EOL><INDENT>pad_iter_b = min(safe_pad,<EOL>safe_pad * (pad_before // safe_pad))<EOL>pad_iter_a = min(safe_pad, safe_pad * (pad_after // safe_pad))<EOL>newmat = _pad_wrap(newmat, (pad_iter_b, pad_iter_a), axis)<EOL>pad_before -= pad_iter_b<EOL>pad_after -= pad_iter_a<EOL>safe_pad += pad_iter_b + pad_iter_a<EOL><DEDENT>newmat = _pad_wrap(newmat, (pad_before, pad_after), axis)<EOL><DEDENT><DEDENT>return newmat<EOL>

Pads an array.

Parameters
----------
array : array_like of rank N
    Input array
pad_width : {sequence, int}
    Number of values padded to the edges of each axis.
    ((before_1, after_1), ... (before_N, after_N)) unique pad widths
    for each axis.
    ((before, after),) yields same before and after pad for each axis.
    (pad,) or int is a shortcut for before = after = pad width for all
    axes.
mode : {str, function}
    One of the following string values or a user supplied function.

    'constant'
        Pads with a constant value.
    'edge'
        Pads with the edge values of array.
    'linear_ramp'
        Pads with the linear ramp between end_value and the
        array edge value.
    'maximum'
        Pads with the maximum value of all or part of the
        vector along each axis.
    'mean'
        Pads with the mean value of all or part of the
        vector along each axis.
    'median'
        Pads with the median value of all or part of the
        vector along each axis.
    'minimum'
        Pads with the minimum value of all or part of the
        vector along each axis.
    'reflect'
        Pads with the reflection of the vector mirrored on
        the first and last values of the vector along each
        axis.
    'symmetric'
        Pads with the reflection of the vector mirrored
        along the edge of the array.
    'wrap'
        Pads with the wrap of the vector along the axis.
        The first values are used to pad the end and the
        end values are used to pad the beginning.
    <function>
        Padding function, see Notes.
stat_length : {sequence, int}, optional
    Used in 'maximum', 'mean', 'median', and 'minimum'.  Number of
    values at edge of each axis used to calculate the statistic value.

    ((before_1, after_1), ... (before_N, after_N)) unique statistic
    lengths for each axis.

    ((before, after),) yields same before and after statistic lengths
    for each axis.

    (stat_length,) or int is a shortcut for before = after = statistic
    length for all axes.

    Default is ``None``, to use the entire axis.
constant_values : {sequence, int}, optional
    Used in 'constant'.  The values to set the padded values for each
    axis.

    ((before_1, after_1), ... (before_N, after_N)) unique pad constants
    for each axis.

    ((before, after),) yields same before and after constants for each
    axis.

    (constant,) or int is a shortcut for before = after = constant for
    all axes.

    Default is 0.
end_values : {sequence, int}, optional
    Used in 'linear_ramp'.  The values used for the ending value of the
    linear_ramp and that will form the edge of the padded array.

    ((before_1, after_1), ... (before_N, after_N)) unique end values
    for each axis.

    ((before, after),) yields same before and after end values for each
    axis.

    (constant,) or int is a shortcut for before = after = end value for
    all axes.

    Default is 0.
reflect_type : str {'even', 'odd'}, optional
    Used in 'reflect', and 'symmetric'.  The 'even' style is the
    default with an unaltered reflection around the edge value.  For
    the 'odd' style, the extented part of the array is created by
    subtracting the reflected values from two times the edge value.

Returns
-------
pad : ndarray
    Padded array of rank equal to `array` with shape increased
    according to `pad_width`.

Notes
-----
.. versionadded:: 1.7.0

For an array with rank greater than 1, some of the padding of later
axes is calculated from padding of previous axes.  This is easiest to
think about with a rank 2 array where the corners of the padded array
are calculated by using padded values from the first axis.

The padding function, if used, should return a rank 1 array equal in
length to the vector argument with padded values replaced. It has the
following signature::

    padding_func(vector, iaxis_pad_width, iaxis, **kwargs)

where

    vector : ndarray
        A rank 1 array already padded with zeros.  Padded values are
        vector[:pad_tuple[0]] and vector[-pad_tuple[1]:].
    iaxis_pad_width : tuple
        A 2-tuple of ints, iaxis_pad_width[0] represents the number of
        values padded at the beginning of vector where
        iaxis_pad_width[1] represents the number of values padded at
        the end of vector.
    iaxis : int
        The axis currently being calculated.
    kwargs : misc
        Any keyword arguments the function requires.

Examples
--------
>>> a = [1, 2, 3, 4, 5]
>>> np.lib.pad(a, (2,3), 'constant', constant_values=(4,6))
array([4, 4, 1, 2, 3, 4, 5, 6, 6, 6])

>>> np.lib.pad(a, (2,3), 'edge')
array([1, 1, 1, 2, 3, 4, 5, 5, 5, 5])

>>> np.lib.pad(a, (2,3), 'linear_ramp', end_values=(5,-4))
array([ 5,  3,  1,  2,  3,  4,  5,  2, -1, -4])

>>> np.lib.pad(a, (2,), 'maximum')
array([5, 5, 1, 2, 3, 4, 5, 5, 5])

>>> np.lib.pad(a, (2,), 'mean')
array([3, 3, 1, 2, 3, 4, 5, 3, 3])

>>> np.lib.pad(a, (2,), 'median')
array([3, 3, 1, 2, 3, 4, 5, 3, 3])

>>> a = [[1,2], [3,4]]
>>> np.lib.pad(a, ((3, 2), (2, 3)), 'minimum')
array([[1, 1, 1, 2, 1, 1, 1],
       [1, 1, 1, 2, 1, 1, 1],
       [1, 1, 1, 2, 1, 1, 1],
       [1, 1, 1, 2, 1, 1, 1],
       [3, 3, 3, 4, 3, 3, 3],
       [1, 1, 1, 2, 1, 1, 1],
       [1, 1, 1, 2, 1, 1, 1]])

>>> a = [1, 2, 3, 4, 5]
>>> np.lib.pad(a, (2,3), 'reflect')
array([3, 2, 1, 2, 3, 4, 5, 4, 3, 2])

>>> np.lib.pad(a, (2,3), 'reflect', reflect_type='odd')
array([-1,  0,  1,  2,  3,  4,  5,  6,  7,  8])

>>> np.lib.pad(a, (2,3), 'symmetric')
array([2, 1, 1, 2, 3, 4, 5, 5, 4, 3])

>>> np.lib.pad(a, (2,3), 'symmetric', reflect_type='odd')
array([0, 1, 1, 2, 3, 4, 5, 5, 6, 7])

>>> np.lib.pad(a, (2,3), 'wrap')
array([4, 5, 1, 2, 3, 4, 5, 1, 2, 3])

>>> def padwithtens(vector, pad_width, iaxis, kwargs):
...     vector[:pad_width[0]] = 10
...     vector[-pad_width[1]:] = 10
...     return vector

>>> a = np.arange(6)
>>> a = a.reshape((2,3))

>>> np.lib.pad(a, 2, padwithtens)
array([[10, 10, 10, 10, 10, 10, 10],
       [10, 10, 10, 10, 10, 10, 10],
       [10, 10,  0,  1,  2, 10, 10],
       [10, 10,  3,  4,  5, 10, 10],
       [10, 10, 10, 10, 10, 10, 10],
       [10, 10, 10, 10, 10, 10, 10]])


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>


m = asanyarray(m)<EOL>if m.ndim < <NUM_LIT:2>:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>return m[:, ::-<NUM_LIT:1>]<EOL>

Flip array in the left/right direction.

Flip the entries in each row in the left/right direction.
Columns are preserved, but appear in a different order than before.

Parameters
----------
m : array_like
    Input array, must be at least 2-D.

Returns
-------
f : ndarray
    A view of `m` with the columns reversed.  Since a view
    is returned, this operation is :math:`\\mathcal O(1)`.

See Also
--------
flipud : Flip array in the up/down direction.
rot90 : Rotate array counterclockwise.

Notes
-----
Equivalent to A[:,::-1]. Requires the array to be at least 2-D.

Examples
--------
>>> A = np.diag([1.,2.,3.])
>>> A
array([[ 1.,  0.,  0.],
       [ 0.,  2.,  0.],
       [ 0.,  0.,  3.]])
>>> np.fliplr(A)
array([[ 0.,  0.,  1.],
       [ 0.,  2.,  0.],
       [ 3.,  0.,  0.]])

>>> A = np.random.randn(2,3,5)
>>> np.all(np.fliplr(A)==A[:,::-1,...])
True


m = asanyarray(m)<EOL>if m.ndim < <NUM_LIT:1>:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>return m[::-<NUM_LIT:1>, ...]<EOL>

Flip array in the up/down direction.

Flip the entries in each column in the up/down direction.
Rows are preserved, but appear in a different order than before.

Parameters
----------
m : array_like
    Input array.

Returns
-------
out : array_like
    A view of `m` with the rows reversed.  Since a view is
    returned, this operation is :math:`\\mathcal O(1)`.

See Also
--------
fliplr : Flip array in the left/right direction.
rot90 : Rotate array counterclockwise.

Notes
-----
Equivalent to ``A[::-1,...]``.
Does not require the array to be two-dimensional.

Examples
--------
>>> A = np.diag([1.0, 2, 3])
>>> A
array([[ 1.,  0.,  0.],
       [ 0.,  2.,  0.],
       [ 0.,  0.,  3.]])
>>> np.flipud(A)
array([[ 0.,  0.,  3.],
       [ 0.,  2.,  0.],
       [ 1.,  0.,  0.]])

>>> A = np.random.randn(2,3,5)
>>> np.all(np.flipud(A)==A[::-1,...])
True

>>> np.flipud([1,2])
array([2, 1])


m = asanyarray(m)<EOL>if m.ndim < <NUM_LIT:2>:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>k = k % <NUM_LIT:4><EOL>if k == <NUM_LIT:0>:<EOL><INDENT>return m<EOL><DEDENT>elif k == <NUM_LIT:1>:<EOL><INDENT>return fliplr(m).swapaxes(<NUM_LIT:0>, <NUM_LIT:1>)<EOL><DEDENT>elif k == <NUM_LIT:2>:<EOL><INDENT>return fliplr(flipud(m))<EOL><DEDENT>else:<EOL><INDENT>return fliplr(m.swapaxes(<NUM_LIT:0>, <NUM_LIT:1>))<EOL><DEDENT>

Rotate an array by 90 degrees in the counter-clockwise direction.

The first two dimensions are rotated; therefore, the array must be at
least 2-D.

Parameters
----------
m : array_like
    Array of two or more dimensions.
k : integer
    Number of times the array is rotated by 90 degrees.

Returns
-------
y : ndarray
    Rotated array.

See Also
--------
fliplr : Flip an array horizontally.
flipud : Flip an array vertically.

Examples
--------
>>> m = np.array([[1,2],[3,4]], int)
>>> m
array([[1, 2],
       [3, 4]])
>>> np.rot90(m)
array([[2, 4],
       [1, 3]])
>>> np.rot90(m, 2)
array([[4, 3],
       [2, 1]])


def eye(N, M=None, k=<NUM_LIT:0>, dtype=float):

if M is None:<EOL><INDENT>M = N<EOL><DEDENT>m = zeros((N, M), dtype=dtype)<EOL>if k >= M:<EOL><INDENT>return m<EOL><DEDENT>if k >= <NUM_LIT:0>:<EOL><INDENT>i = k<EOL><DEDENT>else:<EOL><INDENT>i = (-k) * M<EOL><DEDENT>m[:M-k].flat[i::M+<NUM_LIT:1>] = <NUM_LIT:1><EOL>return m<EOL>

Return a 2-D array with ones on the diagonal and zeros elsewhere.

Parameters
----------
N : int
  Number of rows in the output.
M : int, optional
  Number of columns in the output. If None, defaults to `N`.
k : int, optional
  Index of the diagonal: 0 (the default) refers to the main diagonal,
  a positive value refers to an upper diagonal, and a negative value
  to a lower diagonal.
dtype : data-type, optional
  Data-type of the returned array.

Returns
-------
I : ndarray of shape (N,M)
  An array where all elements are equal to zero, except for the `k`-th
  diagonal, whose values are equal to one.

See Also
--------
identity : (almost) equivalent function
diag : diagonal 2-D array from a 1-D array specified by the user.

Examples
--------
>>> np.eye(2, dtype=int)
array([[1, 0],
       [0, 1]])
>>> np.eye(3, k=1)
array([[ 0.,  1.,  0.],
       [ 0.,  0.,  1.],
       [ 0.,  0.,  0.]])


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]])


try:<EOL><INDENT>wrap = v.__array_wrap__<EOL><DEDENT>except AttributeError:<EOL><INDENT>wrap = None<EOL><DEDENT>v = asarray(v).ravel()<EOL>s = len(v)<EOL>n = s + abs(k)<EOL>res = zeros((n, n), v.dtype)<EOL>if (k >= <NUM_LIT:0>):<EOL><INDENT>i = arange(<NUM_LIT:0>, n-k)<EOL>fi = i+k+i*n<EOL><DEDENT>else:<EOL><INDENT>i = arange(<NUM_LIT:0>, n+k)<EOL>fi = i+(i-k)*n<EOL><DEDENT>res.flat[fi] = v<EOL>if not wrap:<EOL><INDENT>return res<EOL><DEDENT>return wrap(res)<EOL>

Create a two-dimensional array with the flattened input as a diagonal.

Parameters
----------
v : array_like
    Input data, which is flattened and set as the `k`-th
    diagonal of the output.
k : int, optional
    Diagonal to set; 0, the default, corresponds to the "main" diagonal,
    a positive (negative) `k` giving the number of the diagonal above
    (below) the main.

Returns
-------
out : ndarray
    The 2-D output array.

See Also
--------
diag : MATLAB work-alike for 1-D and 2-D arrays.
diagonal : Return specified diagonals.
trace : Sum along diagonals.

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

>>> np.diagflat([1,2], 1)
array([[0, 1, 0],
       [0, 0, 2],
       [0, 0, 0]])


def tri(N, M=None, k=<NUM_LIT:0>, dtype=float):

if M is None:<EOL><INDENT>M = N<EOL><DEDENT>m = greater_equal.outer(arange(N, dtype=_min_int(<NUM_LIT:0>, N)),<EOL>arange(-k, M-k, dtype=_min_int(-k, M - k)))<EOL>m = m.astype(dtype, copy=False)<EOL>return m<EOL>

An array with ones at and below the given diagonal and zeros elsewhere.

Parameters
----------
N : int
    Number of rows in the array.
M : int, optional
    Number of columns in the array.
    By default, `M` is taken equal to `N`.
k : int, optional
    The sub-diagonal at and below which the array is filled.
    `k` = 0 is the main diagonal, while `k` < 0 is below it,
    and `k` > 0 is above.  The default is 0.
dtype : dtype, optional
    Data type of the returned array.  The default is float.

Returns
-------
tri : ndarray of shape (N, M)
    Array with its lower triangle filled with ones and zero elsewhere;
    in other words ``T[i,j] == 1`` for ``i <= j + k``, 0 otherwise.

Examples
--------
>>> np.tri(3, 5, 2, dtype=int)
array([[1, 1, 1, 0, 0],
       [1, 1, 1, 1, 0],
       [1, 1, 1, 1, 1]])

>>> np.tri(3, 5, -1)
array([[ 0.,  0.,  0.,  0.,  0.],
       [ 1.,  0.,  0.,  0.,  0.],
       [ 1.,  1.,  0.,  0.,  0.]])


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

Lower triangle of an array.

Return a copy of an array with elements above the `k`-th diagonal zeroed.

Parameters
----------
m : array_like, shape (M, N)
    Input array.
k : int, optional
    Diagonal above which to zero elements.  `k = 0` (the default) is the
    main diagonal, `k < 0` is below it and `k > 0` is above.

Returns
-------
tril : ndarray, shape (M, N)
    Lower triangle of `m`, of same shape and data-type as `m`.

See Also
--------
triu : same thing, only for the upper triangle

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


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


def histogram2d(x, y, bins=<NUM_LIT:10>, range=None, normed=False, weights=None):

from numpy import histogramdd<EOL>try:<EOL><INDENT>N = len(bins)<EOL><DEDENT>except TypeError:<EOL><INDENT>N = <NUM_LIT:1><EOL><DEDENT>if N != <NUM_LIT:1> and N != <NUM_LIT:2>:<EOL><INDENT>xedges = yedges = asarray(bins, float)<EOL>bins = [xedges, yedges]<EOL><DEDENT>hist, edges = histogramdd([x, y], bins, range, normed, weights)<EOL>return hist, edges[<NUM_LIT:0>], edges[<NUM_LIT:1>]<EOL>

Compute the bi-dimensional histogram of two data samples.

Parameters
----------
x : array_like, shape (N,)
    An array containing the x coordinates of the points to be
    histogrammed.
y : array_like, shape (N,)
    An array containing the y coordinates of the points to be
    histogrammed.
bins : int or [int, int] or array_like or [array, array], optional
    The bin specification:

      * If int, the number of bins for the two dimensions (nx=ny=bins).
      * If [int, int], the number of bins in each dimension
        (nx, ny = bins).
      * If array_like, the bin edges for the two dimensions
        (x_edges=y_edges=bins).
      * If [array, array], the bin edges in each dimension
        (x_edges, y_edges = bins).

range : array_like, shape(2,2), optional
    The leftmost and rightmost edges of the bins along each dimension
    (if not specified explicitly in the `bins` parameters):
    ``[[xmin, xmax], [ymin, ymax]]``. All values outside of this range
    will be considered outliers and not tallied in the histogram.
normed : bool, optional
    If False, returns the number of samples in each bin. If True,
    returns the bin density ``bin_count / sample_count / bin_area``.
weights : array_like, shape(N,), optional
    An array of values ``w_i`` weighing each sample ``(x_i, y_i)``.
    Weights are normalized to 1 if `normed` is True. If `normed` is
    False, the values of the returned histogram are equal to the sum of
    the weights belonging to the samples falling into each bin.

Returns
-------
H : ndarray, shape(nx, ny)
    The bi-dimensional histogram of samples `x` and `y`. Values in `x`
    are histogrammed along the first dimension and values in `y` are
    histogrammed along the second dimension.
xedges : ndarray, shape(nx,)
    The bin edges along the first dimension.
yedges : ndarray, shape(ny,)
    The bin edges along the second dimension.

See Also
--------
histogram : 1D histogram
histogramdd : Multidimensional histogram

Notes
-----
When `normed` is True, then the returned histogram is the sample
density, defined such that the sum over bins of the product
``bin_value * bin_area`` is 1.

Please note that the histogram does not follow the Cartesian convention
where `x` values are on the abscissa and `y` values on the ordinate
axis.  Rather, `x` is histogrammed along the first dimension of the
array (vertical), and `y` along the second dimension of the array
(horizontal).  This ensures compatibility with `histogramdd`.

Examples
--------
>>> import matplotlib as mpl
>>> import matplotlib.pyplot as plt

Construct a 2D-histogram with variable bin width. First define the bin
edges:

>>> xedges = [0, 1, 1.5, 3, 5]
>>> yedges = [0, 2, 3, 4, 6]

Next we create a histogram H with random bin content:

>>> x = np.random.normal(3, 1, 100)
>>> y = np.random.normal(1, 1, 100)
>>> H, xedges, yedges = np.histogram2d(y, x, bins=(xedges, yedges))

Or we fill the histogram H with a determined bin content:

>>> H = np.ones((4, 4)).cumsum().reshape(4, 4)
>>> print H[::-1]  # This shows the bin content in the order as plotted
[[ 13.  14.  15.  16.]
 [  9.  10.  11.  12.]
 [  5.   6.   7.   8.]
 [  1.   2.   3.   4.]]

Imshow can only do an equidistant representation of bins:

>>> fig = plt.figure(figsize=(7, 3))
>>> ax = fig.add_subplot(131)
>>> ax.set_title('imshow: equidistant')
>>> im = plt.imshow(H, interpolation='nearest', origin='low',
                extent=[xedges[0], xedges[-1], yedges[0], yedges[-1]])

pcolormesh can display exact bin edges:

>>> ax = fig.add_subplot(132)
>>> ax.set_title('pcolormesh: exact bin edges')
>>> X, Y = np.meshgrid(xedges, yedges)
>>> ax.pcolormesh(X, Y, H)
>>> ax.set_aspect('equal')

NonUniformImage displays exact bin edges with interpolation:

>>> ax = fig.add_subplot(133)
>>> ax.set_title('NonUniformImage: interpolated')
>>> im = mpl.image.NonUniformImage(ax, interpolation='bilinear')
>>> xcenters = xedges[:-1] + 0.5 * (xedges[1:] - xedges[:-1])
>>> ycenters = yedges[:-1] + 0.5 * (yedges[1:] - yedges[:-1])
>>> im.set_data(xcenters, ycenters, H)
>>> ax.images.append(im)
>>> ax.set_xlim(xedges[0], xedges[-1])
>>> ax.set_ylim(yedges[0], yedges[-1])
>>> ax.set_aspect('equal')
>>> plt.show()


def mask_indices(n, mask_func, k=<NUM_LIT:0>):

m = ones((n, n), int)<EOL>a = mask_func(m, k)<EOL>return where(a != <NUM_LIT:0>)<EOL>

Return the indices to access (n, n) arrays, given a masking function.

Assume `mask_func` is a function that, for a square array a of size
``(n, n)`` with a possible offset argument `k`, when called as
``mask_func(a, k)`` returns a new array with zeros in certain locations
(functions like `triu` or `tril` do precisely this). Then this function
returns the indices where the non-zero values would be located.

Parameters
----------
n : int
    The returned indices will be valid to access arrays of shape (n, n).
mask_func : callable
    A function whose call signature is similar to that of `triu`, `tril`.
    That is, ``mask_func(x, k)`` returns a boolean array, shaped like `x`.
    `k` is an optional argument to the function.
k : scalar
    An optional argument which is passed through to `mask_func`. Functions
    like `triu`, `tril` take a second argument that is interpreted as an
    offset.

Returns
-------
indices : tuple of arrays.
    The `n` arrays of indices corresponding to the locations where
    ``mask_func(np.ones((n, n)), k)`` is True.

See Also
--------
triu, tril, triu_indices, tril_indices

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

Examples
--------
These are the indices that would allow you to access the upper triangular
part of any 3x3 array:

>>> iu = np.mask_indices(3, np.triu)

For example, if `a` is a 3x3 array:

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

An offset can be passed also to the masking function.  This gets us the
indices starting on the first diagonal right of the main one:

>>> iu1 = np.mask_indices(3, np.triu, 1)

with which we now extract only three elements:

>>> a[iu1]
array([1, 2, 5])


def tril_indices(n, k=<NUM_LIT:0>, m=None):

return where(tri(n, m, k=k, dtype=bool))<EOL>

Return the indices for the lower-triangle of an (n, m) array.

Parameters
----------
n : int
    The row dimension of the arrays for which the returned
    indices will be valid.
k : int, optional
    Diagonal offset (see `tril` for details).
m : int, optional
    .. versionadded:: 1.9.0

    The column dimension of the arrays for which the returned
    arrays will be valid.
    By default `m` is taken equal to `n`.

Returns
-------
inds : tuple of arrays
    The indices for the triangle. The returned tuple contains two arrays,
    each with the indices along one dimension of the array.

See also
--------
triu_indices : similar function, for upper-triangular.
mask_indices : generic function accepting an arbitrary mask function.
tril, triu

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

Examples
--------
Compute two different sets of indices to access 4x4 arrays, one for the
lower triangular part starting at the main diagonal, and one starting two
diagonals further right:

>>> il1 = np.tril_indices(4)
>>> il2 = np.tril_indices(4, 2)

Here is how they can be used with a sample array:

>>> a = np.arange(16).reshape(4, 4)
>>> a
array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11],
       [12, 13, 14, 15]])

Both for indexing:

>>> a[il1]
array([ 0,  4,  5,  8,  9, 10, 12, 13, 14, 15])

And for assigning values:

>>> a[il1] = -1
>>> a
array([[-1,  1,  2,  3],
       [-1, -1,  6,  7],
       [-1, -1, -1, 11],
       [-1, -1, -1, -1]])

These cover almost the whole array (two diagonals right of the main one):

>>> a[il2] = -10
>>> a
array([[-10, -10, -10,   3],
       [-10, -10, -10, -10],
       [-10, -10, -10, -10],
       [-10, -10, -10, -10]])


if arr.ndim != <NUM_LIT:2>:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>return tril_indices(arr.shape[-<NUM_LIT:2>], k=k, m=arr.shape[-<NUM_LIT:1>])<EOL>

Return the indices for the lower-triangle of arr.

See `tril_indices` for full details.

Parameters
----------
arr : array_like
    The indices will be valid for square arrays whose dimensions are
    the same as arr.
k : int, optional
    Diagonal offset (see `tril` for details).

See Also
--------
tril_indices, tril

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


def triu_indices(n, k=<NUM_LIT:0>, m=None):

return where(~tri(n, m, k=k-<NUM_LIT:1>, dtype=bool))<EOL>

Return the indices for the upper-triangle of an (n, m) array.

Parameters
----------
n : int
    The size of the arrays for which the returned indices will
    be valid.
k : int, optional
    Diagonal offset (see `triu` for details).
m : int, optional
    .. versionadded:: 1.9.0

    The column dimension of the arrays for which the returned
    arrays will be valid.
    By default `m` is taken equal to `n`.

Returns
-------
inds : tuple, shape(2) of ndarrays, shape(`n`)
    The indices for the triangle. The returned tuple contains two arrays,
    each with the indices along one dimension of the array.  Can be used
    to slice a ndarray of shape(`n`, `n`).

See also
--------
tril_indices : similar function, for lower-triangular.
mask_indices : generic function accepting an arbitrary mask function.
triu, tril

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

Examples
--------
Compute two different sets of indices to access 4x4 arrays, one for the
upper triangular part starting at the main diagonal, and one starting two
diagonals further right:

>>> iu1 = np.triu_indices(4)
>>> iu2 = np.triu_indices(4, 2)

Here is how they can be used with a sample array:

>>> a = np.arange(16).reshape(4, 4)
>>> a
array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11],
       [12, 13, 14, 15]])

Both for indexing:

>>> a[iu1]
array([ 0,  1,  2,  3,  5,  6,  7, 10, 11, 15])

And for assigning values:

>>> a[iu1] = -1
>>> a
array([[-1, -1, -1, -1],
       [ 4, -1, -1, -1],
       [ 8,  9, -1, -1],
       [12, 13, 14, -1]])

These cover only a small part of the whole array (two diagonals right
of the main one):

>>> a[iu2] = -10
>>> a
array([[ -1,  -1, -10, -10],
       [  4,  -1,  -1, -10],
       [  8,   9,  -1,  -1],
       [ 12,  13,  14,  -1]])


if arr.ndim != <NUM_LIT:2>:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>return triu_indices(arr.shape[-<NUM_LIT:2>], k=k, m=arr.shape[-<NUM_LIT:1>])<EOL>

Return the indices for the upper-triangle of arr.

See `triu_indices` for full details.

Parameters
----------
arr : ndarray, shape(N, N)
    The indices will be valid for square arrays.
k : int, optional
    Diagonal offset (see `triu` for details).

Returns
-------
triu_indices_from : tuple, shape(2) of ndarray, shape(N)
    Indices for the upper-triangle of `arr`.

See Also
--------
triu_indices, triu

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


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.


args = [np.asarray(_m) for _m in args]<EOL>shapes = [x.shape for x in args]<EOL>if len(set(shapes)) == <NUM_LIT:1>:<EOL><INDENT>return args<EOL><DEDENT>shapes = [list(s) for s in shapes]<EOL>strides = [list(x.strides) for x in args]<EOL>nds = [len(s) for s in shapes]<EOL>biggest = max(nds)<EOL>for i in range(len(args)):<EOL><INDENT>diff = biggest - nds[i]<EOL>if diff > <NUM_LIT:0>:<EOL><INDENT>shapes[i] = [<NUM_LIT:1>] * diff + shapes[i]<EOL>strides[i] = [<NUM_LIT:0>] * diff + strides[i]<EOL><DEDENT><DEDENT>common_shape = []<EOL>for axis in range(biggest):<EOL><INDENT>lengths = [s[axis] for s in shapes]<EOL>unique = set(lengths + [<NUM_LIT:1>])<EOL>if len(unique) > <NUM_LIT:2>:<EOL><INDENT>raise ValueError("<STR_LIT>"<EOL>"<STR_LIT>" % (axis,))<EOL><DEDENT>elif len(unique) == <NUM_LIT:2>:<EOL><INDENT>unique.remove(<NUM_LIT:1>)<EOL>new_length = unique.pop()<EOL>common_shape.append(new_length)<EOL>for i in range(len(args)):<EOL><INDENT>if shapes[i][axis] == <NUM_LIT:1>:<EOL><INDENT>shapes[i][axis] = new_length<EOL>strides[i][axis] = <NUM_LIT:0><EOL><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>common_shape.append(<NUM_LIT:1>)<EOL><DEDENT><DEDENT>broadcasted = [as_strided(x, shape=sh, strides=st) for (x, sh, st) in<EOL>zip(args, shapes, strides)]<EOL>return broadcasted<EOL>

Broadcast any number of arrays against each other.

Parameters
----------
`*args` : array_likes
    The arrays to broadcast.

Returns
-------
broadcasted : list of arrays
    These arrays are views on the original arrays.  They are typically
    not contiguous.  Furthermore, more than one element of a
    broadcasted array may refer to a single memory location.  If you
    need to write to the arrays, make copies first.

Examples
--------
>>> x = np.array([[1,2,3]])
>>> y = np.array([[1],[2],[3]])
>>> np.broadcast_arrays(x, y)
[array([[1, 2, 3],
       [1, 2, 3],
       [1, 2, 3]]), array([[1, 1, 1],
       [2, 2, 2],
       [3, 3, 3]])]

Here is a useful idiom for getting contiguous copies instead of
non-contiguous views.

>>> [np.array(a) for a in np.broadcast_arrays(x, y)]
[array([[1, 2, 3],
       [1, 2, 3],
       [1, 2, 3]]), array([[1, 1, 1],
       [2, 2, 2],
       [3, 3, 3]])]


try:<EOL><INDENT>obj + '<STR_LIT>'<EOL><DEDENT>except (TypeError, ValueError):<EOL><INDENT>return False<EOL><DEDENT>return True<EOL>

Check whether obj behaves like a string.


try:<EOL><INDENT>obj + asbytes('<STR_LIT>')<EOL><DEDENT>except (TypeError, ValueError):<EOL><INDENT>return False<EOL><DEDENT>return True<EOL>

Check whether obj behaves like a bytes object.


def _to_filehandle(fname, flag='<STR_LIT:r>', return_opened=False):

if _is_string_like(fname):<EOL><INDENT>if fname.endswith('<STR_LIT>'):<EOL><INDENT>import gzip<EOL>fhd = gzip.open(fname, flag)<EOL><DEDENT>elif fname.endswith('<STR_LIT>'):<EOL><INDENT>import bz2<EOL>fhd = bz2.BZ2File(fname)<EOL><DEDENT>else:<EOL><INDENT>fhd = file(fname, flag)<EOL><DEDENT>opened = True<EOL><DEDENT>elif hasattr(fname, '<STR_LIT>'):<EOL><INDENT>fhd = fname<EOL>opened = False<EOL><DEDENT>else:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>if return_opened:<EOL><INDENT>return fhd, opened<EOL><DEDENT>return fhd<EOL>

Returns the filehandle corresponding to a string or a file.
If the string ends in '.gz', the file is automatically unzipped.

Parameters
----------
fname : string, filehandle
    Name of the file whose filehandle must be returned.
flag : string, optional
    Flag indicating the status of the file ('r' for read, 'w' for write).
return_opened : boolean, optional
    Whether to return the opening status of the file.


for name in ndtype.names or ():<EOL><INDENT>if ndtype[name].names:<EOL><INDENT>return True<EOL><DEDENT><DEDENT>return False<EOL>

Returns whether one or several fields of a dtype are nested.

Parameters
----------
ndtype : dtype
    Data-type of a structured array.

Raises
------
AttributeError
    If `ndtype` does not have a `names` attribute.

Examples
--------
>>> dt = np.dtype([('name', 'S4'), ('x', float), ('y', float)])
>>> np.lib._iotools.has_nested_fields(dt)
False


names = ndtype.names<EOL>if names is None:<EOL><INDENT>if flatten_base:<EOL><INDENT>return [ndtype.base] * int(np.prod(ndtype.shape))<EOL><DEDENT>return [ndtype.base]<EOL><DEDENT>else:<EOL><INDENT>types = []<EOL>for field in names:<EOL><INDENT>info = ndtype.fields[field]<EOL>flat_dt = flatten_dtype(info[<NUM_LIT:0>], flatten_base)<EOL>types.extend(flat_dt)<EOL><DEDENT>return types<EOL><DEDENT>

Unpack a structured data-type by collapsing nested fields and/or fields
with a shape.

Note that the field names are lost.

Parameters
----------
ndtype : dtype
    The datatype to collapse
flatten_base : {False, True}, optional
    Whether to transform a field with a shape into several fields or not.

Examples
--------
>>> dt = np.dtype([('name', 'S4'), ('x', float), ('y', float),
...                ('block', int, (2, 3))])
>>> np.lib._iotools.flatten_dtype(dt)
[dtype('|S4'), dtype('float64'), dtype('float64'), dtype('int32')]
>>> np.lib._iotools.flatten_dtype(dt, flatten_base=True)
[dtype('|S4'), dtype('float64'), dtype('float64'), dtype('int32'),
 dtype('int32'), dtype('int32'), dtype('int32'), dtype('int32'),
 dtype('int32')]


value = value.upper()<EOL>if value == asbytes('<STR_LIT>'):<EOL><INDENT>return True<EOL><DEDENT>elif value == asbytes('<STR_LIT>'):<EOL><INDENT>return False<EOL><DEDENT>else:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>

Tries to transform a string supposed to represent a boolean to a boolean.

Parameters
----------
value : str
    The string that is transformed to a boolean.

Returns
-------
boolval : bool
    The boolean representation of `value`.

Raises
------
ValueError
    If the string is not 'True' or 'False' (case independent)

Examples
--------
>>> np.lib._iotools.str2bool('TRUE')
True
>>> np.lib._iotools.str2bool('false')
False


def easy_dtype(ndtype, names=None, defaultfmt="<STR_LIT>", **validationargs):

try:<EOL><INDENT>ndtype = np.dtype(ndtype)<EOL><DEDENT>except TypeError:<EOL><INDENT>validate = NameValidator(**validationargs)<EOL>nbfields = len(ndtype)<EOL>if names is None:<EOL><INDENT>names = ['<STR_LIT>'] * len(ndtype)<EOL><DEDENT>elif isinstance(names, basestring):<EOL><INDENT>names = names.split("<STR_LIT:U+002C>")<EOL><DEDENT>names = validate(names, nbfields=nbfields, defaultfmt=defaultfmt)<EOL>ndtype = np.dtype(dict(formats=ndtype, names=names))<EOL><DEDENT>else:<EOL><INDENT>nbtypes = len(ndtype)<EOL>if names is not None:<EOL><INDENT>validate = NameValidator(**validationargs)<EOL>if isinstance(names, basestring):<EOL><INDENT>names = names.split("<STR_LIT:U+002C>")<EOL><DEDENT>if nbtypes == <NUM_LIT:0>:<EOL><INDENT>formats = tuple([ndtype.type] * len(names))<EOL>names = validate(names, defaultfmt=defaultfmt)<EOL>ndtype = np.dtype(list(zip(names, formats)))<EOL><DEDENT>else:<EOL><INDENT>ndtype.names = validate(names, nbfields=nbtypes,<EOL>defaultfmt=defaultfmt)<EOL><DEDENT><DEDENT>elif (nbtypes > <NUM_LIT:0>):<EOL><INDENT>validate = NameValidator(**validationargs)<EOL>if ((ndtype.names == tuple("<STR_LIT>" % i for i in range(nbtypes))) and<EOL>(defaultfmt != "<STR_LIT>")):<EOL><INDENT>ndtype.names = validate(['<STR_LIT>'] * nbtypes, defaultfmt=defaultfmt)<EOL><DEDENT>else:<EOL><INDENT>ndtype.names = validate(ndtype.names, defaultfmt=defaultfmt)<EOL><DEDENT><DEDENT><DEDENT>return ndtype<EOL>

Convenience function to create a `np.dtype` object.

The function processes the input `dtype` and matches it with the given
names.

Parameters
----------
ndtype : var
    Definition of the dtype. Can be any string or dictionary recognized
    by the `np.dtype` function, or a sequence of types.
names : str or sequence, optional
    Sequence of strings to use as field names for a structured dtype.
    For convenience, `names` can be a string of a comma-separated list
    of names.
defaultfmt : str, optional
    Format string used to define missing names, such as ``"f%i"``
    (default) or ``"fields_%02i"``.
validationargs : optional
    A series of optional arguments used to initialize a
    `NameValidator`.

Examples
--------
>>> np.lib._iotools.easy_dtype(float)
dtype('float64')
>>> np.lib._iotools.easy_dtype("i4, f8")
dtype([('f0', '<i4'), ('f1', '<f8')])
>>> np.lib._iotools.easy_dtype("i4, f8", defaultfmt="field_%03i")
dtype([('field_000', '<i4'), ('field_001', '<f8')])

>>> np.lib._iotools.easy_dtype((int, float, float), names="a,b,c")
dtype([('a', '<i8'), ('b', '<f8'), ('c', '<f8')])
>>> np.lib._iotools.easy_dtype(float, names="a,b,c")
dtype([('a', '<f8'), ('b', '<f8'), ('c', '<f8')])


return lambda input: [_.strip() for _ in method(input)]<EOL>

Wrapper to strip each member of the output of `method`.

Parameters
----------
method : function
    Function that takes a single argument and returns a sequence of
    strings.

Returns
-------
wrapped : function
    The result of wrapping `method`. `wrapped` takes a single input
    argument and returns a list of strings that are stripped of
    white-space.


def validate(self, names, defaultfmt="<STR_LIT>", nbfields=None):

<EOL>if (names is None):<EOL><INDENT>if (nbfields is None):<EOL><INDENT>return None<EOL><DEDENT>names = []<EOL><DEDENT>if isinstance(names, basestring):<EOL><INDENT>names = [names, ]<EOL><DEDENT>if nbfields is not None:<EOL><INDENT>nbnames = len(names)<EOL>if (nbnames < nbfields):<EOL><INDENT>names = list(names) + ['<STR_LIT>'] * (nbfields - nbnames)<EOL><DEDENT>elif (nbnames > nbfields):<EOL><INDENT>names = names[:nbfields]<EOL><DEDENT><DEDENT>deletechars = self.deletechars<EOL>excludelist = self.excludelist<EOL>case_converter = self.case_converter<EOL>replace_space = self.replace_space<EOL>validatednames = []<EOL>seen = dict()<EOL>nbempty = <NUM_LIT:0><EOL>for item in names:<EOL><INDENT>item = case_converter(item).strip()<EOL>if replace_space:<EOL><INDENT>item = item.replace('<STR_LIT:U+0020>', replace_space)<EOL><DEDENT>item = '<STR_LIT>'.join([c for c in item if c not in deletechars])<EOL>if item == '<STR_LIT>':<EOL><INDENT>item = defaultfmt % nbempty<EOL>while item in names:<EOL><INDENT>nbempty += <NUM_LIT:1><EOL>item = defaultfmt % nbempty<EOL><DEDENT>nbempty += <NUM_LIT:1><EOL><DEDENT>elif item in excludelist:<EOL><INDENT>item += '<STR_LIT:_>'<EOL><DEDENT>cnt = seen.get(item, <NUM_LIT:0>)<EOL>if cnt > <NUM_LIT:0>:<EOL><INDENT>validatednames.append(item + '<STR_LIT>' % cnt)<EOL><DEDENT>else:<EOL><INDENT>validatednames.append(item)<EOL><DEDENT>seen[item] = cnt + <NUM_LIT:1><EOL><DEDENT>return tuple(validatednames)<EOL>

Validate a list of strings as field names for a structured array.

Parameters
----------
names : sequence of str
    Strings to be validated.
defaultfmt : str, optional
    Default format string, used if validating a given string
    reduces its length to zero.
nboutput : integer, optional
    Final number of validated names, used to expand or shrink the
    initial list of names.

Returns
-------
validatednames : list of str
    The list of validated field names.

Notes
-----
A `NameValidator` instance can be called directly, which is the
same as calling `validate`. For examples, see `NameValidator`.


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.


if dtype.type == np.datetime64:<EOL><INDENT>return dtype<EOL><DEDENT>return dtype.type<EOL>

Returns dtype for datetime64 and type of dtype otherwise.


@classmethod<EOL><INDENT>def upgrade_mapper(cls, func, default=None):<DEDENT>

<EOL>if hasattr(func, '<STR_LIT>'):<EOL><INDENT>cls._mapper.insert(-<NUM_LIT:1>, (cls._getsubdtype(default), func, default))<EOL>return<EOL><DEDENT>elif hasattr(func, '<STR_LIT>'):<EOL><INDENT>if isinstance(func[<NUM_LIT:0>], (tuple, list)):<EOL><INDENT>for _ in func:<EOL><INDENT>cls._mapper.insert(-<NUM_LIT:1>, _)<EOL><DEDENT>return<EOL><DEDENT>if default is None:<EOL><INDENT>default = [None] * len(func)<EOL><DEDENT>else:<EOL><INDENT>default = list(default)<EOL>default.append([None] * (len(func) - len(default)))<EOL><DEDENT>for (fct, dft) in zip(func, default):<EOL><INDENT>cls._mapper.insert(-<NUM_LIT:1>, (cls._getsubdtype(dft), fct, dft))<EOL><DEDENT><DEDENT>

Upgrade the mapper of a StringConverter by adding a new function and
its corresponding default.

The input function (or sequence of functions) and its associated
default value (if any) is inserted in penultimate position of the
mapper.  The corresponding type is estimated from the dtype of the
default value.

Parameters
----------
func : var
    Function, or sequence of functions

Examples
--------
>>> import dateutil.parser
>>> import datetime
>>> dateparser = datetustil.parser.parse
>>> defaultdate = datetime.date(2000, 1, 1)
>>> StringConverter.upgrade_mapper(dateparser, default=defaultdate)


self._checked = True<EOL>try:<EOL><INDENT>self._strict_call(value)<EOL><DEDENT>except ValueError:<EOL><INDENT>if self._locked:<EOL><INDENT>errmsg = "<STR_LIT>"<EOL>raise ConverterLockError(errmsg)<EOL><DEDENT>_statusmax = len(self._mapper)<EOL>_status = self._status<EOL>if _status == _statusmax:<EOL><INDENT>errmsg = "<STR_LIT>"<EOL>raise ConverterError(errmsg)<EOL><DEDENT>elif _status < _statusmax - <NUM_LIT:1>:<EOL><INDENT>_status += <NUM_LIT:1><EOL><DEDENT>(self.type, self.func, default) = self._mapper[_status]<EOL>self._status = _status<EOL>if self._initial_default is not None:<EOL><INDENT>self.default = self._initial_default<EOL><DEDENT>else:<EOL><INDENT>self.default = default<EOL><DEDENT>self.upgrade(value)<EOL><DEDENT>

Find the best converter for a given string, and return the result.

The supplied string `value` is converted by testing different
converters in order. First the `func` method of the
`StringConverter` instance is tried, if this fails other available
converters are tried.  The order in which these other converters
are tried is determined by the `_status` attribute of the instance.

Parameters
----------
value : str
    The string to convert.

Returns
-------
out : any
    The result of converting `value` with the appropriate converter.


def fv(rate, nper, pmt, pv, when='<STR_LIT:end>'):

when = _convert_when(when)<EOL>(rate, nper, pmt, pv, when) = map(np.asarray, [rate, nper, pmt, pv, when])<EOL>temp = (<NUM_LIT:1>+rate)**nper<EOL>miter = np.broadcast(rate, nper, pmt, pv, when)<EOL>zer = np.zeros(miter.shape)<EOL>fact = np.where(rate == zer, nper + zer,<EOL>(<NUM_LIT:1> + rate*when)*(temp - <NUM_LIT:1>)/rate + zer)<EOL>return -(pv*temp + pmt*fact)<EOL>

Compute the future value.

Given:
 * a present value, `pv`
 * an interest `rate` compounded once per period, of which
   there are
 * `nper` total
 * a (fixed) payment, `pmt`, paid either
 * at the beginning (`when` = {'begin', 1}) or the end
   (`when` = {'end', 0}) of each period

Return:
   the value at the end of the `nper` periods

Parameters
----------
rate : scalar or array_like of shape(M, )
    Rate of interest as decimal (not per cent) per period
nper : scalar or array_like of shape(M, )
    Number of compounding periods
pmt : scalar or array_like of shape(M, )
    Payment
pv : scalar or array_like of shape(M, )
    Present value
when : {{'begin', 1}, {'end', 0}}, {string, int}, optional
    When payments are due ('begin' (1) or 'end' (0)).
    Defaults to {'end', 0}.

Returns
-------
out : ndarray
    Future values.  If all input is scalar, returns a scalar float.  If
    any input is array_like, returns future values for each input element.
    If multiple inputs are array_like, they all must have the same shape.

Notes
-----
The future value is computed by solving the equation::

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

or, when ``rate == 0``::

 fv + pv + pmt * nper == 0

References
----------
.. [WRW] 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

Examples
--------
What is the future value after 10 years of saving $100 now, with
an additional monthly savings of $100.  Assume the interest rate is
5% (annually) compounded monthly?

>>> np.fv(0.05/12, 10*12, -100, -100)
15692.928894335748

By convention, the negative sign represents cash flow out (i.e. money not
available today).  Thus, saving $100 a month at 5% annual interest leads
to $15,692.93 available to spend in 10 years.

If any input is array_like, returns an array of equal shape.  Let's
compare different interest rates from the example above.

>>> a = np.array((0.05, 0.06, 0.07))/12
>>> np.fv(a, 10*12, -100, -100)
array([ 15692.92889434,  16569.87435405,  17509.44688102])


def pmt(rate, nper, pv, fv=<NUM_LIT:0>, when='<STR_LIT:end>'):

when = _convert_when(when)<EOL>(rate, nper, pv, fv, when) = map(np.asarray, [rate, nper, pv, fv, when])<EOL>temp = (<NUM_LIT:1>+rate)**nper<EOL>miter = np.broadcast(rate, nper, pv, fv, when)<EOL>zer = np.zeros(miter.shape)<EOL>fact = np.where(rate == zer, nper + zer,<EOL>(<NUM_LIT:1> + rate*when)*(temp - <NUM_LIT:1>)/rate + zer)<EOL>return -(fv + pv*temp) / fact<EOL>

Compute the payment against loan principal plus interest.

Given:
 * a present value, `pv` (e.g., an amount borrowed)
 * a future value, `fv` (e.g., 0)
 * an interest `rate` compounded once per period, of which
   there are
 * `nper` total
 * and (optional) specification of whether payment is made
   at the beginning (`when` = {'begin', 1}) or the end
   (`when` = {'end', 0}) of each period

Return:
   the (fixed) periodic payment.

Parameters
----------
rate : array_like
    Rate of interest (per period)
nper : array_like
    Number of compounding periods
pv : array_like
    Present value
fv : array_like (optional)
    Future value (default = 0)
when : {{'begin', 1}, {'end', 0}}, {string, int}
    When payments are due ('begin' (1) or 'end' (0))

Returns
-------
out : ndarray
    Payment against loan plus interest.  If all input is scalar, returns a
    scalar float.  If any input is array_like, returns payment for each
    input element. If multiple inputs are array_like, they all must have
    the same shape.

Notes
-----
The payment is computed by solving the equation::

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

or, when ``rate == 0``::

  fv + pv + pmt * nper == 0

for ``pmt``.

Note that computing a monthly mortgage payment is only
one use for this function.  For example, pmt returns the
periodic deposit one must make to achieve a specified
future balance given an initial deposit, a fixed,
periodically compounded interest rate, and the total
number of periods.

References
----------
.. [WRW] 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-formulaOpenDocument-formula-20090508.odt

Examples
--------
What is the monthly payment needed to pay off a $200,000 loan in 15
years at an annual interest rate of 7.5%?

>>> np.pmt(0.075/12, 12*15, 200000)
-1854.0247200054619

In order to pay-off (i.e., have a future-value of 0) the $200,000 obtained
today, a monthly payment of $1,854.02 would be required.  Note that this
example illustrates usage of `fv` having a default value of 0.


def nper(rate, pmt, pv, fv=<NUM_LIT:0>, when='<STR_LIT:end>'):

when = _convert_when(when)<EOL>(rate, pmt, pv, fv, when) = map(np.asarray, [rate, pmt, pv, fv, when])<EOL>use_zero_rate = False<EOL>with np.errstate(divide="<STR_LIT>"):<EOL><INDENT>try:<EOL><INDENT>z = pmt*(<NUM_LIT:1.0>+rate*when)/rate<EOL><DEDENT>except FloatingPointError:<EOL><INDENT>use_zero_rate = True<EOL><DEDENT><DEDENT>if use_zero_rate:<EOL><INDENT>return (-fv + pv) / (pmt + <NUM_LIT:0.0>)<EOL><DEDENT>else:<EOL><INDENT>A = -(fv + pv)/(pmt+<NUM_LIT:0.0>)<EOL>B = np.log((-fv+z) / (pv+z))/np.log(<NUM_LIT:1.0>+rate)<EOL>miter = np.broadcast(rate, pmt, pv, fv, when)<EOL>zer = np.zeros(miter.shape)<EOL>return np.where(rate == zer, A + zer, B + zer) + <NUM_LIT:0.0><EOL><DEDENT>

Compute the number of periodic payments.

Parameters
----------
rate : array_like
    Rate of interest (per period)
pmt : array_like
    Payment
pv : array_like
    Present value
fv : array_like, optional
    Future value
when : {{'begin', 1}, {'end', 0}}, {string, int}, optional
    When payments are due ('begin' (1) or 'end' (0))

Notes
-----
The number of periods ``nper`` is computed by solving the equation::

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

but if ``rate = 0`` then::

 fv + pv + pmt*nper = 0

Examples
--------
If you only had $150/month to pay towards the loan, how long would it take
to pay-off a loan of $8,000 at 7% annual interest?

>>> print round(np.nper(0.07/12, -150, 8000), 5)
64.07335

So, over 64 months would be required to pay off the loan.

The same analysis could be done with several different interest rates
and/or payments and/or total amounts to produce an entire table.

>>> np.nper(*(np.ogrid[0.07/12: 0.08/12: 0.01/12,
...                    -150   : -99     : 50    ,
...                    8000   : 9001    : 1000]))
array([[[  64.07334877,   74.06368256],
        [ 108.07548412,  127.99022654]],
       [[  66.12443902,   76.87897353],
        [ 114.70165583,  137.90124779]]])


def ipmt(rate, per, nper, pv, fv=<NUM_LIT:0.0>, when='<STR_LIT:end>'):

when = _convert_when(when)<EOL>rate, per, nper, pv, fv, when = np.broadcast_arrays(rate, per, nper,<EOL>pv, fv, when)<EOL>total_pmt = pmt(rate, nper, pv, fv, when)<EOL>ipmt = _rbl(rate, per, total_pmt, pv, when)*rate<EOL>try:<EOL><INDENT>ipmt = np.where(when == <NUM_LIT:1>, ipmt/(<NUM_LIT:1> + rate), ipmt)<EOL>ipmt = np.where(np.logical_and(when == <NUM_LIT:1>, per == <NUM_LIT:1>), <NUM_LIT:0.0>, ipmt)<EOL><DEDENT>except IndexError:<EOL><INDENT>pass<EOL><DEDENT>return ipmt<EOL>

Compute the interest portion of a payment.

Parameters
----------
rate : scalar or array_like of shape(M, )
    Rate of interest as decimal (not per cent) per period
per : scalar or array_like of shape(M, )
    Interest paid against the loan changes during the life or the loan.
    The `per` is the payment period to calculate the interest amount.
nper : scalar or array_like of shape(M, )
    Number of compounding periods
pv : scalar or array_like of shape(M, )
    Present value
fv : scalar or array_like of shape(M, ), optional
    Future value
when : {{'begin', 1}, {'end', 0}}, {string, int}, optional
    When payments are due ('begin' (1) or 'end' (0)).
    Defaults to {'end', 0}.

Returns
-------
out : ndarray
    Interest portion of payment.  If all input is scalar, returns a scalar
    float.  If any input is array_like, returns interest payment for each
    input element. If multiple inputs are array_like, they all must have
    the same shape.

See Also
--------
ppmt, pmt, pv

Notes
-----
The total payment is made up of payment against principal plus interest.

``pmt = ppmt + ipmt``

Examples
--------
What is the amortization schedule for a 1 year loan of $2500 at
8.24% interest per year compounded monthly?

>>> principal = 2500.00

The 'per' variable represents the periods of the loan.  Remember that
financial equations start the period count at 1!

>>> per = np.arange(1*12) + 1
>>> ipmt = np.ipmt(0.0824/12, per, 1*12, principal)
>>> ppmt = np.ppmt(0.0824/12, per, 1*12, principal)

Each element of the sum of the 'ipmt' and 'ppmt' arrays should equal
'pmt'.

>>> pmt = np.pmt(0.0824/12, 1*12, principal)
>>> np.allclose(ipmt + ppmt, pmt)
True

>>> fmt = '{0:2d} {1:8.2f} {2:8.2f} {3:8.2f}'
>>> for payment in per:
...     index = payment - 1
...     principal = principal + ppmt[index]
...     print fmt.format(payment, ppmt[index], ipmt[index], principal)
 1  -200.58   -17.17  2299.42
 2  -201.96   -15.79  2097.46
 3  -203.35   -14.40  1894.11
 4  -204.74   -13.01  1689.37
 5  -206.15   -11.60  1483.22
 6  -207.56   -10.18  1275.66
 7  -208.99    -8.76  1066.67
 8  -210.42    -7.32   856.25
 9  -211.87    -5.88   644.38
10  -213.32    -4.42   431.05
11  -214.79    -2.96   216.26
12  -216.26    -1.49    -0.00

>>> interestpd = np.sum(ipmt)
>>> np.round(interestpd, 2)
-112.98


return fv(rate, (per - <NUM_LIT:1>), pmt, pv, when)<EOL>

This function is here to simply have a different name for the 'fv'
function to not interfere with the 'fv' keyword argument within the 'ipmt'
function.  It is the 'remaining balance on loan' which might be useful as
it's own function, but is easily calculated with the 'fv' function.


def ppmt(rate, per, nper, pv, fv=<NUM_LIT:0.0>, when='<STR_LIT:end>'):

total = pmt(rate, nper, pv, fv, when)<EOL>return total - ipmt(rate, per, nper, pv, fv, when)<EOL>

Compute the payment against loan principal.

Parameters
----------
rate : array_like
    Rate of interest (per period)
per : array_like, int
    Amount paid against the loan changes.  The `per` is the period of
    interest.
nper : array_like
    Number of compounding periods
pv : array_like
    Present value
fv : array_like, optional
    Future value
when : {{'begin', 1}, {'end', 0}}, {string, int}
    When payments are due ('begin' (1) or 'end' (0))

See Also
--------
pmt, pv, ipmt


def pv(rate, nper, pmt, fv=<NUM_LIT:0.0>, when='<STR_LIT:end>'):

when = _convert_when(when)<EOL>(rate, nper, pmt, fv, when) = map(np.asarray, [rate, nper, pmt, fv, when])<EOL>temp = (<NUM_LIT:1>+rate)**nper<EOL>miter = np.broadcast(rate, nper, pmt, fv, when)<EOL>zer = np.zeros(miter.shape)<EOL>fact = np.where(rate == zer, nper+zer, (<NUM_LIT:1>+rate*when)*(temp-<NUM_LIT:1>)/rate+zer)<EOL>return -(fv + pmt*fact)/temp<EOL>

Compute the present value.

Given:
 * a future value, `fv`
 * an interest `rate` compounded once per period, of which
   there are
 * `nper` total
 * a (fixed) payment, `pmt`, paid either
 * at the beginning (`when` = {'begin', 1}) or the end
   (`when` = {'end', 0}) of each period

Return:
   the value now

Parameters
----------
rate : array_like
    Rate of interest (per period)
nper : array_like
    Number of compounding periods
pmt : array_like
    Payment
fv : array_like, optional
    Future value
when : {{'begin', 1}, {'end', 0}}, {string, int}, optional
    When payments are due ('begin' (1) or 'end' (0))

Returns
-------
out : ndarray, float
    Present value of a series of payments or investments.

Notes
-----
The present value is computed by solving the equation::

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

or, when ``rate = 0``::

 fv + pv + pmt * nper = 0

for `pv`, which is then returned.

References
----------
.. [WRW] 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

Examples
--------
What is the present value (e.g., the initial investment)
of an investment that needs to total $15692.93
after 10 years of saving $100 every month?  Assume the
interest rate is 5% (annually) compounded monthly.

>>> np.pv(0.05/12, 10*12, -100, 15692.93)
-100.00067131625819

By convention, the negative sign represents cash flow out
(i.e., money not available today).  Thus, to end up with
$15,692.93 in 10 years saving $100 a month at 5% annual
interest, one's initial deposit should also be $100.

If any input is array_like, ``pv`` returns an array of equal shape.
Let's compare different interest rates in the example above:

>>> a = np.array((0.05, 0.04, 0.03))/12
>>> np.pv(a, 10*12, -100, 15692.93)
array([ -100.00067132,  -649.26771385, -1273.78633713])

So, to end up with the same $15692.93 under the same $100 per month
"savings plan," for annual interest rates of 4% and 3%, one would
need initial investments of $649.27 and $1273.79, respectively.


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


res = np.roots(values[::-<NUM_LIT:1>])<EOL>mask = (res.imag == <NUM_LIT:0>) & (res.real > <NUM_LIT:0>)<EOL>if res.size == <NUM_LIT:0>:<EOL><INDENT>return np.nan<EOL><DEDENT>res = res[mask].real<EOL>rate = <NUM_LIT:1.0>/res - <NUM_LIT:1><EOL>rate = rate.item(np.argmin(np.abs(rate)))<EOL>return rate<EOL>

Return the Internal Rate of Return (IRR).

This is the "average" periodically compounded rate of return
that gives a net present value of 0.0; for a more complete explanation,
see Notes below.

Parameters
----------
values : array_like, shape(N,)
    Input cash flows per time period.  By convention, net "deposits"
    are negative and net "withdrawals" are positive.  Thus, for
    example, at least the first element of `values`, which represents
    the initial investment, will typically be negative.

Returns
-------
out : float
    Internal Rate of Return for periodic input values.

Notes
-----
The IRR is perhaps best understood through an example (illustrated
using np.irr in the Examples section below).  Suppose one invests 100
units and then makes the following withdrawals at regular (fixed)
intervals: 39, 59, 55, 20.  Assuming the ending value is 0, one's 100
unit investment yields 173 units; however, due to the combination of
compounding and the periodic withdrawals, the "average" rate of return
is neither simply 0.73/4 nor (1.73)^0.25-1.  Rather, it is the solution
(for :math:`r`) of the equation:

.. math:: -100 + \\frac{39}{1+r} + \\frac{59}{(1+r)^2}
 + \\frac{55}{(1+r)^3} + \\frac{20}{(1+r)^4} = 0

In general, for `values` :math:`= [v_0, v_1, ... v_M]`,
irr is the solution of the equation: [G]_

.. math:: \\sum_{t=0}^M{\\frac{v_t}{(1+irr)^{t}}} = 0

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

Examples
--------
>>> round(irr([-100, 39, 59, 55, 20]), 5)
0.28095
>>> round(irr([-100, 0, 0, 74]), 5)
-0.0955
>>> round(irr([-100, 100, 0, -7]), 5)
-0.0833
>>> round(irr([-100, 100, 0, 7]), 5)
0.06206
>>> round(irr([-5, 10.5, 1, -8, 1]), 5)
0.0886

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


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 mirr(values, finance_rate, reinvest_rate):

values = np.asarray(values, dtype=np.double)<EOL>n = values.size<EOL>pos = values > <NUM_LIT:0><EOL>neg = values < <NUM_LIT:0><EOL>if not (pos.any() and neg.any()):<EOL><INDENT>return np.nan<EOL><DEDENT>numer = np.abs(npv(reinvest_rate, values*pos))<EOL>denom = np.abs(npv(finance_rate, values*neg))<EOL>return (numer/denom)**(<NUM_LIT:1.0>/(n - <NUM_LIT:1>))*(<NUM_LIT:1> + reinvest_rate) - <NUM_LIT:1><EOL>

Modified internal rate of return.

Parameters
----------
values : array_like
    Cash flows (must contain at least one positive and one negative
    value) or nan is returned.  The first value is considered a sunk
    cost at time zero.
finance_rate : scalar
    Interest rate paid on the cash flows
reinvest_rate : scalar
    Interest rate received on the cash flows upon reinvestment

Returns
-------
out : float
    Modified internal rate of return


if self.major == other.major:<EOL><INDENT>if self.minor == other.minor:<EOL><INDENT>if self.bugfix == other.bugfix:<EOL><INDENT>vercmp = <NUM_LIT:0><EOL><DEDENT>elif self.bugfix > other.bugfix:<EOL><INDENT>vercmp = <NUM_LIT:1><EOL><DEDENT>else:<EOL><INDENT>vercmp = -<NUM_LIT:1><EOL><DEDENT><DEDENT>elif self.minor > other.minor:<EOL><INDENT>vercmp = <NUM_LIT:1><EOL><DEDENT>else:<EOL><INDENT>vercmp = -<NUM_LIT:1><EOL><DEDENT><DEDENT>elif self.major > other.major:<EOL><INDENT>vercmp = <NUM_LIT:1><EOL><DEDENT>else:<EOL><INDENT>vercmp = -<NUM_LIT:1><EOL><DEDENT>return vercmp<EOL>


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>


import gzip<EOL>class GzipFile(gzip.GzipFile):<EOL><INDENT>def seek(self, offset, whence=<NUM_LIT:0>):<EOL><INDENT>if whence == <NUM_LIT:1>:<EOL><INDENT>offset = self.offset + offset<EOL><DEDENT>if whence not in [<NUM_LIT:0>, <NUM_LIT:1>]:<EOL><INDENT>raise IOError("<STR_LIT>")<EOL><DEDENT>if offset < self.offset:<EOL><INDENT>self.rewind()<EOL>count = offset - self.offset<EOL>for i in range(count // <NUM_LIT>):<EOL><INDENT>self.read(<NUM_LIT>)<EOL><DEDENT>self.read(count % <NUM_LIT>)<EOL><DEDENT><DEDENT>def tell(self):<EOL><INDENT>return self.offset<EOL><DEDENT><DEDENT>if isinstance(f, str):<EOL><INDENT>f = GzipFile(f)<EOL><DEDENT>elif isinstance(f, gzip.GzipFile):<EOL><INDENT>try:<EOL><INDENT>name = f.name<EOL><DEDENT>except AttributeError:<EOL><INDENT>name = f.filename<EOL><DEDENT>mode = f.mode<EOL>f = GzipFile(fileobj=f.fileobj, filename=name)<EOL>f.mode = mode<EOL><DEDENT>return f<EOL>

Use this factory to produce the class so that we can do a lazy
    import on gzip.


import gzip<EOL>own_fid = False<EOL>if isinstance(file, basestring):<EOL><INDENT>fid = open(file, "<STR_LIT:rb>")<EOL>own_fid = True<EOL><DEDENT>elif isinstance(file, gzip.GzipFile):<EOL><INDENT>fid = seek_gzip_factory(file)<EOL><DEDENT>else:<EOL><INDENT>fid = file<EOL><DEDENT>try:<EOL><INDENT>_ZIP_PREFIX = asbytes('<STR_LIT>')<EOL>N = len(format.MAGIC_PREFIX)<EOL>magic = fid.read(N)<EOL>fid.seek(-N, <NUM_LIT:1>)  <EOL>if magic.startswith(_ZIP_PREFIX):<EOL><INDENT>tmp = own_fid<EOL>own_fid = False<EOL>return NpzFile(fid, own_fid=tmp)<EOL><DEDENT>elif magic == format.MAGIC_PREFIX:<EOL><INDENT>if mmap_mode:<EOL><INDENT>return format.open_memmap(file, mode=mmap_mode)<EOL><DEDENT>else:<EOL><INDENT>return format.read_array(fid)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>try:<EOL><INDENT>return pickle.load(fid)<EOL><DEDENT>except:<EOL><INDENT>raise IOError(<EOL>"<STR_LIT>" % repr(file))<EOL><DEDENT><DEDENT><DEDENT>finally:<EOL><INDENT>if own_fid:<EOL><INDENT>fid.close()<EOL><DEDENT><DEDENT>

Load arrays or pickled objects from ``.npy``, ``.npz`` or pickled files.

Parameters
----------
file : file-like object or string
    The file to read. File-like objects must support the
    ``seek()`` and ``read()`` methods. Pickled files require that the
    file-like object support the ``readline()`` method as well.
mmap_mode : {None, 'r+', 'r', 'w+', 'c'}, optional
    If not None, then memory-map the file, using the given mode (see
    `numpy.memmap` for a detailed description of the modes).  A
    memory-mapped array is kept on disk. However, it can be accessed
    and sliced like any ndarray.  Memory mapping is especially useful
    for accessing small fragments of large files without reading the
    entire file into memory.

Returns
-------
result : array, tuple, dict, etc.
    Data stored in the file. For ``.npz`` files, the returned instance
    of NpzFile class must be closed to avoid leaking file descriptors.

Raises
------
IOError
    If the input file does not exist or cannot be read.

See Also
--------
save, savez, savez_compressed, loadtxt
memmap : Create a memory-map to an array stored in a file on disk.

Notes
-----
- If the file contains pickle data, then whatever object is stored
  in the pickle is returned.
- If the file is a ``.npy`` file, then a single array is returned.
- If the file is a ``.npz`` file, then a dictionary-like object is
  returned, containing ``{filename: array}`` key-value pairs, one for
  each file in the archive.
- If the file is a ``.npz`` file, the returned value supports the
  context manager protocol in a similar fashion to the open function::

    with load('foo.npz') as data:
        a = data['a']

  The underlying file descriptor is closed when exiting the 'with'
  block.

Examples
--------
Store data to disk, and load it again:

>>> np.save('/tmp/123', np.array([[1, 2, 3], [4, 5, 6]]))
>>> np.load('/tmp/123.npy')
array([[1, 2, 3],
       [4, 5, 6]])

Store compressed data to disk, and load it again:

>>> a=np.array([[1, 2, 3], [4, 5, 6]])
>>> b=np.array([1, 2])
>>> np.savez('/tmp/123.npz', a=a, b=b)
>>> data = np.load('/tmp/123.npz')
>>> data['a']
array([[1, 2, 3],
       [4, 5, 6]])
>>> data['b']
array([1, 2])
>>> data.close()

Mem-map the stored array, and then access the second row
directly from disk:

>>> X = np.load('/tmp/123.npy', mmap_mode='r')
>>> X[1, :]
memmap([4, 5, 6])


own_fid = False<EOL>if isinstance(file, basestring):<EOL><INDENT>if not file.endswith('<STR_LIT>'):<EOL><INDENT>file = file + '<STR_LIT>'<EOL><DEDENT>fid = open(file, "<STR_LIT:wb>")<EOL>own_fid = True<EOL><DEDENT>else:<EOL><INDENT>fid = file<EOL><DEDENT>try:<EOL><INDENT>arr = np.asanyarray(arr)<EOL>format.write_array(fid, arr)<EOL><DEDENT>finally:<EOL><INDENT>if own_fid:<EOL><INDENT>fid.close()<EOL><DEDENT><DEDENT>

Save an array to a binary file in NumPy ``.npy`` format.

Parameters
----------
file : file or str
    File or filename to which the data is saved.  If file is a file-object,
    then the filename is unchanged.  If file is a string, a ``.npy``
    extension will be appended to the file name if it does not already
    have one.
arr : array_like
    Array data to be saved.

See Also
--------
savez : Save several arrays into a ``.npz`` archive
savetxt, load

Notes
-----
For a description of the ``.npy`` format, see `format`.

Examples
--------
>>> from tempfile import TemporaryFile
>>> outfile = TemporaryFile()

>>> x = np.arange(10)
>>> np.save(outfile, x)

>>> outfile.seek(0) # Only needed here to simulate closing & reopening file
>>> np.load(outfile)
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])


_savez(file, args, kwds, False)<EOL>

Save several arrays into a single file in uncompressed ``.npz`` format.

If arguments are passed in with no keywords, the corresponding variable
names, in the ``.npz`` file, are 'arr_0', 'arr_1', etc. If keyword
arguments are given, the corresponding variable names, in the ``.npz``
file will match the keyword names.

Parameters
----------
file : str or file
    Either the file name (string) or an open file (file-like object)
    where the data will be saved. If file is a string, the ``.npz``
    extension will be appended to the file name if it is not already there.
args : Arguments, optional
    Arrays to save to the file. Since it is not possible for Python to
    know the names of the arrays outside `savez`, the arrays will be saved
    with names "arr_0", "arr_1", and so on. These arguments can be any
    expression.
kwds : Keyword arguments, optional
    Arrays to save to the file. Arrays will be saved in the file with the
    keyword names.

Returns
-------
None

See Also
--------
save : Save a single array to a binary file in NumPy format.
savetxt : Save an array to a file as plain text.
savez_compressed : Save several arrays into a compressed ``.npz`` archive

Notes
-----
The ``.npz`` file format is a zipped archive of files named after the
variables they contain.  The archive is not compressed and each file
in the archive contains one variable in ``.npy`` format. For a
description of the ``.npy`` format, see `format`.

When opening the saved ``.npz`` file with `load` a `NpzFile` object is
returned. This is a dictionary-like object which can be queried for
its list of arrays (with the ``.files`` attribute), and for the arrays
themselves.

Examples
--------
>>> from tempfile import TemporaryFile
>>> outfile = TemporaryFile()
>>> x = np.arange(10)
>>> y = np.sin(x)

Using `savez` with \\*args, the arrays are saved with default names.

>>> np.savez(outfile, x, y)
>>> outfile.seek(0) # Only needed here to simulate closing & reopening file
>>> npzfile = np.load(outfile)
>>> npzfile.files
['arr_1', 'arr_0']
>>> npzfile['arr_0']
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])

Using `savez` with \\**kwds, the arrays are saved with the keyword names.

>>> outfile = TemporaryFile()
>>> np.savez(outfile, x=x, y=y)
>>> outfile.seek(0)
>>> npzfile = np.load(outfile)
>>> npzfile.files
['y', 'x']
>>> npzfile['x']
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])


def savez_compressed(file, *args, **kwds):

_savez(file, args, kwds, True)<EOL>

Save several arrays into a single file in compressed ``.npz`` format.

If keyword arguments are given, then filenames are taken from the keywords.
If arguments are passed in with no keywords, then stored file names are
arr_0, arr_1, etc.

Parameters
----------
file : str
    File name of ``.npz`` file.
args : Arguments
    Function arguments.
kwds : Keyword arguments
    Keywords.

See Also
--------
numpy.savez : Save several arrays into an uncompressed ``.npz`` file format
numpy.load : Load the files created by savez_compressed.


typ = dtype.type<EOL>if issubclass(typ, np.bool_):<EOL><INDENT>return lambda x: bool(int(x))<EOL><DEDENT>if issubclass(typ, np.uint64):<EOL><INDENT>return np.uint64<EOL><DEDENT>if issubclass(typ, np.int64):<EOL><INDENT>return np.int64<EOL><DEDENT>if issubclass(typ, np.integer):<EOL><INDENT>return lambda x: int(float(x))<EOL><DEDENT>elif issubclass(typ, np.floating):<EOL><INDENT>return float<EOL><DEDENT>elif issubclass(typ, np.complex):<EOL><INDENT>return complex<EOL><DEDENT>elif issubclass(typ, np.bytes_):<EOL><INDENT>return bytes<EOL><DEDENT>else:<EOL><INDENT>return str<EOL><DEDENT>

Find the correct dtype converter. Adapted from matplotlib