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

Get the current way of handling floating-point errors.

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

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

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

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

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


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

Set the size of the buffer used in ufuncs.

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


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

Return the size of the buffer used in ufuncs.

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


if func is not None and not isinstance(func, collections.Callable):<EOL><INDENT>if not hasattr(func, '<STR_LIT>') or not isinstance(func.write, collections.Callable):<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT><DEDENT>pyvals = umath.geterrobj()<EOL>old = geterrcall()<EOL>pyvals[<NUM_LIT:2>] = func<EOL>umath.seterrobj(pyvals)<EOL>return old<EOL>

Set the floating-point error callback function or log object.

There are two ways to capture floating-point error messages.  The first
is to set the error-handler to 'call', using `seterr`.  Then, set
the function to call using this function.

The second is to set the error-handler to 'log', using `seterr`.
Floating-point errors then trigger a call to the 'write' method of
the provided object.

Parameters
----------
func : callable f(err, flag) or object with write method
    Function to call upon floating-point errors ('call'-mode) or
    object whose 'write' method is used to log such message ('log'-mode).

    The call function takes two arguments. The first is the
    type of error (one of "divide", "over", "under", or "invalid"),
    and the second is the status flag.  The flag is a byte, whose
    least-significant bits indicate the status::

      [0 0 0 0 invalid over under invalid]

    In other words, ``flags = divide + 2*over + 4*under + 8*invalid``.

    If an object is provided, its write method should take one argument,
    a string.

Returns
-------
h : callable, log instance or None
    The old error handler.

See Also
--------
seterr, geterr, geterrcall

Examples
--------
Callback upon error:

>>> def err_handler(type, flag):
...     print "Floating point error (%s), with flag %s" % (type, flag)
...

>>> saved_handler = np.seterrcall(err_handler)
>>> save_err = np.seterr(all='call')

>>> np.array([1, 2, 3]) / 0.0
Floating point error (divide by zero), with flag 1
array([ Inf,  Inf,  Inf])

>>> np.seterrcall(saved_handler)
<function err_handler at 0x...>
>>> np.seterr(**save_err)
{'over': 'call', 'divide': 'call', 'invalid': 'call', 'under': 'call'}

Log error message:

>>> class Log(object):
...     def write(self, msg):
...         print "LOG: %s" % msg
...

>>> log = Log()
>>> saved_handler = np.seterrcall(log)
>>> save_err = np.seterr(all='log')

>>> np.array([1, 2, 3]) / 0.0
LOG: Warning: divide by zero encountered in divide
<BLANKLINE>
array([ Inf,  Inf,  Inf])

>>> np.seterrcall(saved_handler)
<__main__.Log object at 0x...>
>>> np.seterr(**save_err)
{'over': 'log', 'divide': 'log', 'invalid': 'log', 'under': 'log'}


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

Return the current callback function used on floating-point errors.

When the error handling for a floating-point error (one of "divide",
"over", "under", or "invalid") is set to 'call' or 'log', the function
that is called or the log instance that is written to is returned by
`geterrcall`. This function or log instance has been set with
`seterrcall`.

Returns
-------
errobj : callable, log instance or None
    The current error handler. If no handler was set through `seterrcall`,
    ``None`` is returned.

See Also
--------
seterrcall, seterr, geterr

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

Examples
--------
>>> np.geterrcall()  # we did not yet set a handler, returns None

>>> oldsettings = np.seterr(all='call')
>>> def err_handler(type, flag):
...     print "Floating point error (%s), with flag %s" % (type, flag)
>>> oldhandler = np.seterrcall(err_handler)
>>> np.array([1, 2, 3]) / 0.0
Floating point error (divide by zero), with flag 1
array([ Inf,  Inf,  Inf])

>>> cur_handler = np.geterrcall()
>>> cur_handler is err_handler
True


tmp = asarray(x)<EOL>ndim = len(tmp.shape)<EOL>if axes is None:<EOL><INDENT>axes = list(range(ndim))<EOL><DEDENT>elif isinstance(axes, integer_types):<EOL><INDENT>axes = (axes,)<EOL><DEDENT>y = tmp<EOL>for k in axes:<EOL><INDENT>n = tmp.shape[k]<EOL>p2 = (n+<NUM_LIT:1>)//<NUM_LIT:2><EOL>mylist = concatenate((arange(p2, n), arange(p2)))<EOL>y = take(y, mylist, k)<EOL><DEDENT>return y<EOL>

Shift the zero-frequency component to the center of the spectrum.

This function swaps half-spaces for all axes listed (defaults to all).
Note that ``y[0]`` is the Nyquist component only if ``len(x)`` is even.

Parameters
----------
x : array_like
    Input array.
axes : int or shape tuple, optional
    Axes over which to shift.  Default is None, which shifts all axes.

Returns
-------
y : ndarray
    The shifted array.

See Also
--------
ifftshift : The inverse of `fftshift`.

Examples
--------
>>> freqs = np.fft.fftfreq(10, 0.1)
>>> freqs
array([ 0.,  1.,  2.,  3.,  4., -5., -4., -3., -2., -1.])
>>> np.fft.fftshift(freqs)
array([-5., -4., -3., -2., -1.,  0.,  1.,  2.,  3.,  4.])

Shift the zero-frequency component only along the second axis:

>>> freqs = np.fft.fftfreq(9, d=1./9).reshape(3, 3)
>>> freqs
array([[ 0.,  1.,  2.],
       [ 3.,  4., -4.],
       [-3., -2., -1.]])
>>> np.fft.fftshift(freqs, axes=(1,))
array([[ 2.,  0.,  1.],
       [-4.,  3.,  4.],
       [-1., -3., -2.]])


tmp = asarray(x)<EOL>ndim = len(tmp.shape)<EOL>if axes is None:<EOL><INDENT>axes = list(range(ndim))<EOL><DEDENT>elif isinstance(axes, integer_types):<EOL><INDENT>axes = (axes,)<EOL><DEDENT>y = tmp<EOL>for k in axes:<EOL><INDENT>n = tmp.shape[k]<EOL>p2 = n-(n+<NUM_LIT:1>)//<NUM_LIT:2><EOL>mylist = concatenate((arange(p2, n), arange(p2)))<EOL>y = take(y, mylist, k)<EOL><DEDENT>return y<EOL>

The inverse of `fftshift`. Although identical for even-length `x`, the
functions differ by one sample for odd-length `x`.

Parameters
----------
x : array_like
    Input array.
axes : int or shape tuple, optional
    Axes over which to calculate.  Defaults to None, which shifts all axes.

Returns
-------
y : ndarray
    The shifted array.

See Also
--------
fftshift : Shift zero-frequency component to the center of the spectrum.

Examples
--------
>>> freqs = np.fft.fftfreq(9, d=1./9).reshape(3, 3)
>>> freqs
array([[ 0.,  1.,  2.],
       [ 3.,  4., -4.],
       [-3., -2., -1.]])
>>> np.fft.ifftshift(np.fft.fftshift(freqs))
array([[ 0.,  1.,  2.],
       [ 3.,  4., -4.],
       [-3., -2., -1.]])


if not isinstance(n, integer_types):<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>val = <NUM_LIT:1.0> / (n * d)<EOL>results = empty(n, int)<EOL>N = (n-<NUM_LIT:1>)//<NUM_LIT:2> + <NUM_LIT:1><EOL>p1 = arange(<NUM_LIT:0>, N, dtype=int)<EOL>results[:N] = p1<EOL>p2 = arange(-(n//<NUM_LIT:2>), <NUM_LIT:0>, dtype=int)<EOL>results[N:] = p2<EOL>return results * val<EOL>

Return the Discrete Fourier Transform sample frequencies.

The returned float array `f` contains the frequency bin centers in cycles
per unit of the sample spacing (with zero at the start).  For instance, if
the sample spacing is in seconds, then the frequency unit is cycles/second.

Given a window length `n` and a sample spacing `d`::

  f = [0, 1, ...,   n/2-1,     -n/2, ..., -1] / (d*n)   if n is even
  f = [0, 1, ..., (n-1)/2, -(n-1)/2, ..., -1] / (d*n)   if n is odd

Parameters
----------
n : int
    Window length.
d : scalar, optional
    Sample spacing (inverse of the sampling rate). Defaults to 1.

Returns
-------
f : ndarray
    Array of length `n` containing the sample frequencies.

Examples
--------
>>> signal = np.array([-2, 8, 6, 4, 1, 0, 3, 5], dtype=float)
>>> fourier = np.fft.fft(signal)
>>> n = signal.size
>>> timestep = 0.1
>>> freq = np.fft.fftfreq(n, d=timestep)
>>> freq
array([ 0.  ,  1.25,  2.5 ,  3.75, -5.  , -3.75, -2.5 , -1.25])


if not isinstance(n, integer_types):<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>val = <NUM_LIT:1.0>/(n*d)<EOL>N = n//<NUM_LIT:2> + <NUM_LIT:1><EOL>results = arange(<NUM_LIT:0>, N, dtype=int)<EOL>return results * val<EOL>

Return the Discrete Fourier Transform sample frequencies
(for usage with rfft, irfft).

The returned float array `f` contains the frequency bin centers in cycles
per unit of the sample spacing (with zero at the start).  For instance, if
the sample spacing is in seconds, then the frequency unit is cycles/second.

Given a window length `n` and a sample spacing `d`::

  f = [0, 1, ...,     n/2-1,     n/2] / (d*n)   if n is even
  f = [0, 1, ..., (n-1)/2-1, (n-1)/2] / (d*n)   if n is odd

Unlike `fftfreq` (but like `scipy.fftpack.rfftfreq`)
the Nyquist frequency component is considered to be positive.

Parameters
----------
n : int
    Window length.
d : scalar, optional
    Sample spacing (inverse of the sampling rate). Defaults to 1.

Returns
-------
f : ndarray
    Array of length ``n//2 + 1`` containing the sample frequencies.

Examples
--------
>>> signal = np.array([-2, 8, 6, 4, 1, 0, 3, 5, -3, 4], dtype=float)
>>> fourier = np.fft.rfft(signal)
>>> n = signal.size
>>> sample_rate = 100
>>> freq = np.fft.fftfreq(n, d=1./sample_rate)
>>> freq
array([  0.,  10.,  20.,  30.,  40., -50., -40., -30., -20., -10.])
>>> freq = np.fft.rfftfreq(n, d=1./sample_rate)
>>> freq
array([  0.,  10.,  20.,  30.,  40.,  50.])


return _raw_fft(a, n, axis, fftpack.cffti, fftpack.cfftf, _fft_cache)<EOL>

Compute the one-dimensional discrete Fourier Transform.

This function computes the one-dimensional *n*-point discrete Fourier
Transform (DFT) with the efficient Fast Fourier Transform (FFT)
algorithm [CT].

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

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

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

See Also
--------
numpy.fft : for definition of the DFT and conventions used.
ifft : The inverse of `fft`.
fft2 : The two-dimensional FFT.
fftn : The *n*-dimensional FFT.
rfftn : The *n*-dimensional FFT of real input.
fftfreq : Frequency bins for given FFT parameters.

Notes
-----
FFT (Fast Fourier Transform) refers to a way the discrete Fourier
Transform (DFT) can be calculated efficiently, by using symmetries in the
calculated terms.  The symmetry is highest when `n` is a power of 2, and
the transform is therefore most efficient for these sizes.

The DFT is defined, with the conventions used in this implementation, in
the documentation for the `numpy.fft` module.

References
----------
.. [CT] Cooley, James W., and John W. Tukey, 1965, "An algorithm for the
        machine calculation of complex Fourier series," *Math. Comput.*
        19: 297-301.

Examples
--------
>>> np.fft.fft(np.exp(2j * np.pi * np.arange(8) / 8))
array([ -3.44505240e-16 +1.14383329e-17j,
         8.00000000e+00 -5.71092652e-15j,
         2.33482938e-16 +1.22460635e-16j,
         1.64863782e-15 +1.77635684e-15j,
         9.95839695e-17 +2.33482938e-16j,
         0.00000000e+00 +1.66837030e-15j,
         1.14383329e-17 +1.22460635e-16j,
         -1.64863782e-15 +1.77635684e-15j])

>>> import matplotlib.pyplot as plt
>>> t = np.arange(256)
>>> sp = np.fft.fft(np.sin(t))
>>> freq = np.fft.fftfreq(t.shape[-1])
>>> plt.plot(freq, sp.real, freq, sp.imag)
[<matplotlib.lines.Line2D object at 0x...>, <matplotlib.lines.Line2D object at 0x...>]
>>> plt.show()

In this example, real input has an FFT which is Hermitian, i.e., symmetric
in the real part and anti-symmetric in the imaginary part, as described in
the `numpy.fft` documentation.


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

Compute the one-dimensional inverse discrete Fourier Transform.

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

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

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

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

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

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

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

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

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

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


a = asarray(a).astype(float)<EOL>return _raw_fft(a, n, axis, fftpack.rffti, fftpack.rfftf, _real_fft_cache)<EOL>

Compute the one-dimensional discrete Fourier Transform for real input.

This function computes the one-dimensional *n*-point discrete Fourier
Transform (DFT) of a real-valued array by means of an efficient algorithm
called the Fast Fourier Transform (FFT).

Parameters
----------
a : array_like
    Input array
n : int, optional
    Number of points along transformation axis in the input to use.
    If `n` is smaller than the length of the input, the input is cropped.
    If it is larger, the input is padded with zeros. If `n` is not given,
    the length of the input along the axis specified by `axis` is used.
axis : int, optional
    Axis over which to compute the FFT. If not given, the last axis is
    used.

Returns
-------
out : complex ndarray
    The truncated or zero-padded input, transformed along the axis
    indicated by `axis`, or the last one if `axis` is not specified.
    If `n` is even, the length of the transformed axis is ``(n/2)+1``.
    If `n` is odd, the length is ``(n+1)/2``.

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

See Also
--------
numpy.fft : For definition of the DFT and conventions used.
irfft : The inverse of `rfft`.
fft : The one-dimensional FFT of general (complex) input.
fftn : The *n*-dimensional FFT.
rfftn : The *n*-dimensional FFT of real input.

Notes
-----
When the DFT is computed for purely real input, the output is
Hermitian-symmetric, i.e. the negative frequency terms are just the complex
conjugates of the corresponding positive-frequency terms, and the
negative-frequency terms are therefore redundant.  This function does not
compute the negative frequency terms, and the length of the transformed
axis of the output is therefore ``n//2 + 1``.

When ``A = rfft(a)`` and fs is the sampling frequency, ``A[0]`` contains
the zero-frequency term 0*fs, which is real due to Hermitian symmetry.

If `n` is even, ``A[-1]`` contains the term representing both positive
and negative Nyquist frequency (+fs/2 and -fs/2), and must also be purely
real. If `n` is odd, there is no term at fs/2; ``A[-1]`` contains
the largest positive frequency (fs/2*(n-1)/n), and is complex in the
general case.

If the input `a` contains an imaginary part, it is silently discarded.

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

Notice how the final element of the `fft` output is the complex conjugate
of the second element, for real input. For `rfft`, this symmetry is
exploited to compute only the non-negative frequency terms.


def irfft(a, n=None, axis=-<NUM_LIT:1>):

a = asarray(a).astype(complex)<EOL>if n is None:<EOL><INDENT>n = (shape(a)[axis] - <NUM_LIT:1>) * <NUM_LIT:2><EOL><DEDENT>return _raw_fft(a, n, axis, fftpack.rffti, fftpack.rfftb,<EOL>_real_fft_cache) / n<EOL>

Compute the inverse of the n-point DFT for real input.

This function computes the inverse of the one-dimensional *n*-point
discrete Fourier Transform of real input computed by `rfft`.
In other words, ``irfft(rfft(a), len(a)) == a`` to within numerical
accuracy. (See Notes below for why ``len(a)`` is necessary here.)

The input is expected to be in the form returned by `rfft`, i.e. the
real zero-frequency term followed by the complex positive frequency terms
in order of increasing frequency.  Since the discrete Fourier Transform of
real input is Hermitian-symmetric, the negative frequency terms are taken
to be the complex conjugates of the corresponding positive frequency terms.

Parameters
----------
a : array_like
    The input array.
n : int, optional
    Length of the transformed axis of the output.
    For `n` output points, ``n//2+1`` input points are necessary.  If the
    input is longer than this, it is cropped.  If it is shorter than this,
    it is padded with zeros.  If `n` is not given, it is determined from
    the length of the input along the axis specified by `axis`.
axis : int, optional
    Axis over which to compute the inverse FFT. If not given, the last
    axis is used.

Returns
-------
out : ndarray
    The truncated or zero-padded input, transformed along the axis
    indicated by `axis`, or the last one if `axis` is not specified.
    The length of the transformed axis is `n`, or, if `n` is not given,
    ``2*(m-1)`` where ``m`` is the length of the transformed axis of the
    input. To get an odd number of output points, `n` must be specified.

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

See Also
--------
numpy.fft : For definition of the DFT and conventions used.
rfft : The one-dimensional FFT of real input, of which `irfft` is inverse.
fft : The one-dimensional FFT.
irfft2 : The inverse of the two-dimensional FFT of real input.
irfftn : The inverse of the *n*-dimensional FFT of real input.

Notes
-----
Returns the real valued `n`-point inverse discrete Fourier transform
of `a`, where `a` contains the non-negative frequency terms of a
Hermitian-symmetric sequence. `n` is the length of the result, not the
input.

If you specify an `n` such that `a` must be zero-padded or truncated, the
extra/removed values will be added/removed at high frequencies. One can
thus resample a series to `m` points via Fourier interpolation by:
``a_resamp = irfft(rfft(a), m)``.

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

Notice how the last term in the input to the ordinary `ifft` is the
complex conjugate of the second term, and the output has zero imaginary
part everywhere.  When calling `irfft`, the negative frequencies are not
specified, and the output array is purely real.


a = asarray(a).astype(complex)<EOL>if n is None:<EOL><INDENT>n = (shape(a)[axis] - <NUM_LIT:1>) * <NUM_LIT:2><EOL><DEDENT>return irfft(conjugate(a), n, axis) * n<EOL>

Compute the FFT of a signal which has Hermitian symmetry (real spectrum).

Parameters
----------
a : array_like
    The input array.
n : int, optional
    Length of the transformed axis of the output.
    For `n` output points, ``n//2+1`` input points are necessary.  If the
    input is longer than this, it is cropped.  If it is shorter than this,
    it is padded with zeros.  If `n` is not given, it is determined from
    the length of the input along the axis specified by `axis`.
axis : int, optional
    Axis over which to compute the FFT. If not given, the last
    axis is used.

Returns
-------
out : ndarray
    The truncated or zero-padded input, transformed along the axis
    indicated by `axis`, or the last one if `axis` is not specified.
    The length of the transformed axis is `n`, or, if `n` is not given,
    ``2*(m-1)`` where ``m`` is the length of the transformed axis of the
    input. To get an odd number of output points, `n` must be specified.

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

See also
--------
rfft : Compute the one-dimensional FFT for real input.
ihfft : The inverse of `hfft`.

Notes
-----
`hfft`/`ihfft` are a pair analogous to `rfft`/`irfft`, but for the
opposite case: here the signal has Hermitian symmetry in the time domain
and is real in the frequency domain. So here it's `hfft` for which
you must supply the length of the result if it is to be odd:
``ihfft(hfft(a), len(a)) == a``, within numerical accuracy.

Examples
--------
>>> signal = np.array([1, 2, 3, 4, 3, 2])
>>> np.fft.fft(signal)
array([ 15.+0.j,  -4.+0.j,   0.+0.j,  -1.-0.j,   0.+0.j,  -4.+0.j])
>>> np.fft.hfft(signal[:4]) # Input first half of signal
array([ 15.,  -4.,   0.,  -1.,   0.,  -4.])
>>> np.fft.hfft(signal, 6)  # Input entire signal and truncate
array([ 15.,  -4.,   0.,  -1.,   0.,  -4.])

>>> signal = np.array([[1, 1.j], [-1.j, 2]])
>>> np.conj(signal.T) - signal   # check Hermitian symmetry
array([[ 0.-0.j,  0.+0.j],
       [ 0.+0.j,  0.-0.j]])
>>> freq_spectrum = np.fft.hfft(signal)
>>> freq_spectrum
array([[ 1.,  1.],
       [ 2., -2.]])


def ihfft(a, n=None, axis=-<NUM_LIT:1>):

a = asarray(a).astype(float)<EOL>if n is None:<EOL><INDENT>n = shape(a)[axis]<EOL><DEDENT>return conjugate(rfft(a, n, axis))/n<EOL>

Compute the inverse FFT of a signal which has Hermitian symmetry.

Parameters
----------
a : array_like
    Input array.
n : int, optional
    Length of the inverse FFT.
    Number of points along transformation axis in the input to use.
    If `n` is smaller than the length of the input, the input is cropped.
    If it is larger, the input is padded with zeros. If `n` is not given,
    the length of the input along the axis specified by `axis` is used.
axis : int, optional
    Axis over which to compute the inverse FFT. If not given, the last
    axis is used.

Returns
-------
out : complex ndarray
    The truncated or zero-padded input, transformed along the axis
    indicated by `axis`, or the last one if `axis` is not specified.
    If `n` is even, the length of the transformed axis is ``(n/2)+1``.
    If `n` is odd, the length is ``(n+1)/2``.

See also
--------
hfft, irfft

Notes
-----
`hfft`/`ihfft` are a pair analogous to `rfft`/`irfft`, but for the
opposite case: here the signal has Hermitian symmetry in the time domain
and is real in the frequency domain. So here it's `hfft` for which
you must supply the length of the result if it is to be odd:
``ihfft(hfft(a), len(a)) == a``, within numerical accuracy.

Examples
--------
>>> spectrum = np.array([ 15, -4, 0, -1, 0, -4])
>>> np.fft.ifft(spectrum)
array([ 1.+0.j,  2.-0.j,  3.+0.j,  4.+0.j,  3.+0.j,  2.-0.j])
>>> np.fft.ihfft(spectrum)
array([ 1.-0.j,  2.-0.j,  3.-0.j,  4.-0.j])


return _raw_fftnd(a, s, axes, fft)<EOL>

Compute the N-dimensional discrete Fourier Transform.

This function computes the *N*-dimensional discrete Fourier Transform over
any number of axes in an *M*-dimensional array by means of the Fast Fourier
Transform (FFT).

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

Returns
-------
out : complex ndarray
    The truncated or zero-padded input, transformed along the axes
    indicated by `axes`, or by a combination of `s` and `a`,
    as explained in the parameters section above.

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

See Also
--------
numpy.fft : Overall view of discrete Fourier transforms, with definitions
    and conventions used.
ifftn : The inverse of `fftn`, the inverse *n*-dimensional FFT.
fft : The one-dimensional FFT, with definitions and conventions used.
rfftn : The *n*-dimensional FFT of real input.
fft2 : The two-dimensional FFT.
fftshift : Shifts zero-frequency terms to centre of array

Notes
-----
The output, analogously to `fft`, contains the term for zero frequency in
the low-order corner of all axes, the positive frequency terms in the
first half of all axes, the term for the Nyquist frequency in the middle
of all axes and the negative frequency terms in the second half of all
axes, in order of decreasingly negative frequency.

See `numpy.fft` for details, definitions and conventions used.

Examples
--------
>>> a = np.mgrid[:3, :3, :3][0]
>>> np.fft.fftn(a, axes=(1, 2))
array([[[  0.+0.j,   0.+0.j,   0.+0.j],
        [  0.+0.j,   0.+0.j,   0.+0.j],
        [  0.+0.j,   0.+0.j,   0.+0.j]],
       [[  9.+0.j,   0.+0.j,   0.+0.j],
        [  0.+0.j,   0.+0.j,   0.+0.j],
        [  0.+0.j,   0.+0.j,   0.+0.j]],
       [[ 18.+0.j,   0.+0.j,   0.+0.j],
        [  0.+0.j,   0.+0.j,   0.+0.j],
        [  0.+0.j,   0.+0.j,   0.+0.j]]])
>>> np.fft.fftn(a, (2, 2), axes=(0, 1))
array([[[ 2.+0.j,  2.+0.j,  2.+0.j],
        [ 0.+0.j,  0.+0.j,  0.+0.j]],
       [[-2.+0.j, -2.+0.j, -2.+0.j],
        [ 0.+0.j,  0.+0.j,  0.+0.j]]])

>>> import matplotlib.pyplot as plt
>>> [X, Y] = np.meshgrid(2 * np.pi * np.arange(200) / 12,
...                      2 * np.pi * np.arange(200) / 34)
>>> S = np.sin(X) + np.cos(Y) + np.random.uniform(0, 1, X.shape)
>>> FS = np.fft.fftn(S)
>>> plt.imshow(np.log(np.abs(np.fft.fftshift(FS))**2))
<matplotlib.image.AxesImage object at 0x...>
>>> plt.show()


return _raw_fftnd(a, s, axes, ifft)<EOL>

Compute the N-dimensional inverse discrete Fourier Transform.

This function computes the inverse of the N-dimensional discrete
Fourier Transform over any number of axes in an M-dimensional array by
means of the Fast Fourier Transform (FFT).  In other words,
``ifftn(fftn(a)) == a`` to within numerical accuracy.
For a description of the definitions and conventions used, see `numpy.fft`.

The input, analogously to `ifft`, should be ordered in the same way as is
returned by `fftn`, i.e. it should have the term for zero frequency
in all axes in the low-order corner, the positive frequency terms in the
first half of all axes, the term for the Nyquist frequency in the middle
of all axes and the negative frequency terms in the second half of all
axes, in order of decreasingly negative frequency.

Parameters
----------
a : array_like
    Input array, can be complex.
s : sequence of ints, optional
    Shape (length of each transformed axis) of the output
    (``s[0]`` refers to axis 0, ``s[1]`` to axis 1, etc.).
    This corresponds to ``n`` for ``ifft(x, n)``.
    Along any axis, if the given shape is smaller than that of the input,
    the input is cropped.  If it is larger, the input is padded with zeros.
    if `s` is not given, the shape of the input along the axes specified
    by `axes` is used.  See notes for issue on `ifft` zero padding.
axes : sequence of ints, optional
    Axes over which to compute the IFFT.  If not given, the last ``len(s)``
    axes are used, or all axes if `s` is also not specified.
    Repeated indices in `axes` means that the inverse transform over that
    axis is performed multiple times.

Returns
-------
out : complex ndarray
    The truncated or zero-padded input, transformed along the axes
    indicated by `axes`, or by a combination of `s` or `a`,
    as explained in the parameters section above.

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

See Also
--------
numpy.fft : Overall view of discrete Fourier transforms, with definitions
     and conventions used.
fftn : The forward *n*-dimensional FFT, of which `ifftn` is the inverse.
ifft : The one-dimensional inverse FFT.
ifft2 : The two-dimensional inverse FFT.
ifftshift : Undoes `fftshift`, shifts zero-frequency terms to beginning
    of array.

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

Zero-padding, analogously with `ifft`, is performed by appending zeros to
the input along the specified dimension.  Although this is the common
approach, it might lead to surprising results.  If another form of zero
padding is desired, it must be performed before `ifftn` is called.

Examples
--------
>>> a = np.eye(4)
>>> np.fft.ifftn(np.fft.fftn(a, axes=(0,)), axes=(1,))
array([[ 1.+0.j,  0.+0.j,  0.+0.j,  0.+0.j],
       [ 0.+0.j,  1.+0.j,  0.+0.j,  0.+0.j],
       [ 0.+0.j,  0.+0.j,  1.+0.j,  0.+0.j],
       [ 0.+0.j,  0.+0.j,  0.+0.j,  1.+0.j]])

Create and plot an image with band-limited frequency content:

>>> import matplotlib.pyplot as plt
>>> n = np.zeros((200,200), dtype=complex)
>>> n[60:80, 20:40] = np.exp(1j*np.random.uniform(0, 2*np.pi, (20, 20)))
>>> im = np.fft.ifftn(n).real
>>> plt.imshow(im)
<matplotlib.image.AxesImage object at 0x...>
>>> plt.show()


def fft2(a, s=None, axes=(-<NUM_LIT:2>, -<NUM_LIT:1>)):

return _raw_fftnd(a, s, axes, fft)<EOL>

Compute the 2-dimensional discrete Fourier Transform

This function computes the *n*-dimensional discrete Fourier Transform
over any axes in an *M*-dimensional array by means of the
Fast Fourier Transform (FFT).  By default, the transform is computed over
the last two axes of the input array, i.e., a 2-dimensional FFT.

Parameters
----------
a : array_like
    Input array, can be complex
s : sequence of ints, optional
    Shape (length of each transformed axis) of the output
    (`s[0]` refers to axis 0, `s[1]` to axis 1, etc.).
    This corresponds to `n` for `fft(x, n)`.
    Along each axis, if the given shape is smaller than that of the input,
    the input is cropped.  If it is larger, the input is padded with zeros.
    if `s` is not given, the shape of the input along the axes specified
    by `axes` is used.
axes : sequence of ints, optional
    Axes over which to compute the FFT.  If not given, the last two
    axes are used.  A repeated index in `axes` means the transform over
    that axis is performed multiple times.  A one-element sequence means
    that a one-dimensional FFT is performed.

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

Raises
------
ValueError
    If `s` and `axes` have different length, or `axes` not given and
    ``len(s) != 2``.
IndexError
    If an element of `axes` is larger than than the number of axes of `a`.

See Also
--------
numpy.fft : Overall view of discrete Fourier transforms, with definitions
     and conventions used.
ifft2 : The inverse two-dimensional FFT.
fft : The one-dimensional FFT.
fftn : The *n*-dimensional FFT.
fftshift : Shifts zero-frequency terms to the center of the array.
    For two-dimensional input, swaps first and third quadrants, and second
    and fourth quadrants.

Notes
-----
`fft2` is just `fftn` with a different default for `axes`.

The output, analogously to `fft`, contains the term for zero frequency in
the low-order corner of the transformed axes, the positive frequency terms
in the first half of these axes, the term for the Nyquist frequency in the
middle of the axes and the negative frequency terms in the second half of
the axes, in order of decreasingly negative frequency.

See `fftn` for details and a plotting example, and `numpy.fft` for
definitions and conventions used.

Examples
--------
>>> a = np.mgrid[:5, :5][0]
>>> np.fft.fft2(a)
array([[ 50.0 +0.j        ,   0.0 +0.j        ,   0.0 +0.j        ,
          0.0 +0.j        ,   0.0 +0.j        ],
       [-12.5+17.20477401j,   0.0 +0.j        ,   0.0 +0.j        ,
          0.0 +0.j        ,   0.0 +0.j        ],
       [-12.5 +4.0614962j ,   0.0 +0.j        ,   0.0 +0.j        ,
          0.0 +0.j        ,   0.0 +0.j        ],
       [-12.5 -4.0614962j ,   0.0 +0.j        ,   0.0 +0.j        ,
            0.0 +0.j        ,   0.0 +0.j        ],
       [-12.5-17.20477401j,   0.0 +0.j        ,   0.0 +0.j        ,
          0.0 +0.j        ,   0.0 +0.j        ]])


def ifft2(a, s=None, axes=(-<NUM_LIT:2>, -<NUM_LIT:1>)):

Compute the 2-dimensional inverse discrete Fourier Transform.

This function computes the inverse of the 2-dimensional discrete Fourier
Transform over any number of axes in an M-dimensional array by means of
the Fast Fourier Transform (FFT).  In other words, ``ifft2(fft2(a)) == a``
to within numerical accuracy.  By default, the inverse transform is
computed over the last two axes of the input array.

The input, analogously to `ifft`, should be ordered in the same way as is
returned by `fft2`, i.e. it should have the term for zero frequency
in the low-order corner of the two axes, the positive frequency terms in
the first half of these axes, the term for the Nyquist frequency in the
middle of the axes and the negative frequency terms in the second half of
both axes, in order of decreasingly negative frequency.

Parameters
----------
a : array_like
    Input array, can be complex.
s : sequence of ints, optional
    Shape (length of each axis) of the output (``s[0]`` refers to axis 0,
    ``s[1]`` to axis 1, etc.).  This corresponds to `n` for ``ifft(x, n)``.
    Along each axis, if the given shape is smaller than that of the input,
    the input is cropped.  If it is larger, the input is padded with zeros.
    if `s` is not given, the shape of the input along the axes specified
    by `axes` is used.  See notes for issue on `ifft` zero padding.
axes : sequence of ints, optional
    Axes over which to compute the FFT.  If not given, the last two
    axes are used.  A repeated index in `axes` means the transform over
    that axis is performed multiple times.  A one-element sequence means
    that a one-dimensional FFT is performed.

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

Raises
------
ValueError
    If `s` and `axes` have different length, or `axes` not given and
    ``len(s) != 2``.
IndexError
    If an element of `axes` is larger than than the number of axes of `a`.

See Also
--------
numpy.fft : Overall view of discrete Fourier transforms, with definitions
     and conventions used.
fft2 : The forward 2-dimensional FFT, of which `ifft2` is the inverse.
ifftn : The inverse of the *n*-dimensional FFT.
fft : The one-dimensional FFT.
ifft : The one-dimensional inverse FFT.

Notes
-----
`ifft2` is just `ifftn` with a different default for `axes`.

See `ifftn` for details and a plotting example, and `numpy.fft` for
definition and conventions used.

Zero-padding, analogously with `ifft`, is performed by appending zeros to
the input along the specified dimension.  Although this is the common
approach, it might lead to surprising results.  If another form of zero
padding is desired, it must be performed before `ifft2` is called.

Examples
--------
>>> a = 4 * np.eye(4)
>>> np.fft.ifft2(a)
array([[ 1.+0.j,  0.+0.j,  0.+0.j,  0.+0.j],
       [ 0.+0.j,  0.+0.j,  0.+0.j,  1.+0.j],
       [ 0.+0.j,  0.+0.j,  1.+0.j,  0.+0.j],
       [ 0.+0.j,  1.+0.j,  0.+0.j,  0.+0.j]])


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

Compute the N-dimensional discrete Fourier Transform for real input.

This function computes the N-dimensional discrete Fourier Transform over
any number of axes in an M-dimensional real array by means of the Fast
Fourier Transform (FFT).  By default, all axes are transformed, with the
real transform performed over the last axis, while the remaining
transforms are complex.

Parameters
----------
a : array_like
    Input array, taken to be real.
s : sequence of ints, optional
    Shape (length along each transformed axis) to use from the input.
    (``s[0]`` refers to axis 0, ``s[1]`` to axis 1, etc.).
    The final element of `s` corresponds to `n` for ``rfft(x, n)``, while
    for the remaining axes, it corresponds to `n` for ``fft(x, n)``.
    Along any axis, if the given shape is smaller than that of the input,
    the input is cropped.  If it is larger, the input is padded with zeros.
    if `s` is not given, the shape of the input along the axes specified
    by `axes` is used.
axes : sequence of ints, optional
    Axes over which to compute the FFT.  If not given, the last ``len(s)``
    axes are used, or all axes if `s` is also not specified.

Returns
-------
out : complex ndarray
    The truncated or zero-padded input, transformed along the axes
    indicated by `axes`, or by a combination of `s` and `a`,
    as explained in the parameters section above.
    The length of the last axis transformed will be ``s[-1]//2+1``,
    while the remaining transformed axes will have lengths according to
    `s`, or unchanged from the input.

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

See Also
--------
irfftn : The inverse of `rfftn`, i.e. the inverse of the n-dimensional FFT
     of real input.
fft : The one-dimensional FFT, with definitions and conventions used.
rfft : The one-dimensional FFT of real input.
fftn : The n-dimensional FFT.
rfft2 : The two-dimensional FFT of real input.

Notes
-----
The transform for real input is performed over the last transformation
axis, as by `rfft`, then the transform over the remaining axes is
performed as by `fftn`.  The order of the output is as for `rfft` for the
final transformation axis, and as for `fftn` for the remaining
transformation axes.

See `fft` for details, definitions and conventions used.

Examples
--------
>>> a = np.ones((2, 2, 2))
>>> np.fft.rfftn(a)
array([[[ 8.+0.j,  0.+0.j],
        [ 0.+0.j,  0.+0.j]],
       [[ 0.+0.j,  0.+0.j],
        [ 0.+0.j,  0.+0.j]]])

>>> np.fft.rfftn(a, axes=(2, 0))
array([[[ 4.+0.j,  0.+0.j],
        [ 4.+0.j,  0.+0.j]],
       [[ 0.+0.j,  0.+0.j],
        [ 0.+0.j,  0.+0.j]]])


def rfft2(a, s=None, axes=(-<NUM_LIT:2>, -<NUM_LIT:1>)):

return rfftn(a, s, axes)<EOL>

Compute the 2-dimensional FFT of a real array.

Parameters
----------
a : array
    Input array, taken to be real.
s : sequence of ints, optional
    Shape of the FFT.
axes : sequence of ints, optional
    Axes over which to compute the FFT.

Returns
-------
out : ndarray
    The result of the real 2-D FFT.

See Also
--------
rfftn : Compute the N-dimensional discrete Fourier Transform for real
        input.

Notes
-----
This is really just `rfftn` with different default behavior.
For more details see `rfftn`.


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

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

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

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

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

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

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

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

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

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

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


def irfft2(a, s=None, axes=(-<NUM_LIT:2>, -<NUM_LIT:1>)):

return irfftn(a, s, axes)<EOL>

Compute the 2-dimensional inverse FFT of a real array.

Parameters
----------
a : array_like
    The input array
s : sequence of ints, optional
    Shape of the inverse FFT.
axes : sequence of ints, optional
    The axes over which to compute the inverse fft.
    Default is the last two axes.

Returns
-------
out : ndarray
    The result of the inverse real 2-D FFT.

See Also
--------
irfftn : Compute the inverse of the N-dimensional FFT of real input.

Notes
-----
This is really `irfftn` with different defaults.
For more details see `irfftn`.


def ndpointer(dtype=None, ndim=None, shape=None, flags=None):

if dtype is not None:<EOL><INDENT>dtype = _dtype(dtype)<EOL><DEDENT>num = None<EOL>if flags is not None:<EOL><INDENT>if isinstance(flags, str):<EOL><INDENT>flags = flags.split('<STR_LIT:U+002C>')<EOL><DEDENT>elif isinstance(flags, (int, integer)):<EOL><INDENT>num = flags<EOL>flags = _flags_fromnum(num)<EOL><DEDENT>elif isinstance(flags, flagsobj):<EOL><INDENT>num = flags.num<EOL>flags = _flags_fromnum(num)<EOL><DEDENT>if num is None:<EOL><INDENT>try:<EOL><INDENT>flags = [x.strip().upper() for x in flags]<EOL><DEDENT>except:<EOL><INDENT>raise TypeError("<STR_LIT>")<EOL><DEDENT>num = _num_fromflags(flags)<EOL><DEDENT><DEDENT>try:<EOL><INDENT>return _pointer_type_cache[(dtype, ndim, shape, num)]<EOL><DEDENT>except KeyError:<EOL><INDENT>pass<EOL><DEDENT>if dtype is None:<EOL><INDENT>name = '<STR_LIT>'<EOL><DEDENT>elif dtype.names:<EOL><INDENT>name = str(id(dtype))<EOL><DEDENT>else:<EOL><INDENT>name = dtype.str<EOL><DEDENT>if ndim is not None:<EOL><INDENT>name += "<STR_LIT>" % ndim<EOL><DEDENT>if shape is not None:<EOL><INDENT>try:<EOL><INDENT>strshape = [str(x) for x in shape]<EOL><DEDENT>except TypeError:<EOL><INDENT>strshape = [str(shape)]<EOL>shape = (shape,)<EOL><DEDENT>shape = tuple(shape)<EOL>name += "<STR_LIT:_>"+"<STR_LIT:x>".join(strshape)<EOL><DEDENT>if flags is not None:<EOL><INDENT>name += "<STR_LIT:_>"+"<STR_LIT:_>".join(flags)<EOL><DEDENT>else:<EOL><INDENT>flags = []<EOL><DEDENT>klass = type("<STR_LIT>"%name, (_ndptr,),<EOL>{"<STR_LIT>": dtype,<EOL>"<STR_LIT>" : shape,<EOL>"<STR_LIT>" : ndim,<EOL>"<STR_LIT>" : num})<EOL>_pointer_type_cache[dtype] = klass<EOL>return klass<EOL>

Array-checking restype/argtypes.

An ndpointer instance is used to describe an ndarray in restypes
and argtypes specifications.  This approach is more flexible than
using, for example, ``POINTER(c_double)``, since several restrictions
can be specified, which are verified upon calling the ctypes function.
These include data type, number of dimensions, shape and flags.  If a
given array does not satisfy the specified restrictions,
a ``TypeError`` is raised.

Parameters
----------
dtype : data-type, optional
    Array data-type.
ndim : int, optional
    Number of array dimensions.
shape : tuple of ints, optional
    Array shape.
flags : str or tuple of str
    Array flags; may be one or more of:

      - C_CONTIGUOUS / C / CONTIGUOUS
      - F_CONTIGUOUS / F / FORTRAN
      - OWNDATA / O
      - WRITEABLE / W
      - ALIGNED / A
      - UPDATEIFCOPY / U

Returns
-------
klass : ndpointer type object
    A type object, which is an ``_ndtpr`` instance containing
    dtype, ndim, shape and flags information.

Raises
------
TypeError
    If a given array does not satisfy the specified restrictions.

Examples
--------
>>> clib.somefunc.argtypes = [np.ctypeslib.ndpointer(dtype=np.float64,
...                                                  ndim=1,
...                                                  flags='C_CONTIGUOUS')]
... #doctest: +SKIP
>>> clib.somefunc(np.array([1, 2, 3], dtype=np.float64))
... #doctest: +SKIP


return array(self)<EOL>

This method is called when this class is used as the .restype
        asttribute for a shared-library function.   It constructs a numpy
        array from a void pointer.


if issubclass(arr.dtype.type, (nt.single, nt.byte, nt.short, nt.ubyte,<EOL>nt.ushort, nt.csingle)):<EOL><INDENT>return arr.astype(nt.csingle)<EOL><DEDENT>else:<EOL><INDENT>return arr.astype(nt.cdouble)<EOL><DEDENT>

Convert its input `arr` to a complex array.

    The input is returned as a complex array of the smallest type that will fit
    the original data: types like single, byte, short, etc. become csingle,
    while others become cdouble.

    A copy of the input is always made.

    Parameters
    ----------
    arr : array

    Returns
    -------
    array
        An array with the same input data as the input but in complex form.

    Examples
    --------

    First, consider an input of type short:

    >>> a = np.array([1,2,3],np.short)

    >>> ac = np.lib.scimath._tocomplex(a); ac
    array([ 1.+0.j,  2.+0.j,  3.+0.j], dtype=complex64)

    >>> ac.dtype
    dtype('complex64')

    If the input is of type double, the output is correspondingly of the
    complex double type as well:

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

    >>> bc = np.lib.scimath._tocomplex(b); bc
    array([ 1.+0.j,  2.+0.j,  3.+0.j])

    >>> bc.dtype
    dtype('complex128')

    Note that even if the input was complex to begin with, a copy is still
    made, since the astype() method always copies:

    >>> c = np.array([1,2,3],np.csingle)

    >>> cc = np.lib.scimath._tocomplex(c); cc
    array([ 1.+0.j,  2.+0.j,  3.+0.j], dtype=complex64)

    >>> c *= 2; c
    array([ 2.+0.j,  4.+0.j,  6.+0.j], dtype=complex64)

    >>> cc
    array([ 1.+0.j,  2.+0.j,  3.+0.j], dtype=complex64)


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

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

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

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

    Returns
    -------
    array

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

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


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

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

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

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

    Returns
    -------
    array

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

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


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

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

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

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

    Returns
    -------
    array

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

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


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

Compute the square root of x.

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

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

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

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

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

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

But it automatically handles negative inputs:

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


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

Compute the natural logarithm of `x`.

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

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

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

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

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

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

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

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


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

Compute the logarithm base 10 of `x`.

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

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

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

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

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

Examples
--------

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

>>> np.set_printoptions(precision=4)

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

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


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

Take log base n of x.

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

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

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

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

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


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

Compute the logarithm base 2 of `x`.

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

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

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

See Also
--------
numpy.log2

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

Examples
--------
We set the printing precision so the example can be auto-tested:

>>> np.set_printoptions(precision=4)

>>> np.emath.log2(8)
3.0
>>> np.emath.log2([-4, -8, 8])
array([ 2.+4.5324j,  3.+4.5324j,  3.+0.j    ])


x = _fix_real_lt_zero(x)<EOL>p = _fix_int_lt_zero(p)<EOL>return nx.power(x, p)<EOL>

Return x to the power p, (x**p).

If `x` contains negative values, the output is converted to the
complex domain.

Parameters
----------
x : array_like
    The input value(s).
p : array_like of ints
    The power(s) to which `x` is raised. If `x` contains multiple values,
    `p` has to either be a scalar, or contain the same number of values
    as `x`. In the latter case, the result is
    ``x[0]**p[0], x[1]**p[1], ...``.

Returns
-------
out : ndarray or scalar
    The result of ``x**p``. If `x` and `p` are scalars, so is `out`,
    otherwise an array is returned.

See Also
--------
numpy.power

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

>>> np.lib.scimath.power([2, 4], 2)
array([ 4, 16])
>>> np.lib.scimath.power([2, 4], -2)
array([ 0.25  ,  0.0625])
>>> np.lib.scimath.power([-2, 4], 2)
array([  4.+0.j,  16.+0.j])


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

Compute the inverse cosine of x.

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

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

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

See Also
--------
numpy.arccos

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

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

>>> np.emath.arccos(1) # a scalar is returned
0.0

>>> np.emath.arccos([1,2])
array([ 0.-0.j   ,  0.+1.317j])


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

Compute the inverse sine of x.

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

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

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

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

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

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

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

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


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

Compute the inverse hyperbolic tangent of `x`.

Return the "principal value" (for a description of this, see
`numpy.arctanh`) of `arctanh(x)`. For real `x` such that
`abs(x) < 1`, this is a real number.  If `abs(x) > 1`, or if `x` is
complex, the result is complex. Finally, `x = 1` returns``inf`` and
`x=-1` returns ``-inf``.

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

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

See Also
--------
numpy.arctanh

Notes
-----
For an arctanh() that returns ``NAN`` when real `x` is not in the
interval ``(-1,1)``, use `numpy.arctanh` (this latter, however, does
return +/-inf for `x = +/-1`).

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

>>> np.emath.arctanh(np.matrix(np.eye(2)))
array([[ Inf,   0.],
       [  0.,  Inf]])
>>> np.emath.arctanh([1j])
array([ 0.+0.7854j])


def open(path, mode='<STR_LIT:r>', destpath=os.curdir):

ds = DataSource(destpath)<EOL>return ds.open(path, mode)<EOL>

Open `path` with `mode` and return the file object.

If ``path`` is an URL, it will be downloaded, stored in the
`DataSource` `destpath` directory and opened from there.

Parameters
----------
path : str
    Local file path or URL to open.
mode : str, optional
    Mode to open `path`. Mode 'r' for reading, 'w' for writing, 'a' to
    append. Available modes depend on the type of object specified by
    path.  Default is 'r'.
destpath : str, optional
    Path to the directory where the source file gets downloaded to for
    use.  If `destpath` is None, a temporary directory will be created.
    The default path is the current directory.

Returns
-------
out : file object
    The opened file.

Notes
-----
This is a convenience function that instantiates a `DataSource` and
returns the file object from ``DataSource.open(path)``.


self._load()<EOL>return list(self._file_openers.keys())<EOL>

Return the keys of currently supported file openers.

Parameters
----------
None

Returns
-------
keys : list
    The keys are None for uncompressed files and the file extension
    strings (i.e. ``'.gz'``, ``'.bz2'``) for supported compression
    methods.


if destpath:<EOL><INDENT>self._destpath = os.path.abspath(destpath)<EOL>self._istmpdest = False<EOL><DEDENT>else:<EOL><INDENT>import tempfile  <EOL>self._destpath = tempfile.mkdtemp()<EOL>self._istmpdest = True<EOL><DEDENT>

Create a DataSource with a local path at destpath.


fname, ext = os.path.splitext(filename)<EOL>return ext in _file_openers.keys()<EOL>

Test if the filename is a zip file by looking at the file extension.


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

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


if self._iszip(filename):<EOL><INDENT>return os.path.splitext(filename)<EOL><DEDENT>else:<EOL><INDENT>return filename, None<EOL><DEDENT>

Split zip extension from filename and return filename.

        *Returns*:
            base, zip_ext : {tuple}


names = [filename]<EOL>if not self._iszip(filename):<EOL><INDENT>for zipext in _file_openers.keys():<EOL><INDENT>if zipext:<EOL><INDENT>names.append(filename+zipext)<EOL><DEDENT><DEDENT><DEDENT>return names<EOL>

Return a tuple containing compressed filename variations.


<EOL>if sys.version_info[<NUM_LIT:0>] >= <NUM_LIT:3>:<EOL><INDENT>from urllib.parse import urlparse<EOL><DEDENT>else:<EOL><INDENT>from urlparse import urlparse<EOL><DEDENT>scheme, netloc, upath, uparams, uquery, ufrag = urlparse(path)<EOL>return bool(scheme and netloc)<EOL>

Test if path is a net location.  Tests the scheme and netloc.


<EOL>if sys.version_info[<NUM_LIT:0>] >= <NUM_LIT:3>:<EOL><INDENT>from urllib.request import urlopen<EOL>from urllib.error import URLError<EOL><DEDENT>else:<EOL><INDENT>from urllib2 import urlopen<EOL>from urllib2 import URLError<EOL><DEDENT>upath = self.abspath(path)<EOL>if not os.path.exists(os.path.dirname(upath)):<EOL><INDENT>os.makedirs(os.path.dirname(upath))<EOL><DEDENT>if self._isurl(path):<EOL><INDENT>try:<EOL><INDENT>openedurl = urlopen(path)<EOL>f = _open(upath, '<STR_LIT:wb>')<EOL>try:<EOL><INDENT>shutil.copyfileobj(openedurl, f)<EOL><DEDENT>finally:<EOL><INDENT>f.close()<EOL>openedurl.close()<EOL><DEDENT><DEDENT>except URLError:<EOL><INDENT>raise URLError("<STR_LIT>" % path)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>shutil.copyfile(path, upath)<EOL><DEDENT>return upath<EOL>

Cache the file specified by path.

        Creates a copy of the file in the datasource cache.


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

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

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

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


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

Return absolute path of file in the DataSource directory.

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

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

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

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


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

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


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

Test if path exists.

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

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

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

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

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


def open(self, path, mode='<STR_LIT:r>'):

<EOL>if self._isurl(path) and self._iswritemode(mode):<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>found = self._findfile(path)<EOL>if found:<EOL><INDENT>_fname, ext = self._splitzipext(found)<EOL>if ext == '<STR_LIT>':<EOL><INDENT>mode.replace("<STR_LIT:+>", "<STR_LIT>")<EOL><DEDENT>return _file_openers[ext](found, mode=mode)<EOL><DEDENT>else:<EOL><INDENT>raise IOError("<STR_LIT>" % path)<EOL><DEDENT>

Open and return file-like object.

If `path` is an URL, it will be downloaded, stored in the
`DataSource` directory and opened from there.

Parameters
----------
path : str
    Local file path or URL to open.
mode : {'r', 'w', 'a'}, optional
    Mode to open `path`.  Mode 'r' for reading, 'w' for writing,
    'a' to append. Available modes depend on the type of object
    specified by `path`. Default is 'r'.

Returns
-------
out : file object
    File object.


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

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

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


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

Return complete path for path.  Prepends baseurl if necessary.


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

Extend DataSource method to prepend baseurl to ``path``.


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

Return absolute path of file in the Repository directory.

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

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

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


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

Test if path exists prepending Repository base URL to path.

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

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

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

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

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


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

Open and return file-like object prepending Repository base URL.

If `path` is an URL, it will be downloaded, stored in the
DataSource directory and opened from there.

Parameters
----------
path : str
    Local file path or URL to open. This may, but does not have to,
    include the `baseurl` with which the `Repository` was
    initialized.
mode : {'r', 'w', 'a'}, optional
    Mode to open `path`.  Mode 'r' for reading, 'w' for writing,
    'a' to append. Available modes depend on the type of object
    specified by `path`. Default is 'r'.

Returns
-------
out : file object
    File object.


if self._isurl(self._baseurl):<EOL><INDENT>raise NotImplementedError(<EOL>"<STR_LIT>")<EOL><DEDENT>else:<EOL><INDENT>return os.listdir(self._baseurl)<EOL><DEDENT>

List files in the source Repository.

Returns
-------
files : list of str
    List of file names (not containing a directory part).

Notes
-----
Does not currently work for remote repositories.


if sys.version_info[<NUM_LIT:0>] >= <NUM_LIT:3>:<EOL><INDENT>return datetime(*time.strptime(s.decode('<STR_LIT>'), fmt)[:<NUM_LIT:3>])<EOL><DEDENT>else:<EOL><INDENT>return datetime(*time.strptime(s, fmt)[:<NUM_LIT:3>])<EOL><DEDENT>

This function is available in the datetime module only
    from Python >= 2.5.


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

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

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


if url == valid_httpurl():<EOL><INDENT>tmpfile = NamedTemporaryFile(prefix='<STR_LIT>')<EOL>return tmpfile<EOL><DEDENT>else:<EOL><INDENT>raise URLError('<STR_LIT>')<EOL><DEDENT>


out = []<EOL>nd = len(args)<EOL>baseshape = [<NUM_LIT:1>]*nd<EOL>for k in range(nd):<EOL><INDENT>new = _nx.asarray(args[k])<EOL>if (new.ndim != <NUM_LIT:1>):<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if issubclass(new.dtype.type, _nx.bool_):<EOL><INDENT>new = new.nonzero()[<NUM_LIT:0>]<EOL><DEDENT>baseshape[k] = len(new)<EOL>new = new.reshape(tuple(baseshape))<EOL>out.append(new)<EOL>baseshape[k] = <NUM_LIT:1><EOL><DEDENT>return tuple(out)<EOL>

Construct an open mesh from multiple sequences.

This function takes N 1-D sequences and returns N outputs with N
dimensions each, such that the shape is 1 in all but one dimension
and the dimension with the non-unit shape value cycles through all
N dimensions.

Using `ix_` one can quickly construct index arrays that will index
the cross product. ``a[np.ix_([1,3],[2,5])]`` returns the array
``[[a[1,2] a[1,5]], [a[3,2] a[3,5]]]``.

Parameters
----------
args : 1-D sequences

Returns
-------
out : tuple of ndarrays
    N arrays with N dimensions each, with N the number of input
    sequences. Together these arrays form an open mesh.

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

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


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

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

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

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

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

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

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

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

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

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

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

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

    We only show a few blocks for clarity:

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

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

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

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


idx = arange(n)<EOL>return (idx,) * ndim<EOL>

Return the indices to access the main diagonal of an array.

This returns a tuple of indices that can be used to access the main
diagonal of an array `a` with ``a.ndim >= 2`` dimensions and shape
(n, n, ..., n). For ``a.ndim = 2`` this is the usual diagonal, for
``a.ndim > 2`` this is the set of indices to access ``a[i, i, ..., i]``
for ``i = [0..n-1]``.

Parameters
----------
n : int
  The size, along each dimension, of the arrays for which the returned
  indices can be used.

ndim : int, optional
  The number of dimensions.

See also
--------
diag_indices_from

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

Examples
--------
Create a set of indices to access the diagonal of a (4, 4) array:

>>> di = np.diag_indices(4)
>>> di
(array([0, 1, 2, 3]), array([0, 1, 2, 3]))
>>> 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]])
>>> a[di] = 100
>>> a
array([[100,   1,   2,   3],
       [  4, 100,   6,   7],
       [  8,   9, 100,  11],
       [ 12,  13,  14, 100]])

Now, we create indices to manipulate a 3-D array:

>>> d3 = np.diag_indices(2, 3)
>>> d3
(array([0, 1]), array([0, 1]), array([0, 1]))

And use it to set the diagonal of an array of zeros to 1:

>>> a = np.zeros((2, 2, 2), dtype=np.int)
>>> a[d3] = 1
>>> a
array([[[1, 0],
        [0, 0]],
       [[0, 0],
        [0, 1]]])


if not arr.ndim >= <NUM_LIT:2>:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if not alltrue(diff(arr.shape) == <NUM_LIT:0>):<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>return diag_indices(arr.shape[<NUM_LIT:0>], arr.ndim)<EOL>

Return the indices to access the main diagonal of an n-dimensional array.

See `diag_indices` for full details.

Parameters
----------
arr : array, at least 2-D

See Also
--------
diag_indices

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


return self.iter.coords, next(self.iter)<EOL>

Standard iterator method, returns the index tuple and array value.

Returns
-------
coords : tuple of ints
    The indices of the current iteration.
val : scalar
    The array element of the current iteration.


next(self)<EOL>

Increment the multi-dimensional index by one.

This method is for backward compatibility only: do not use.


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

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

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


def _arange_ndarray(arr, shape, axis, reverse=False):

initshape = tuple(<NUM_LIT:1> if i != axis else shape[axis]<EOL>for (i, x) in enumerate(arr.shape))<EOL>if not reverse:<EOL><INDENT>padarr = np.arange(<NUM_LIT:1>, shape[axis] + <NUM_LIT:1>)<EOL><DEDENT>else:<EOL><INDENT>padarr = np.arange(shape[axis], <NUM_LIT:0>, -<NUM_LIT:1>)<EOL><DEDENT>padarr = padarr.reshape(initshape)<EOL>for i, dim in enumerate(shape):<EOL><INDENT>if padarr.shape[i] != dim:<EOL><INDENT>padarr = padarr.repeat(dim, axis=i)<EOL><DEDENT><DEDENT>return padarr<EOL>

Create an ndarray of `shape` with increments along specified `axis`

Parameters
----------
arr : ndarray
    Input array of arbitrary shape.
shape : tuple of ints
    Shape of desired array. Should be equivalent to `arr.shape` except
    `shape[axis]` which may have any positive value.
axis : int
    Axis to increment along.
reverse : bool
    If False, increment in a positive fashion from 1 to `shape[axis]`,
    inclusive. If True, the bounds are the same but the order reversed.

Returns
-------
padarr : ndarray
    Output array sized to pad `arr` along `axis`, with linear range from
    1 to `shape[axis]` along specified `axis`.

Notes
-----
The range is deliberately 1-indexed for this specific use case. Think of
this algorithm as broadcasting `np.arange` to a single `axis` of an
arbitrarily shaped ndarray.


if np.issubdtype(dtype, np.integer):<EOL><INDENT>arr.round(out=arr)<EOL><DEDENT>

Rounds arr inplace if destination dtype is integer.

Parameters
----------
arr : ndarray
    Input array.
dtype : dtype
    The dtype of the destination array.


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

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

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

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

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


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

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

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

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

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


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

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

Prepend `pad_amt` to `arr` along `axis` by extending edge values.

Parameters
----------
arr : ndarray
    Input array of arbitrary shape.
pad_amt : int
    Amount of padding to prepend.
axis : int
    Axis along which to pad `arr`.

Returns
-------
padarr : ndarray
    Output array, extended by `pad_amt` edge values appended along `axis`.


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

if pad_amt == <NUM_LIT:0>:<EOL><INDENT>return arr<EOL><DEDENT>edge_slice = tuple(slice(None) if i != axis else arr.shape[axis] - <NUM_LIT:1><EOL>for (i, x) in enumerate(arr.shape))<EOL>pad_singleton = tuple(x if i != axis else <NUM_LIT:1><EOL>for (i, x) in enumerate(arr.shape))<EOL>edge_arr = arr[edge_slice].reshape(pad_singleton)<EOL>return np.concatenate((arr, edge_arr.repeat(pad_amt, axis=axis)),<EOL>axis=axis)<EOL>

Append `pad_amt` to `arr` along `axis` by extending edge values.

Parameters
----------
arr : ndarray
    Input array of arbitrary shape.
pad_amt : int
    Amount of padding to append.
axis : int
    Axis along which to pad `arr`.

Returns
-------
padarr : ndarray
    Output array, extended by `pad_amt` edge values prepended along
    `axis`.


def _prepend_ramp(arr, pad_amt, end, axis=-<NUM_LIT:1>):

if pad_amt == <NUM_LIT:0>:<EOL><INDENT>return arr<EOL><DEDENT>padshape = tuple(x if i != axis else pad_amt<EOL>for (i, x) in enumerate(arr.shape))<EOL>ramp_arr = _arange_ndarray(arr, padshape, axis,<EOL>reverse=True).astype(np.float64)<EOL>edge_slice = tuple(slice(None) if i != axis else <NUM_LIT:0><EOL>for (i, x) in enumerate(arr.shape))<EOL>pad_singleton = tuple(x if i != axis else <NUM_LIT:1><EOL>for (i, x) in enumerate(arr.shape))<EOL>edge_pad = arr[edge_slice].reshape(pad_singleton).repeat(pad_amt, axis)<EOL>slope = (end - edge_pad) / float(pad_amt)<EOL>ramp_arr = ramp_arr * slope<EOL>ramp_arr += edge_pad<EOL>_round_ifneeded(ramp_arr, arr.dtype)<EOL>return np.concatenate((ramp_arr.astype(arr.dtype), arr), axis=axis)<EOL>

Prepend linear ramp along `axis`.

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

Returns
-------
padarr : ndarray
    Output array, with `pad_amt` values prepended along `axis`. The
    prepended region ramps linearly from the edge value to `end`.


def _append_ramp(arr, pad_amt, end, axis=-<NUM_LIT:1>):

if pad_amt == <NUM_LIT:0>:<EOL><INDENT>return arr<EOL><DEDENT>padshape = tuple(x if i != axis else pad_amt<EOL>for (i, x) in enumerate(arr.shape))<EOL>ramp_arr = _arange_ndarray(arr, padshape, axis,<EOL>reverse=False).astype(np.float64)<EOL>edge_slice = tuple(slice(None) if i != axis else -<NUM_LIT:1><EOL>for (i, x) in enumerate(arr.shape))<EOL>pad_singleton = tuple(x if i != axis else <NUM_LIT:1><EOL>for (i, x) in enumerate(arr.shape))<EOL>edge_pad = arr[edge_slice].reshape(pad_singleton).repeat(pad_amt, axis)<EOL>slope = (end - edge_pad) / float(pad_amt)<EOL>ramp_arr = ramp_arr * slope<EOL>ramp_arr += edge_pad<EOL>_round_ifneeded(ramp_arr, arr.dtype)<EOL>return np.concatenate((arr, ramp_arr.astype(arr.dtype)), axis=axis)<EOL>

Append linear ramp along `axis`.

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

Returns
-------
padarr : ndarray
    Output array, with `pad_amt` values appended along `axis`. The
    appended region ramps linearly from the edge value to `end`.


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

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

Prepend `pad_amt` maximum values along `axis`.

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

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


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

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

Pad one `axis` of `arr` with the maximum of the last `num` elements.

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

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


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

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

Prepend `pad_amt` mean values along `axis`.

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

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


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

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

Append `pad_amt` mean values along `axis`.

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

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


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

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

Prepend `pad_amt` median values along `axis`.

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

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


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

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

Append `pad_amt` median values along `axis`.

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

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


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

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

Prepend `pad_amt` minimum values along `axis`.

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

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


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

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

Append `pad_amt` median values along `axis`.

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

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