image = asarray(input)<EOL>if kernel_size is None:<EOL><INDENT>kernel_size = [<NUM_LIT:3>] * <NUM_LIT:2><EOL><DEDENT>kernel_size = asarray(kernel_size)<EOL>if kernel_size.shape == ():<EOL><INDENT>kernel_size = np.repeat(kernel_size.item(), <NUM_LIT:2>)<EOL><DEDENT>for size in kernel_size:<EOL><INDENT>if (size % <NUM_LIT:2>) != <NUM_LIT:1>:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT><DEDENT>return sigtools._medfilt2d(image, kernel_size)<EOL>

Median filter a 2-dimensional array.

Apply a median filter to the `input` array using a local window-size
given by `kernel_size` (must be odd).

Parameters
----------
input : array_like
    A 2-dimensional input array.
kernel_size : array_like, optional
    A scalar or a list of length 2, giving the size of the
    median filter window in each dimension.  Elements of
    `kernel_size` should be odd.  If `kernel_size` is a scalar,
    then this scalar is used as the size in each dimension.
    Default is a kernel of size (3, 3).

Returns
-------
out : ndarray
    An array the same size as input containing the median filtered
    result.


def lfilter(b, a, x, axis=-<NUM_LIT:1>, zi=None):

if isscalar(a):<EOL><INDENT>a = [a]<EOL><DEDENT>if zi is None:<EOL><INDENT>return sigtools._linear_filter(b, a, x, axis)<EOL><DEDENT>else:<EOL><INDENT>return sigtools._linear_filter(b, a, x, axis, zi)<EOL><DEDENT>

Filter data along one-dimension with an IIR or FIR filter.

Filter a data sequence, `x`, using a digital filter.  This works for many
fundamental data types (including Object type).  The filter is a direct
form II transposed implementation of the standard difference equation
(see Notes).

Parameters
----------
b : array_like
    The numerator coefficient vector in a 1-D sequence.
a : array_like
    The denominator coefficient vector in a 1-D sequence.  If ``a[0]``
    is not 1, then both `a` and `b` are normalized by ``a[0]``.
x : array_like
    An N-dimensional input array.
axis : int
    The axis of the input data array along which to apply the
    linear filter. The filter is applied to each subarray along
    this axis.  Default is -1.
zi : array_like, optional
    Initial conditions for the filter delays.  It is a vector
    (or array of vectors for an N-dimensional input) of length
    ``max(len(a),len(b))-1``.  If `zi` is None or is not given then
    initial rest is assumed.  See `lfiltic` for more information.

Returns
-------
y : array
    The output of the digital filter.
zf : array, optional
    If `zi` is None, this is not returned, otherwise, `zf` holds the
    final filter delay values.

Notes
-----
The filter function is implemented as a direct II transposed structure.
This means that the filter implements::

   a[0]*y[n] = b[0]*x[n] + b[1]*x[n-1] + ... + b[nb]*x[n-nb]
                           - a[1]*y[n-1] - ... - a[na]*y[n-na]

using the following difference equations::

     y[m] = b[0]*x[m] + z[0,m-1]
     z[0,m] = b[1]*x[m] + z[1,m-1] - a[1]*y[m]
     ...
     z[n-3,m] = b[n-2]*x[m] + z[n-2,m-1] - a[n-2]*y[m]
     z[n-2,m] = b[n-1]*x[m] - a[n-1]*y[m]

where m is the output sample number and n=max(len(a),len(b)) is the
model order.

The rational transfer function describing this filter in the
z-transform domain is::

                         -1               -nb
             b[0] + b[1]z  + ... + b[nb] z
     Y(z) = ---------------------------------- X(z)
                         -1               -na
             a[0] + a[1]z  + ... + a[na] z


N = np.size(a) - <NUM_LIT:1><EOL>M = np.size(b) - <NUM_LIT:1><EOL>K = max(M, N)<EOL>y = asarray(y)<EOL>if y.dtype.kind in '<STR_LIT>':<EOL><INDENT>y = y.astype(np.float64)<EOL><DEDENT>zi = zeros(K, y.dtype)<EOL>if x is None:<EOL><INDENT>x = zeros(M, y.dtype)<EOL><DEDENT>else:<EOL><INDENT>x = asarray(x)<EOL>L = np.size(x)<EOL>if L < M:<EOL><INDENT>x = r_[x, zeros(M - L)]<EOL><DEDENT><DEDENT>L = np.size(y)<EOL>if L < N:<EOL><INDENT>y = r_[y, zeros(N - L)]<EOL><DEDENT>for m in range(M):<EOL><INDENT>zi[m] = sum(b[m + <NUM_LIT:1>:] * x[:M - m], axis=<NUM_LIT:0>)<EOL><DEDENT>for m in range(N):<EOL><INDENT>zi[m] -= sum(a[m + <NUM_LIT:1>:] * y[:N - m], axis=<NUM_LIT:0>)<EOL><DEDENT>return zi<EOL>

Construct initial conditions for lfilter.

Given a linear filter (b, a) and initial conditions on the output `y`
and the input `x`, return the initial conditions on the state vector zi
which is used by `lfilter` to generate the output given the input.

Parameters
----------
b : array_like
    Linear filter term.
a : array_like
    Linear filter term.
y : array_like
    Initial conditions.

    If ``N=len(a) - 1``, then ``y = {y[-1], y[-2], ..., y[-N]}``.

    If `y` is too short, it is padded with zeros.
x : array_like, optional
    Initial conditions.

    If ``M=len(b) - 1``, then ``x = {x[-1], x[-2], ..., x[-M]}``.

    If `x` is not given, its initial conditions are assumed zero.

    If `x` is too short, it is padded with zeros.

Returns
-------
zi : ndarray
    The state vector ``zi``.
    ``zi = {z_0[-1], z_1[-1], ..., z_K-1[-1]}``, where ``K = max(M,N)``.

See Also
--------
lfilter


num = atleast_1d(signal)<EOL>den = atleast_1d(divisor)<EOL>N = len(num)<EOL>D = len(den)<EOL>if D > N:<EOL><INDENT>quot = []<EOL>rem = num<EOL><DEDENT>else:<EOL><INDENT>input = ones(N - D + <NUM_LIT:1>, float)<EOL>input[<NUM_LIT:1>:] = <NUM_LIT:0><EOL>quot = lfilter(num, den, input)<EOL>rem = num - convolve(den, quot, mode='<STR_LIT>')<EOL><DEDENT>return quot, rem<EOL>

Deconvolves `divisor` out of `signal`.

    Returns the quotient and remainder such that
    ``signal = convolve(divisor, quotient) + remainder``

    Parameters
    ----------
    signal : array_like
        Signal data, typically a recorded signal
    divisor : array_like
        Divisor data, typically an impulse response or filter that was
        applied to the original signal

    Returns
    -------
    quotient : ndarray
        Quotient, typically the recovered original signal
    remainder : ndarray
        Remainder

    Examples
    --------
    Deconvolve a signal that's been filtered:

    >>> from scipy import signal
    >>> original = [0, 1, 0, 0, 1, 1, 0, 0]
    >>> impulse_response = [2, 1]
    >>> recorded = signal.convolve(impulse_response, original)
    >>> recorded
    array([0, 2, 1, 0, 2, 3, 1, 0, 0])
    >>> recovered, remainder = signal.deconvolve(recorded, impulse_response)
    >>> recovered
    array([ 0.,  1.,  0.,  0.,  1.,  1.,  0.,  0.])

    See also
    --------
    numpy.polydiv : performs polynomial division (same operation, but
                    also accepts poly1d objects)


def hilbert(x, N=None, axis=-<NUM_LIT:1>):

x = asarray(x)<EOL>if iscomplexobj(x):<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if N is None:<EOL><INDENT>N = x.shape[axis]<EOL><DEDENT>if N <= <NUM_LIT:0>:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>Xf = fft(x, N, axis=axis)<EOL>h = zeros(N)<EOL>if N % <NUM_LIT:2> == <NUM_LIT:0>:<EOL><INDENT>h[<NUM_LIT:0>] = h[N // <NUM_LIT:2>] = <NUM_LIT:1><EOL>h[<NUM_LIT:1>:N // <NUM_LIT:2>] = <NUM_LIT:2><EOL><DEDENT>else:<EOL><INDENT>h[<NUM_LIT:0>] = <NUM_LIT:1><EOL>h[<NUM_LIT:1>:(N + <NUM_LIT:1>) // <NUM_LIT:2>] = <NUM_LIT:2><EOL><DEDENT>if len(x.shape) > <NUM_LIT:1>:<EOL><INDENT>ind = [newaxis] * x.ndim<EOL>ind[axis] = slice(None)<EOL>h = h[ind]<EOL><DEDENT>x = ifft(Xf * h, axis=axis)<EOL>return x<EOL>

Compute the analytic signal, using the Hilbert transform.

The transformation is done along the last axis by default.

Parameters
----------
x : array_like
    Signal data.  Must be real.
N : int, optional
    Number of Fourier components.  Default: ``x.shape[axis]``
axis : int, optional
    Axis along which to do the transformation.  Default: -1.

Returns
-------
xa : ndarray
    Analytic signal of `x`, of each 1-D array along `axis`

Notes
-----
The analytic signal ``x_a(t)`` of signal ``x(t)`` is:

.. math:: x_a = F^{-1}(F(x) 2U) = x + i y

where `F` is the Fourier transform, `U` the unit step function,
and `y` the Hilbert transform of `x`. [1]_

In other words, the negative half of the frequency spectrum is zeroed
out, turning the real-valued signal into a complex signal.  The Hilbert
transformed signal can be obtained from ``np.imag(hilbert(x))``, and the
original signal from ``np.real(hilbert(x))``.

References
----------
.. [1] Wikipedia, "Analytic signal".
       http://en.wikipedia.org/wiki/Analytic_signal


x = atleast_2d(x)<EOL>if len(x.shape) > <NUM_LIT:2>:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if iscomplexobj(x):<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if N is None:<EOL><INDENT>N = x.shape<EOL><DEDENT>elif isinstance(N, int):<EOL><INDENT>if N <= <NUM_LIT:0>:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>N = (N, N)<EOL><DEDENT>elif len(N) != <NUM_LIT:2> or np.any(np.asarray(N) <= <NUM_LIT:0>):<EOL><INDENT>raise ValueError("<STR_LIT>"<EOL>"<STR_LIT>")<EOL><DEDENT>Xf = fft2(x, N, axes=(<NUM_LIT:0>, <NUM_LIT:1>))<EOL>h1 = zeros(N[<NUM_LIT:0>], '<STR_LIT:d>')<EOL>h2 = zeros(N[<NUM_LIT:1>], '<STR_LIT:d>')<EOL>for p in range(<NUM_LIT:2>):<EOL><INDENT>h = eval("<STR_LIT>" % (p + <NUM_LIT:1>))<EOL>N1 = N[p]<EOL>if N1 % <NUM_LIT:2> == <NUM_LIT:0>:<EOL><INDENT>h[<NUM_LIT:0>] = h[N1 // <NUM_LIT:2>] = <NUM_LIT:1><EOL>h[<NUM_LIT:1>:N1 // <NUM_LIT:2>] = <NUM_LIT:2><EOL><DEDENT>else:<EOL><INDENT>h[<NUM_LIT:0>] = <NUM_LIT:1><EOL>h[<NUM_LIT:1>:(N1 + <NUM_LIT:1>) // <NUM_LIT:2>] = <NUM_LIT:2><EOL><DEDENT>exec("<STR_LIT>" % (p + <NUM_LIT:1>), globals(), locals())<EOL><DEDENT>h = h1[:, newaxis] * h2[newaxis, :]<EOL>k = len(x.shape)<EOL>while k > <NUM_LIT:2>:<EOL><INDENT>h = h[:, newaxis]<EOL>k -= <NUM_LIT:1><EOL><DEDENT>x = ifft2(Xf * h, axes=(<NUM_LIT:0>, <NUM_LIT:1>))<EOL>return x<EOL>

Compute the '2-D' analytic signal of `x`

Parameters
----------
x : array_like
    2-D signal data.
N : int or tuple of two ints, optional
    Number of Fourier components. Default is ``x.shape``

Returns
-------
xa : ndarray
    Analytic signal of `x` taken along axes (0,1).

References
----------
.. [1] Wikipedia, "Analytic signal",
    http://en.wikipedia.org/wiki/Analytic_signal


p = asarray(p)<EOL>if iscomplexobj(p):<EOL><INDENT>indx = argsort(abs(p))<EOL><DEDENT>else:<EOL><INDENT>indx = argsort(p)<EOL><DEDENT>return take(p, indx, <NUM_LIT:0>), indx<EOL>

Sort roots based on magnitude.

    Parameters
    ----------
    p : array_like
        The roots to sort, as a 1-D array.

    Returns
    -------
    p_sorted : ndarray
        Sorted roots.
    indx : ndarray
        Array of indices needed to sort the input `p`.


def unique_roots(p, tol=<NUM_LIT>, rtype='<STR_LIT>'):

if rtype in ['<STR_LIT>', '<STR_LIT>']:<EOL><INDENT>comproot = np.max<EOL><DEDENT>elif rtype in ['<STR_LIT>', '<STR_LIT>']:<EOL><INDENT>comproot = np.min<EOL><DEDENT>elif rtype in ['<STR_LIT>', '<STR_LIT>']:<EOL><INDENT>comproot = np.mean<EOL><DEDENT>else:<EOL><INDENT>raise ValueError("<STR_LIT>"<EOL>"<STR_LIT>")<EOL><DEDENT>p = asarray(p) * <NUM_LIT:1.0><EOL>tol = abs(tol)<EOL>p, indx = cmplx_sort(p)<EOL>pout = []<EOL>mult = []<EOL>indx = -<NUM_LIT:1><EOL>curp = p[<NUM_LIT:0>] + <NUM_LIT:5> * tol<EOL>sameroots = []<EOL>for k in range(len(p)):<EOL><INDENT>tr = p[k]<EOL>if abs(tr - curp) < tol:<EOL><INDENT>sameroots.append(tr)<EOL>curp = comproot(sameroots)<EOL>pout[indx] = curp<EOL>mult[indx] += <NUM_LIT:1><EOL><DEDENT>else:<EOL><INDENT>pout.append(tr)<EOL>curp = tr<EOL>sameroots = [tr]<EOL>indx += <NUM_LIT:1><EOL>mult.append(<NUM_LIT:1>)<EOL><DEDENT><DEDENT>return array(pout), array(mult)<EOL>

Determine unique roots and their multiplicities from a list of roots.

Parameters
----------
p : array_like
    The list of roots.
tol : float, optional
    The tolerance for two roots to be considered equal. Default is 1e-3.
rtype : {'max', 'min, 'avg'}, optional
    How to determine the returned root if multiple roots are within
    `tol` of each other.

      - 'max': pick the maximum of those roots.
      - 'min': pick the minimum of those roots.
      - 'avg': take the average of those roots.

Returns
-------
pout : ndarray
    The list of unique roots, sorted from low to high.
mult : ndarray
    The multiplicity of each root.

Notes
-----
This utility function is not specific to roots but can be used for any
sequence of values for which uniqueness and multiplicity has to be
determined. For a more general routine, see `numpy.unique`.

Examples
--------
>>> from scipy import signal
>>> vals = [0, 1.3, 1.31, 2.8, 1.25, 2.2, 10.3]
>>> uniq, mult = signal.unique_roots(vals, tol=2e-2, rtype='avg')

Check which roots have multiplicity larger than 1:

>>> uniq[mult > 1]
array([ 1.305])


def invres(r, p, k, tol=<NUM_LIT>, rtype='<STR_LIT>'):

extra = k<EOL>p, indx = cmplx_sort(p)<EOL>r = take(r, indx, <NUM_LIT:0>)<EOL>pout, mult = unique_roots(p, tol=tol, rtype=rtype)<EOL>p = []<EOL>for k in range(len(pout)):<EOL><INDENT>p.extend([pout[k]] * mult[k])<EOL><DEDENT>a = atleast_1d(poly(p))<EOL>if len(extra) > <NUM_LIT:0>:<EOL><INDENT>b = polymul(extra, a)<EOL><DEDENT>else:<EOL><INDENT>b = [<NUM_LIT:0>]<EOL><DEDENT>indx = <NUM_LIT:0><EOL>for k in range(len(pout)):<EOL><INDENT>temp = []<EOL>for l in range(len(pout)):<EOL><INDENT>if l != k:<EOL><INDENT>temp.extend([pout[l]] * mult[l])<EOL><DEDENT><DEDENT>for m in range(mult[k]):<EOL><INDENT>t2 = temp[:]<EOL>t2.extend([pout[k]] * (mult[k] - m - <NUM_LIT:1>))<EOL>b = polyadd(b, r[indx] * poly(t2))<EOL>indx += <NUM_LIT:1><EOL><DEDENT><DEDENT>b = real_if_close(b)<EOL>while allclose(b[<NUM_LIT:0>], <NUM_LIT:0>, rtol=<NUM_LIT>) and (b.shape[-<NUM_LIT:1>] > <NUM_LIT:1>):<EOL><INDENT>b = b[<NUM_LIT:1>:]<EOL><DEDENT>return b, a<EOL>

Compute b(s) and a(s) from partial fraction expansion.

If ``M = len(b)`` and ``N = len(a)``::

            b(s)     b[0] x**(M-1) + b[1] x**(M-2) + ... + b[M-1]
    H(s) = ------ = ----------------------------------------------
            a(s)     a[0] x**(N-1) + a[1] x**(N-2) + ... + a[N-1]

             r[0]       r[1]             r[-1]
         = -------- + -------- + ... + --------- + k(s)
           (s-p[0])   (s-p[1])         (s-p[-1])

If there are any repeated roots (closer than tol), then the partial
fraction expansion has terms like::

      r[i]      r[i+1]              r[i+n-1]
    -------- + ----------- + ... + -----------
    (s-p[i])  (s-p[i])**2          (s-p[i])**n

Parameters
----------
r : ndarray
    Residues.
p : ndarray
    Poles.
k : ndarray
    Coefficients of the direct polynomial term.
tol : float, optional
    The tolerance for two roots to be considered equal. Default is 1e-3.
rtype : {'max', 'min, 'avg'}, optional
    How to determine the returned root if multiple roots are within
    `tol` of each other.

      'max': pick the maximum of those roots.

      'min': pick the minimum of those roots.

      'avg': take the average of those roots.

See Also
--------
residue, unique_roots


def residue(b, a, tol=<NUM_LIT>, rtype='<STR_LIT>'):

b, a = map(asarray, (b, a))<EOL>rscale = a[<NUM_LIT:0>]<EOL>k, b = polydiv(b, a)<EOL>p = roots(a)<EOL>r = p * <NUM_LIT:0.0><EOL>pout, mult = unique_roots(p, tol=tol, rtype=rtype)<EOL>p = []<EOL>for n in range(len(pout)):<EOL><INDENT>p.extend([pout[n]] * mult[n])<EOL><DEDENT>p = asarray(p)<EOL>indx = <NUM_LIT:0><EOL>for n in range(len(pout)):<EOL><INDENT>bn = b.copy()<EOL>pn = []<EOL>for l in range(len(pout)):<EOL><INDENT>if l != n:<EOL><INDENT>pn.extend([pout[l]] * mult[l])<EOL><DEDENT><DEDENT>an = atleast_1d(poly(pn))<EOL>sig = mult[n]<EOL>for m in range(sig, <NUM_LIT:0>, -<NUM_LIT:1>):<EOL><INDENT>if sig > m:<EOL><INDENT>term1 = polymul(polyder(bn, <NUM_LIT:1>), an)<EOL>term2 = polymul(bn, polyder(an, <NUM_LIT:1>))<EOL>bn = polysub(term1, term2)<EOL>an = polymul(an, an)<EOL><DEDENT>r[indx + m - <NUM_LIT:1>] = (polyval(bn, pout[n]) / polyval(an, pout[n])<EOL>/ factorial(sig - m))<EOL><DEDENT>indx += sig<EOL><DEDENT>return r / rscale, p, k<EOL>

Compute partial-fraction expansion of b(s) / a(s).

If ``M = len(b)`` and ``N = len(a)``, then the partial-fraction
expansion H(s) is defined as::

          b(s)     b[0] s**(M-1) + b[1] s**(M-2) + ... + b[M-1]
  H(s) = ------ = ----------------------------------------------
          a(s)     a[0] s**(N-1) + a[1] s**(N-2) + ... + a[N-1]

           r[0]       r[1]             r[-1]
       = -------- + -------- + ... + --------- + k(s)
         (s-p[0])   (s-p[1])         (s-p[-1])

If there are any repeated roots (closer together than `tol`), then H(s)
has terms like::

        r[i]      r[i+1]              r[i+n-1]
      -------- + ----------- + ... + -----------
      (s-p[i])  (s-p[i])**2          (s-p[i])**n

Returns
-------
r : ndarray
    Residues.
p : ndarray
    Poles.
k : ndarray
    Coefficients of the direct polynomial term.

See Also
--------
invres, numpy.poly, unique_roots


def residuez(b, a, tol=<NUM_LIT>, rtype='<STR_LIT>'):

b, a = map(asarray, (b, a))<EOL>gain = a[<NUM_LIT:0>]<EOL>brev, arev = b[::-<NUM_LIT:1>], a[::-<NUM_LIT:1>]<EOL>krev, brev = polydiv(brev, arev)<EOL>if krev == []:<EOL><INDENT>k = []<EOL><DEDENT>else:<EOL><INDENT>k = krev[::-<NUM_LIT:1>]<EOL><DEDENT>b = brev[::-<NUM_LIT:1>]<EOL>p = roots(a)<EOL>r = p * <NUM_LIT:0.0><EOL>pout, mult = unique_roots(p, tol=tol, rtype=rtype)<EOL>p = []<EOL>for n in range(len(pout)):<EOL><INDENT>p.extend([pout[n]] * mult[n])<EOL><DEDENT>p = asarray(p)<EOL>indx = <NUM_LIT:0><EOL>for n in range(len(pout)):<EOL><INDENT>bn = brev.copy()<EOL>pn = []<EOL>for l in range(len(pout)):<EOL><INDENT>if l != n:<EOL><INDENT>pn.extend([pout[l]] * mult[l])<EOL><DEDENT><DEDENT>an = atleast_1d(poly(pn))[::-<NUM_LIT:1>]<EOL>sig = mult[n]<EOL>for m in range(sig, <NUM_LIT:0>, -<NUM_LIT:1>):<EOL><INDENT>if sig > m:<EOL><INDENT>term1 = polymul(polyder(bn, <NUM_LIT:1>), an)<EOL>term2 = polymul(bn, polyder(an, <NUM_LIT:1>))<EOL>bn = polysub(term1, term2)<EOL>an = polymul(an, an)<EOL><DEDENT>r[indx + m - <NUM_LIT:1>] = (polyval(bn, <NUM_LIT:1.0> / pout[n]) /<EOL>polyval(an, <NUM_LIT:1.0> / pout[n]) /<EOL>factorial(sig - m) / (-pout[n]) ** (sig - m))<EOL><DEDENT>indx += sig<EOL><DEDENT>return r / gain, p, k<EOL>


def invresz(r, p, k, tol=<NUM_LIT>, rtype='<STR_LIT>'):

extra = asarray(k)<EOL>p, indx = cmplx_sort(p)<EOL>r = take(r, indx, <NUM_LIT:0>)<EOL>pout, mult = unique_roots(p, tol=tol, rtype=rtype)<EOL>p = []<EOL>for k in range(len(pout)):<EOL><INDENT>p.extend([pout[k]] * mult[k])<EOL><DEDENT>a = atleast_1d(poly(p))<EOL>if len(extra) > <NUM_LIT:0>:<EOL><INDENT>b = polymul(extra, a)<EOL><DEDENT>else:<EOL><INDENT>b = [<NUM_LIT:0>]<EOL><DEDENT>indx = <NUM_LIT:0><EOL>brev = asarray(b)[::-<NUM_LIT:1>]<EOL>for k in range(len(pout)):<EOL><INDENT>temp = []<EOL>for l in range(len(pout)):<EOL><INDENT>if l != k:<EOL><INDENT>temp.extend([pout[l]] * mult[l])<EOL><DEDENT><DEDENT>for m in range(mult[k]):<EOL><INDENT>t2 = temp[:]<EOL>t2.extend([pout[k]] * (mult[k] - m - <NUM_LIT:1>))<EOL>brev = polyadd(brev, (r[indx] * poly(t2))[::-<NUM_LIT:1>])<EOL>indx += <NUM_LIT:1><EOL><DEDENT><DEDENT>b = real_if_close(brev[::-<NUM_LIT:1>])<EOL>return b, a<EOL>


def resample(x, num, t=None, axis=<NUM_LIT:0>, window=None):

x = asarray(x)<EOL>X = fft(x, axis=axis)<EOL>Nx = x.shape[axis]<EOL>if window is not None:<EOL><INDENT>if callable(window):<EOL><INDENT>W = window(fftfreq(Nx))<EOL><DEDENT>elif isinstance(window, ndarray) and window.shape == (Nx,):<EOL><INDENT>W = window<EOL><DEDENT>else:<EOL><INDENT>W = ifftshift(get_window(window, Nx))<EOL><DEDENT>newshape = [<NUM_LIT:1>] * x.ndim<EOL>newshape[axis] = len(W)<EOL>W.shape = newshape<EOL>X = X * W<EOL><DEDENT>sl = [slice(None)] * len(x.shape)<EOL>newshape = list(x.shape)<EOL>newshape[axis] = num<EOL>N = int(np.minimum(num, Nx))<EOL>Y = zeros(newshape, '<STR_LIT:D>')<EOL>sl[axis] = slice(<NUM_LIT:0>, (N + <NUM_LIT:1>) // <NUM_LIT:2>)<EOL>Y[sl] = X[sl]<EOL>sl[axis] = slice(-(N - <NUM_LIT:1>) // <NUM_LIT:2>, None)<EOL>Y[sl] = X[sl]<EOL>y = ifft(Y, axis=axis) * (float(num) / float(Nx))<EOL>if x.dtype.char not in ['<STR_LIT:F>', '<STR_LIT:D>']:<EOL><INDENT>y = y.real<EOL><DEDENT>if t is None:<EOL><INDENT>return y<EOL><DEDENT>else:<EOL><INDENT>new_t = arange(<NUM_LIT:0>, num) * (t[<NUM_LIT:1>] - t[<NUM_LIT:0>]) * Nx / float(num) + t[<NUM_LIT:0>]<EOL>return y, new_t<EOL><DEDENT>

Resample `x` to `num` samples using Fourier method along the given axis.

The resampled signal starts at the same value as `x` but is sampled
with a spacing of ``len(x) / num * (spacing of x)``.  Because a
Fourier method is used, the signal is assumed to be periodic.

Parameters
----------
x : array_like
    The data to be resampled.
num : int
    The number of samples in the resampled signal.
t : array_like, optional
    If `t` is given, it is assumed to be the sample positions
    associated with the signal data in `x`.
axis : int, optional
    The axis of `x` that is resampled.  Default is 0.
window : array_like, callable, string, float, or tuple, optional
    Specifies the window applied to the signal in the Fourier
    domain.  See below for details.

Returns
-------
resampled_x or (resampled_x, resampled_t)
    Either the resampled array, or, if `t` was given, a tuple
    containing the resampled array and the corresponding resampled
    positions.

Notes
-----
The argument `window` controls a Fourier-domain window that tapers
the Fourier spectrum before zero-padding to alleviate ringing in
the resampled values for sampled signals you didn't intend to be
interpreted as band-limited.

If `window` is a function, then it is called with a vector of inputs
indicating the frequency bins (i.e. fftfreq(x.shape[axis]) ).

If `window` is an array of the same length as `x.shape[axis]` it is
assumed to be the window to be applied directly in the Fourier
domain (with dc and low-frequency first).

For any other type of `window`, the function `scipy.signal.get_window`
is called to generate the window.

The first sample of the returned vector is the same as the first
sample of the input vector.  The spacing between samples is changed
from dx to:

    dx * len(x) / num

If `t` is not None, then it represents the old sample positions,
and the new sample positions will be returned as well as the new
samples.


events = asarray(events)<EOL>period = asarray(period)<EOL>if events.ndim > <NUM_LIT:1>:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>if period.ndim > <NUM_LIT:1>:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>scalarperiod = not period.ndim<EOL>events = atleast_2d(events)<EOL>period = atleast_2d(period)<EOL>if (period <= <NUM_LIT:0>).any():<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>vectors = exp(dot(<NUM_LIT>*pi/period.T, events))<EOL>vectormean = mean(vectors, axis=<NUM_LIT:1>)<EOL>strength = abs(vectormean)<EOL>phase = angle(vectormean)<EOL>if scalarperiod:<EOL><INDENT>strength = strength[<NUM_LIT:0>]<EOL>phase = phase[<NUM_LIT:0>]<EOL><DEDENT>return strength, phase<EOL>

Determine the vector strength of the events corresponding to the given
period.

The vector strength is a measure of phase synchrony, how well the
timing of the events is synchronized to a single period of a periodic
signal.

If multiple periods are used, calculate the vector strength of each.
This is called the "resonating vector strength".

Parameters
----------
events : 1D array_like
    An array of time points containing the timing of the events.
period : float or array_like
    The period of the signal that the events should synchronize to.
    The period is in the same units as `events`.  It can also be an array
    of periods, in which case the outputs are arrays of the same length.

Returns
-------
strength : float or 1D array
    The strength of the synchronization.  1.0 is perfect synchronization
    and 0.0 is no synchronization.  If `period` is an array, this is also
    an array with each element containing the vector strength at the
    corresponding period.
phase : float or array
    The phase that the events are most strongly synchronized to in radians.
    If `period` is an array, this is also an array with each element
    containing the phase for the corresponding period.

References
----------
van Hemmen, JL, Longtin, A, and Vollmayr, AN. Testing resonating vector
    strength: Auditory system, electric fish, and noise.
    Chaos 21, 047508 (2011);
    doi: 10.1063/1.3670512
van Hemmen, JL.  Vector strength after Goldberg, Brown, and von Mises:
    biological and mathematical perspectives.  Biol Cybern.
    2013 Aug;107(4):385-96. doi: 10.1007/s00422-013-0561-7.
van Hemmen, JL and Vollmayr, AN.  Resonating vector strength: what happens
    when we vary the "probing" frequency while keeping the spike times
    fixed.  Biol Cybern. 2013 Aug;107(4):491-94.
    doi: 10.1007/s00422-013-0560-8


def detrend(data, axis=-<NUM_LIT:1>, type='<STR_LIT>', bp=<NUM_LIT:0>):

if type not in ['<STR_LIT>', '<STR_LIT:l>', '<STR_LIT>', '<STR_LIT:c>']:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>data = asarray(data)<EOL>dtype = data.dtype.char<EOL>if dtype not in '<STR_LIT>':<EOL><INDENT>dtype = '<STR_LIT:d>'<EOL><DEDENT>if type in ['<STR_LIT>', '<STR_LIT:c>']:<EOL><INDENT>ret = data - expand_dims(mean(data, axis), axis)<EOL>return ret<EOL><DEDENT>else:<EOL><INDENT>dshape = data.shape<EOL>N = dshape[axis]<EOL>bp = sort(unique(r_[<NUM_LIT:0>, bp, N]))<EOL>if np.any(bp > N):<EOL><INDENT>raise ValueError("<STR_LIT>"<EOL>"<STR_LIT>")<EOL><DEDENT>Nreg = len(bp) - <NUM_LIT:1><EOL>rnk = len(dshape)<EOL>if axis < <NUM_LIT:0>:<EOL><INDENT>axis = axis + rnk<EOL><DEDENT>newdims = r_[axis, <NUM_LIT:0>:axis, axis + <NUM_LIT:1>:rnk]<EOL>newdata = reshape(transpose(data, tuple(newdims)),<EOL>(N, prod(dshape, axis=<NUM_LIT:0>) // N))<EOL>newdata = newdata.copy()  <EOL>if newdata.dtype.char not in '<STR_LIT>':<EOL><INDENT>newdata = newdata.astype(dtype)<EOL><DEDENT>for m in range(Nreg):<EOL><INDENT>Npts = bp[m + <NUM_LIT:1>] - bp[m]<EOL>A = ones((Npts, <NUM_LIT:2>), dtype)<EOL>A[:, <NUM_LIT:0>] = cast[dtype](arange(<NUM_LIT:1>, Npts + <NUM_LIT:1>) * <NUM_LIT:1.0> / Npts)<EOL>sl = slice(bp[m], bp[m + <NUM_LIT:1>])<EOL>coef, resids, rank, s = linalg.lstsq(A, newdata[sl])<EOL>newdata[sl] = newdata[sl] - dot(A, coef)<EOL><DEDENT>tdshape = take(dshape, newdims, <NUM_LIT:0>)<EOL>ret = reshape(newdata, tuple(tdshape))<EOL>vals = list(range(<NUM_LIT:1>, rnk))<EOL>olddims = vals[:axis] + [<NUM_LIT:0>] + vals[axis:]<EOL>ret = transpose(ret, tuple(olddims))<EOL>return ret<EOL><DEDENT>

Remove linear trend along axis from data.

Parameters
----------
data : array_like
    The input data.
axis : int, optional
    The axis along which to detrend the data. By default this is the
    last axis (-1).
type : {'linear', 'constant'}, optional
    The type of detrending. If ``type == 'linear'`` (default),
    the result of a linear least-squares fit to `data` is subtracted
    from `data`.
    If ``type == 'constant'``, only the mean of `data` is subtracted.
bp : array_like of ints, optional
    A sequence of break points. If given, an individual linear fit is
    performed for each part of `data` between two break points.
    Break points are specified as indices into `data`.

Returns
-------
ret : ndarray
    The detrended input data.

Examples
--------
>>> from scipy import signal
>>> randgen = np.random.RandomState(9)
>>> npoints = 1e3
>>> noise = randgen.randn(npoints)
>>> x = 3 + 2*np.linspace(0, 1, npoints) + noise
>>> (signal.detrend(x) - noise).max() < 0.01
True


<EOL>b = np.atleast_1d(b)<EOL>if b.ndim != <NUM_LIT:1>:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>a = np.atleast_1d(a)<EOL>if a.ndim != <NUM_LIT:1>:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>while len(a) > <NUM_LIT:1> and a[<NUM_LIT:0>] == <NUM_LIT:0.0>:<EOL><INDENT>a = a[<NUM_LIT:1>:]<EOL><DEDENT>if a.size < <NUM_LIT:1>:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if a[<NUM_LIT:0>] != <NUM_LIT:1.0>:<EOL><INDENT>b = b / a[<NUM_LIT:0>]<EOL>a = a / a[<NUM_LIT:0>]<EOL><DEDENT>n = max(len(a), len(b))<EOL>if len(a) < n:<EOL><INDENT>a = np.r_[a, np.zeros(n - len(a))]<EOL><DEDENT>elif len(b) < n:<EOL><INDENT>b = np.r_[b, np.zeros(n - len(b))]<EOL><DEDENT>IminusA = np.eye(n - <NUM_LIT:1>) - linalg.companion(a).T<EOL>B = b[<NUM_LIT:1>:] - a[<NUM_LIT:1>:] * b[<NUM_LIT:0>]<EOL>zi = np.linalg.solve(IminusA, B)<EOL>return zi<EOL>

Compute an initial state `zi` for the lfilter function that corresponds
to the steady state of the step response.

A typical use of this function is to set the initial state so that the
output of the filter starts at the same value as the first element of
the signal to be filtered.

Parameters
----------
b, a : array_like (1-D)
    The IIR filter coefficients. See `lfilter` for more
    information.

Returns
-------
zi : 1-D ndarray
    The initial state for the filter.

Notes
-----
A linear filter with order m has a state space representation (A, B, C, D),
for which the output y of the filter can be expressed as::

    z(n+1) = A*z(n) + B*x(n)
    y(n)   = C*z(n) + D*x(n)

where z(n) is a vector of length m, A has shape (m, m), B has shape
(m, 1), C has shape (1, m) and D has shape (1, 1) (assuming x(n) is
a scalar).  lfilter_zi solves::

    zi = A*zi + B

In other words, it finds the initial condition for which the response
to an input of all ones is a constant.

Given the filter coefficients `a` and `b`, the state space matrices
for the transposed direct form II implementation of the linear filter,
which is the implementation used by scipy.signal.lfilter, are::

    A = scipy.linalg.companion(a).T
    B = b[1:] - a[1:]*b[0]

assuming `a[0]` is 1.0; if `a[0]` is not 1, `a` and `b` are first
divided by a[0].

Examples
--------
The following code creates a lowpass Butterworth filter. Then it
applies that filter to an array whose values are all 1.0; the
output is also all 1.0, as expected for a lowpass filter.  If the
`zi` argument of `lfilter` had not been given, the output would have
shown the transient signal.

>>> from numpy import array, ones
>>> from scipy.signal import lfilter, lfilter_zi, butter
>>> b, a = butter(5, 0.25)
>>> zi = lfilter_zi(b, a)
>>> y, zo = lfilter(b, a, ones(10), zi=zi)
>>> y
array([1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.])

Another example:

>>> x = array([0.5, 0.5, 0.5, 0.0, 0.0, 0.0, 0.0])
>>> y, zf = lfilter(b, a, x, zi=zi*x[0])
>>> y
array([ 0.5       ,  0.5       ,  0.5       ,  0.49836039,  0.48610528,
    0.44399389,  0.35505241])

Note that the `zi` argument to `lfilter` was computed using
`lfilter_zi` and scaled by `x[0]`.  Then the output `y` has no
transient until the input drops from 0.5 to 0.0.


def filtfilt(b, a, x, axis=-<NUM_LIT:1>, padtype='<STR_LIT>', padlen=None):

if padtype not in ['<STR_LIT>', '<STR_LIT>', '<STR_LIT>', None]:<EOL><INDENT>raise ValueError(("<STR_LIT>"<EOL>"<STR_LIT>") %<EOL>padtype)<EOL><DEDENT>b = np.atleast_1d(b)<EOL>a = np.atleast_1d(a)<EOL>x = np.asarray(x)<EOL>ntaps = max(len(a), len(b))<EOL>if padtype is None:<EOL><INDENT>padlen = <NUM_LIT:0><EOL><DEDENT>if padlen is None:<EOL><INDENT>edge = ntaps * <NUM_LIT:3><EOL><DEDENT>else:<EOL><INDENT>edge = padlen<EOL><DEDENT>if x.shape[axis] <= edge:<EOL><INDENT>raise ValueError("<STR_LIT>"<EOL>"<STR_LIT>" % edge)<EOL><DEDENT>if padtype is not None and edge > <NUM_LIT:0>:<EOL><INDENT>if padtype == '<STR_LIT>':<EOL><INDENT>ext = even_ext(x, edge, axis=axis)<EOL><DEDENT>elif padtype == '<STR_LIT>':<EOL><INDENT>ext = odd_ext(x, edge, axis=axis)<EOL><DEDENT>else:<EOL><INDENT>ext = const_ext(x, edge, axis=axis)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>ext = x<EOL><DEDENT>zi = lfilter_zi(b, a)<EOL>zi_shape = [<NUM_LIT:1>] * x.ndim<EOL>zi_shape[axis] = zi.size<EOL>zi = np.reshape(zi, zi_shape)<EOL>x0 = axis_slice(ext, stop=<NUM_LIT:1>, axis=axis)<EOL>(y, zf) = lfilter(b, a, ext, axis=axis, zi=zi * x0)<EOL>y0 = axis_slice(y, start=-<NUM_LIT:1>, axis=axis)<EOL>(y, zf) = lfilter(b, a, axis_reverse(y, axis=axis), axis=axis, zi=zi * y0)<EOL>y = axis_reverse(y, axis=axis)<EOL>if edge > <NUM_LIT:0>:<EOL><INDENT>y = axis_slice(y, start=edge, stop=-edge, axis=axis)<EOL><DEDENT>return y<EOL>

A forward-backward filter.

This function applies a linear filter twice, once forward
and once backwards.  The combined filter has linear phase.

Before applying the filter, the function can pad the data along the
given axis in one of three ways: odd, even or constant.  The odd
and even extensions have the corresponding symmetry about the end point
of the data.  The constant extension extends the data with the values
at end points.  On both the forward and backwards passes, the
initial condition of the filter is found by using `lfilter_zi` and
scaling it by the end point of the extended data.

Parameters
----------
b : (N,) array_like
    The numerator coefficient vector of the filter.
a : (N,) array_like
    The denominator coefficient vector of the filter.  If a[0]
    is not 1, then both a and b are normalized by a[0].
x : array_like
    The array of data to be filtered.
axis : int, optional
    The axis of `x` to which the filter is applied.
    Default is -1.
padtype : str or None, optional
    Must be 'odd', 'even', 'constant', or None.  This determines the
    type of extension to use for the padded signal to which the filter
    is applied.  If `padtype` is None, no padding is used.  The default
    is 'odd'.
padlen : int or None, optional
    The number of elements by which to extend `x` at both ends of
    `axis` before applying the filter. This value must be less than
    `x.shape[axis]-1`.  `padlen=0` implies no padding.
    The default value is 3*max(len(a),len(b)).

Returns
-------
y : ndarray
    The filtered output, an array of type numpy.float64 with the same
    shape as `x`.

See Also
--------
lfilter_zi, lfilter

Examples
--------
First we create a one second signal that is the sum of two pure sine
waves, with frequencies 5 Hz and 250 Hz, sampled at 2000 Hz.

>>> t = np.linspace(0, 1.0, 2001)
>>> xlow = np.sin(2 * np.pi * 5 * t)
>>> xhigh = np.sin(2 * np.pi * 250 * t)
>>> x = xlow + xhigh

Now create a lowpass Butterworth filter with a cutoff of 0.125 times
the Nyquist rate, or 125 Hz, and apply it to x with filtfilt.  The
result should be approximately xlow, with no phase shift.

>>> from scipy import signal
>>> b, a = signal.butter(8, 0.125)
>>> y = signal.filtfilt(b, a, x, padlen=150)
>>> np.abs(y - xlow).max()
9.1086182074789912e-06

We get a fairly clean result for this artificial example because
the odd extension is exact, and with the moderately long padding,
the filter's transients have dissipated by the time the actual data
is reached.  In general, transient effects at the edges are
unavoidable.


def decimate(x, q, n=None, ftype='<STR_LIT>', axis=-<NUM_LIT:1>):

if not isinstance(q, int):<EOL><INDENT>raise TypeError("<STR_LIT>")<EOL><DEDENT>if n is None:<EOL><INDENT>if ftype == '<STR_LIT>':<EOL><INDENT>n = <NUM_LIT:30><EOL><DEDENT>else:<EOL><INDENT>n = <NUM_LIT:8><EOL><DEDENT><DEDENT>if ftype == '<STR_LIT>':<EOL><INDENT>b = firwin(n + <NUM_LIT:1>, <NUM_LIT:1.> / q, window='<STR_LIT>')<EOL>a = <NUM_LIT:1.><EOL><DEDENT>else:<EOL><INDENT>b, a = cheby1(n, <NUM_LIT>, <NUM_LIT> / q)<EOL><DEDENT>y = lfilter(b, a, x, axis=axis)<EOL>sl = [slice(None)] * y.ndim<EOL>sl[axis] = slice(None, None, q)<EOL>return y[sl]<EOL>

Downsample the signal by using a filter.

By default, an order 8 Chebyshev type I filter is used.  A 30 point FIR
filter with hamming window is used if `ftype` is 'fir'.

Parameters
----------
x : ndarray
    The signal to be downsampled, as an N-dimensional array.
q : int
    The downsampling factor.
n : int, optional
    The order of the filter (1 less than the length for 'fir').
ftype : str {'iir', 'fir'}, optional
    The type of the lowpass filter.
axis : int, optional
    The axis along which to decimate.

Returns
-------
y : ndarray
    The down-sampled signal.

See also
--------
resample


sqrt = np.sqrt<EOL>if p < <NUM_LIT:1>:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if p == <NUM_LIT:1>:<EOL><INDENT>c = <NUM_LIT:1> / sqrt(<NUM_LIT:2>)<EOL>return np.array([c, c])<EOL><DEDENT>elif p == <NUM_LIT:2>:<EOL><INDENT>f = sqrt(<NUM_LIT:2>) / <NUM_LIT:8><EOL>c = sqrt(<NUM_LIT:3>)<EOL>return f * np.array([<NUM_LIT:1> + c, <NUM_LIT:3> + c, <NUM_LIT:3> - c, <NUM_LIT:1> - c])<EOL><DEDENT>elif p == <NUM_LIT:3>:<EOL><INDENT>tmp = <NUM_LIT:12> * sqrt(<NUM_LIT:10>)<EOL>z1 = <NUM_LIT> + sqrt(<NUM_LIT:15> + tmp) / <NUM_LIT:6> - <NUM_LIT> * (sqrt(<NUM_LIT:15>) + sqrt(tmp - <NUM_LIT:15>)) / <NUM_LIT:6><EOL>z1c = np.conj(z1)<EOL>f = sqrt(<NUM_LIT:2>) / <NUM_LIT:8><EOL>d0 = np.real((<NUM_LIT:1> - z1) * (<NUM_LIT:1> - z1c))<EOL>a0 = np.real(z1 * z1c)<EOL>a1 = <NUM_LIT:2> * np.real(z1)<EOL>return f / d0 * np.array([a0, <NUM_LIT:3> * a0 - a1, <NUM_LIT:3> * a0 - <NUM_LIT:3> * a1 + <NUM_LIT:1>,<EOL>a0 - <NUM_LIT:3> * a1 + <NUM_LIT:3>, <NUM_LIT:3> - a1, <NUM_LIT:1>])<EOL><DEDENT>elif p < <NUM_LIT>:<EOL><INDENT>if p < <NUM_LIT>:<EOL><INDENT>P = [comb(p - <NUM_LIT:1> + k, k, exact=<NUM_LIT:1>) for k in range(p)][::-<NUM_LIT:1>]<EOL>yj = np.roots(P)<EOL><DEDENT>else:  <EOL><INDENT>P = [comb(p - <NUM_LIT:1> + k, k, exact=<NUM_LIT:1>) / <NUM_LIT>**k<EOL>for k in range(p)][::-<NUM_LIT:1>]<EOL>yj = np.roots(P) / <NUM_LIT:4><EOL><DEDENT>c = np.poly1d([<NUM_LIT:1>, <NUM_LIT:1>])**p<EOL>q = np.poly1d([<NUM_LIT:1>])<EOL>for k in range(p - <NUM_LIT:1>):<EOL><INDENT>yval = yj[k]<EOL>part = <NUM_LIT:2> * sqrt(yval * (yval - <NUM_LIT:1>))<EOL>const = <NUM_LIT:1> - <NUM_LIT:2> * yval<EOL>z1 = const + part<EOL>if (abs(z1)) < <NUM_LIT:1>:<EOL><INDENT>z1 = const - part<EOL><DEDENT>q = q * [<NUM_LIT:1>, -z1]<EOL><DEDENT>q = c * np.real(q)<EOL>q = q / np.sum(q) * sqrt(<NUM_LIT:2>)<EOL>return q.c[::-<NUM_LIT:1>]<EOL><DEDENT>else:<EOL><INDENT>raise ValueError("<STR_LIT>"<EOL>"<STR_LIT>")<EOL><DEDENT>

The coefficients for the FIR low-pass filter producing Daubechies wavelets.

p>=1 gives the order of the zero at f=1/2.
There are 2p filter coefficients.

Parameters
----------
p : int
    Order of the zero at f=1/2, can have values from 1 to 34.

Returns
-------
daub : ndarray
    Return


N = len(hk) - <NUM_LIT:1><EOL>asgn = [{<NUM_LIT:0>: <NUM_LIT:1>, <NUM_LIT:1>:-<NUM_LIT:1>}[k % <NUM_LIT:2>] for k in range(N + <NUM_LIT:1>)]<EOL>return hk[::-<NUM_LIT:1>] * np.array(asgn)<EOL>

Return high-pass qmf filter from low-pass

Parameters
----------
hk : array_like
    Coefficients of high-pass filter.


N = len(hk) - <NUM_LIT:1><EOL>if (J > <NUM_LIT:30> - np.log2(N + <NUM_LIT:1>)):<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if (J < <NUM_LIT:1>):<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>nn, kk = np.ogrid[:N, :N]<EOL>s2 = np.sqrt(<NUM_LIT:2>)<EOL>thk = np.r_[hk, <NUM_LIT:0>]<EOL>gk = qmf(hk)<EOL>tgk = np.r_[gk, <NUM_LIT:0>]<EOL>indx1 = np.clip(<NUM_LIT:2> * nn - kk, -<NUM_LIT:1>, N + <NUM_LIT:1>)<EOL>indx2 = np.clip(<NUM_LIT:2> * nn - kk + <NUM_LIT:1>, -<NUM_LIT:1>, N + <NUM_LIT:1>)<EOL>m = np.zeros((<NUM_LIT:2>, <NUM_LIT:2>, N, N), '<STR_LIT:d>')<EOL>m[<NUM_LIT:0>, <NUM_LIT:0>] = np.take(thk, indx1, <NUM_LIT:0>)<EOL>m[<NUM_LIT:0>, <NUM_LIT:1>] = np.take(thk, indx2, <NUM_LIT:0>)<EOL>m[<NUM_LIT:1>, <NUM_LIT:0>] = np.take(tgk, indx1, <NUM_LIT:0>)<EOL>m[<NUM_LIT:1>, <NUM_LIT:1>] = np.take(tgk, indx2, <NUM_LIT:0>)<EOL>m *= s2<EOL>x = np.arange(<NUM_LIT:0>, N * (<NUM_LIT:1> << J), dtype=np.float) / (<NUM_LIT:1> << J)<EOL>phi = <NUM_LIT:0> * x<EOL>psi = <NUM_LIT:0> * x<EOL>lam, v = eig(m[<NUM_LIT:0>, <NUM_LIT:0>])<EOL>ind = np.argmin(np.absolute(lam - <NUM_LIT:1>))<EOL>v = np.real(v[:, ind])<EOL>sm = np.sum(v)<EOL>if sm < <NUM_LIT:0>:  <EOL><INDENT>v = -v<EOL>sm = -sm<EOL><DEDENT>bitdic = {}<EOL>bitdic['<STR_LIT:0>'] = v / sm<EOL>bitdic['<STR_LIT:1>'] = np.dot(m[<NUM_LIT:0>, <NUM_LIT:1>], bitdic['<STR_LIT:0>'])<EOL>step = <NUM_LIT:1> << J<EOL>phi[::step] = bitdic['<STR_LIT:0>']<EOL>phi[(<NUM_LIT:1> << (J - <NUM_LIT:1>))::step] = bitdic['<STR_LIT:1>']<EOL>psi[::step] = np.dot(m[<NUM_LIT:1>, <NUM_LIT:0>], bitdic['<STR_LIT:0>'])<EOL>psi[(<NUM_LIT:1> << (J - <NUM_LIT:1>))::step] = np.dot(m[<NUM_LIT:1>, <NUM_LIT:1>], bitdic['<STR_LIT:0>'])<EOL>prevkeys = ['<STR_LIT:1>']<EOL>for level in range(<NUM_LIT:2>, J + <NUM_LIT:1>):<EOL><INDENT>newkeys = ['<STR_LIT>' % (xx, yy) for xx in [<NUM_LIT:0>, <NUM_LIT:1>] for yy in prevkeys]<EOL>fac = <NUM_LIT:1> << (J - level)<EOL>for key in newkeys:<EOL><INDENT>num = <NUM_LIT:0><EOL>for pos in range(level):<EOL><INDENT>if key[pos] == '<STR_LIT:1>':<EOL><INDENT>num += (<NUM_LIT:1> << (level - <NUM_LIT:1> - pos))<EOL><DEDENT><DEDENT>pastphi = bitdic[key[<NUM_LIT:1>:]]<EOL>ii = int(key[<NUM_LIT:0>])<EOL>temp = np.dot(m[<NUM_LIT:0>, ii], pastphi)<EOL>bitdic[key] = temp<EOL>phi[num * fac::step] = temp<EOL>psi[num * fac::step] = np.dot(m[<NUM_LIT:1>, ii], pastphi)<EOL><DEDENT>prevkeys = newkeys<EOL><DEDENT>return x, phi, psi<EOL>

Return (x, phi, psi) at dyadic points ``K/2**J`` from filter coefficients.

Parameters
----------
hk : array_like
    Coefficients of low-pass filter.
J : int, optional
    Values will be computed at grid points ``K/2**J``. Default is 7.

Returns
-------
x : ndarray
    The dyadic points ``K/2**J`` for ``K=0...N * (2**J)-1`` where
    ``len(hk) = len(gk) = N+1``.
phi : ndarray
    The scaling function ``phi(x)`` at `x`:
    ``phi(x) = sum(hk * phi(2x-k))``, where k is from 0 to N.
psi : ndarray, optional
    The wavelet function ``psi(x)`` at `x`:
    ``phi(x) = sum(gk * phi(2x-k))``, where k is from 0 to N.
    `psi` is only returned if `gk` is not None.

Notes
-----
The algorithm uses the vector cascade algorithm described by Strang and
Nguyen in "Wavelets and Filter Banks".  It builds a dictionary of values
and slices for quick reuse.  Then inserts vectors into final vector at the
end.


def morlet(M, w=<NUM_LIT>, s=<NUM_LIT:1.0>, complete=True):

x = linspace(-s * <NUM_LIT:2> * pi, s * <NUM_LIT:2> * pi, M)<EOL>output = exp(<NUM_LIT> * w * x)<EOL>if complete:<EOL><INDENT>output -= exp(-<NUM_LIT:0.5> * (w**<NUM_LIT:2>))<EOL><DEDENT>output *= exp(-<NUM_LIT:0.5> * (x**<NUM_LIT:2>)) * pi**(-<NUM_LIT>)<EOL>return output<EOL>

Complex Morlet wavelet.

Parameters
----------
M : int
    Length of the wavelet.
w : float
    Omega0. Default is 5
s : float
    Scaling factor, windowed from ``-s*2*pi`` to ``+s*2*pi``. Default is 1.
complete : bool
    Whether to use the complete or the standard version.

Returns
-------
morlet : (M,) ndarray

See Also
--------
scipy.signal.gausspulse

Notes
-----
The standard version::

    pi**-0.25 * exp(1j*w*x) * exp(-0.5*(x**2))

This commonly used wavelet is often referred to simply as the
Morlet wavelet.  Note that this simplified version can cause
admissibility problems at low values of w.

The complete version::

    pi**-0.25 * (exp(1j*w*x) - exp(-0.5*(w**2))) * exp(-0.5*(x**2))

The complete version of the Morlet wavelet, with a correction
term to improve admissibility. For w greater than 5, the
correction term is negligible.

Note that the energy of the return wavelet is not normalised
according to s.

The fundamental frequency of this wavelet in Hz is given
by ``f = 2*s*w*r / M`` where r is the sampling rate.


A = <NUM_LIT:2> / (np.sqrt(<NUM_LIT:3> * a) * (np.pi**<NUM_LIT>))<EOL>wsq = a**<NUM_LIT:2><EOL>vec = np.arange(<NUM_LIT:0>, points) - (points - <NUM_LIT:1.0>) / <NUM_LIT:2><EOL>xsq = vec**<NUM_LIT:2><EOL>mod = (<NUM_LIT:1> - xsq / wsq)<EOL>gauss = np.exp(-xsq / (<NUM_LIT:2> * wsq))<EOL>total = A * mod * gauss<EOL>return total<EOL>

Return a Ricker wavelet, also known as the "Mexican hat wavelet".

It models the function:

    ``A (1 - x^2/a^2) exp(-x^2/2 a^2)``,

where ``A = 2/sqrt(3a)pi^1/4``.

Parameters
----------
points : int
    Number of points in `vector`.
    Will be centered around 0.
a : scalar
    Width parameter of the wavelet.

Returns
-------
vector : (N,) ndarray
    Array of length `points` in shape of ricker curve.

Examples
--------
>>> from scipy import signal
>>> import matplotlib.pyplot as plt

>>> points = 100
>>> a = 4.0
>>> vec2 = signal.ricker(points, a)
>>> print(len(vec2))
100
>>> plt.plot(vec2)
>>> plt.show()


output = np.zeros([len(widths), len(data)])<EOL>for ind, width in enumerate(widths):<EOL><INDENT>wavelet_data = wavelet(min(<NUM_LIT:10> * width, len(data)), width)<EOL>output[ind, :] = convolve(data, wavelet_data,<EOL>mode='<STR_LIT>')<EOL><DEDENT>return output<EOL>

Continuous wavelet transform.

Performs a continuous wavelet transform on `data`,
using the `wavelet` function. A CWT performs a convolution
with `data` using the `wavelet` function, which is characterized
by a width parameter and length parameter.

Parameters
----------
data : (N,) ndarray
    data on which to perform the transform.
wavelet : function
    Wavelet function, which should take 2 arguments.
    The first argument is the number of points that the returned vector
    will have (len(wavelet(width,length)) == length).
    The second is a width parameter, defining the size of the wavelet
    (e.g. standard deviation of a gaussian). See `ricker`, which
    satisfies these requirements.
widths : (M,) sequence
    Widths to use for transform.

Returns
-------
cwt: (M, N) ndarray
    Will have shape of (len(data), len(widths)).

Notes
-----
>>> length = min(10 * width[ii], len(data))
>>> cwt[ii,:] = scipy.signal.convolve(data, wavelet(length,
...                                       width[ii]), mode='same')

Examples
--------
>>> from scipy import signal
>>> import matplotlib.pyplot as plt
>>> t = np.linspace(-1, 1, 200, endpoint=False)
>>> sig  = np.cos(2 * np.pi * 7 * t) + signal.gausspulse(t - 0.4, fc=2)
>>> widths = np.arange(1, 31)
>>> cwtmatr = signal.cwt(sig, signal.ricker, widths)
>>> plt.imshow(cwtmatr, extent=[-1, 1, 1, 31], cmap='PRGn', aspect='auto',
...            vmax=abs(cwtmatr).max(), vmin=-abs(cwtmatr).max())
>>> plt.show()


if a > <NUM_LIT:50>:<EOL><INDENT>beta = <NUM_LIT> * (a - <NUM_LIT>)<EOL><DEDENT>elif a > <NUM_LIT>:<EOL><INDENT>beta = <NUM_LIT> * (a - <NUM_LIT>) ** <NUM_LIT> + <NUM_LIT> * (a - <NUM_LIT>)<EOL><DEDENT>else:<EOL><INDENT>beta = <NUM_LIT:0.0><EOL><DEDENT>return beta<EOL>

Compute the Kaiser parameter `beta`, given the attenuation `a`.

    Parameters
    ----------
    a : float
        The desired attenuation in the stopband and maximum ripple in
        the passband, in dB.  This should be a *positive* number.

    Returns
    -------
    beta : float
        The `beta` parameter to be used in the formula for a Kaiser window.

    References
    ----------
    Oppenheim, Schafer, "Discrete-Time Signal Processing", p.475-476.


a = <NUM_LIT> * (numtaps - <NUM_LIT:1>) * np.pi * width + <NUM_LIT><EOL>return a<EOL>

Compute the attenuation of a Kaiser FIR filter.

    Given the number of taps `N` and the transition width `width`, compute the
    attenuation `a` in dB, given by Kaiser's formula:

        a = 2.285 * (N - 1) * pi * width + 7.95

    Parameters
    ----------
    N : int
        The number of taps in the FIR filter.
    width : float
        The desired width of the transition region between passband and
        stopband (or, in general, at any discontinuity) for the filter.

    Returns
    -------
    a : float
        The attenuation of the ripple, in dB.

    See Also
    --------
    kaiserord, kaiser_beta


A = abs(ripple)  <EOL>if A < <NUM_LIT:8>:<EOL><INDENT>raise ValueError("<STR_LIT>"<EOL>"<STR_LIT>" % A)<EOL><DEDENT>beta = kaiser_beta(A)<EOL>numtaps = (A - <NUM_LIT>) / <NUM_LIT> / (np.pi * width) + <NUM_LIT:1><EOL>return int(ceil(numtaps)), beta<EOL>

Design a Kaiser window to limit ripple and width of transition region.

Parameters
----------
ripple : float
    Positive number specifying maximum ripple in passband (dB) and minimum
    ripple in stopband.
width : float
    Width of transition region (normalized so that 1 corresponds to pi
    radians / sample).

Returns
-------
numtaps : int
    The length of the kaiser window.
beta : float
    The beta parameter for the kaiser window.

See Also
--------
kaiser_beta, kaiser_atten

Notes
-----
There are several ways to obtain the Kaiser window:

- ``signal.kaiser(numtaps, beta, sym=0)``
- ``signal.get_window(beta, numtaps)``
- ``signal.get_window(('kaiser', beta), numtaps)``

The empirical equations discovered by Kaiser are used.

References
----------
Oppenheim, Schafer, "Discrete-Time Signal Processing", p.475-476.


def firwin(numtaps, cutoff, width=None, window='<STR_LIT>', pass_zero=True,<EOL>scale=True, nyq=<NUM_LIT:1.0>):

<EOL>cutoff = np.atleast_1d(cutoff) / float(nyq)<EOL>if cutoff.ndim > <NUM_LIT:1>:<EOL><INDENT>raise ValueError("<STR_LIT>"<EOL>"<STR_LIT>")<EOL><DEDENT>if cutoff.size == <NUM_LIT:0>:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if cutoff.min() <= <NUM_LIT:0> or cutoff.max() >= <NUM_LIT:1>:<EOL><INDENT>raise ValueError("<STR_LIT>"<EOL>"<STR_LIT>")<EOL><DEDENT>if np.any(np.diff(cutoff) <= <NUM_LIT:0>):<EOL><INDENT>raise ValueError("<STR_LIT>"<EOL>"<STR_LIT>")<EOL><DEDENT>if width is not None:<EOL><INDENT>atten = kaiser_atten(numtaps, float(width) / nyq)<EOL>beta = kaiser_beta(atten)<EOL>window = ('<STR_LIT>', beta)<EOL><DEDENT>pass_nyquist = bool(cutoff.size & <NUM_LIT:1>) ^ pass_zero<EOL>if pass_nyquist and numtaps % <NUM_LIT:2> == <NUM_LIT:0>:<EOL><INDENT>raise ValueError("<STR_LIT>"<EOL>"<STR_LIT>")<EOL><DEDENT>cutoff = np.hstack(([<NUM_LIT:0.0>] * pass_zero, cutoff, [<NUM_LIT:1.0>] * pass_nyquist))<EOL>bands = cutoff.reshape(-<NUM_LIT:1>, <NUM_LIT:2>)<EOL>alpha = <NUM_LIT:0.5> * (numtaps - <NUM_LIT:1>)<EOL>m = np.arange(<NUM_LIT:0>, numtaps) - alpha<EOL>h = <NUM_LIT:0><EOL>for left, right in bands:<EOL><INDENT>h += right * sinc(right * m)<EOL>h -= left * sinc(left * m)<EOL><DEDENT>from .signaltools import get_window<EOL>win = get_window(window, numtaps, fftbins=False)<EOL>h *= win<EOL>if scale:<EOL><INDENT>left, right = bands[<NUM_LIT:0>]<EOL>if left == <NUM_LIT:0>:<EOL><INDENT>scale_frequency = <NUM_LIT:0.0><EOL><DEDENT>elif right == <NUM_LIT:1>:<EOL><INDENT>scale_frequency = <NUM_LIT:1.0><EOL><DEDENT>else:<EOL><INDENT>scale_frequency = <NUM_LIT:0.5> * (left + right)<EOL><DEDENT>c = np.cos(np.pi * m * scale_frequency)<EOL>s = np.sum(h * c)<EOL>h /= s<EOL><DEDENT>return h<EOL>

FIR filter design using the window method.

This function computes the coefficients of a finite impulse response
filter.  The filter will have linear phase; it will be Type I if
`numtaps` is odd and Type II if `numtaps` is even.

Type II filters always have zero response at the Nyquist rate, so a
ValueError exception is raised if firwin is called with `numtaps` even and
having a passband whose right end is at the Nyquist rate.

Parameters
----------
numtaps : int
    Length of the filter (number of coefficients, i.e. the filter
    order + 1).  `numtaps` must be even if a passband includes the
    Nyquist frequency.
cutoff : float or 1D array_like
    Cutoff frequency of filter (expressed in the same units as `nyq`)
    OR an array of cutoff frequencies (that is, band edges). In the
    latter case, the frequencies in `cutoff` should be positive and
    monotonically increasing between 0 and `nyq`.  The values 0 and
    `nyq` must not be included in `cutoff`.
width : float or None
    If `width` is not None, then assume it is the approximate width
    of the transition region (expressed in the same units as `nyq`)
    for use in Kaiser FIR filter design.  In this case, the `window`
    argument is ignored.
window : string or tuple of string and parameter values
    Desired window to use. See `scipy.signal.get_window` for a list
    of windows and required parameters.
pass_zero : bool
    If True, the gain at the frequency 0 (i.e. the "DC gain") is 1.
    Otherwise the DC gain is 0.
scale : bool
    Set to True to scale the coefficients so that the frequency
    response is exactly unity at a certain frequency.
    That frequency is either:

    - 0 (DC) if the first passband starts at 0 (i.e. pass_zero
      is True)
    - `nyq` (the Nyquist rate) if the first passband ends at
      `nyq` (i.e the filter is a single band highpass filter);
      center of first passband otherwise

nyq : float
    Nyquist frequency.  Each frequency in `cutoff` must be between 0
    and `nyq`.

Returns
-------
h : (numtaps,) ndarray
    Coefficients of length `numtaps` FIR filter.

Raises
------
ValueError
    If any value in `cutoff` is less than or equal to 0 or greater
    than or equal to `nyq`, if the values in `cutoff` are not strictly
    monotonically increasing, or if `numtaps` is even but a passband
    includes the Nyquist frequency.

See also
--------
scipy.signal.firwin2

Examples
--------
Low-pass from 0 to f::

>>> from scipy import signal
>>> signal.firwin(numtaps, f)

Use a specific window function::

>>> signal.firwin(numtaps, f, window='nuttall')

High-pass ('stop' from 0 to f)::

>>> signal.firwin(numtaps, f, pass_zero=False)

Band-pass::

>>> signal.firwin(numtaps, [f1, f2], pass_zero=False)

Band-stop::

>>> signal.firwin(numtaps, [f1, f2])

Multi-band (passbands are [0, f1], [f2, f3] and [f4, 1])::

>>> signal.firwin(numtaps, [f1, f2, f3, f4])

Multi-band (passbands are [f1, f2] and [f3,f4])::

>>> signal.firwin(numtaps, [f1, f2, f3, f4], pass_zero=False)


def firwin2(numtaps, freq, gain, nfreqs=None, window='<STR_LIT>', nyq=<NUM_LIT:1.0>, antisymmetric=False):

if len(freq) != len(gain):<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>if nfreqs is not None and numtaps >= nfreqs:<EOL><INDENT>raise ValueError(('<STR_LIT>'<EOL>'<STR_LIT>') %<EOL>(numtaps, nfreqs))<EOL><DEDENT>if freq[<NUM_LIT:0>] != <NUM_LIT:0> or freq[-<NUM_LIT:1>] != nyq:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>d = np.diff(freq)<EOL>if (d < <NUM_LIT:0>).any():<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>d2 = d[:-<NUM_LIT:1>] + d[<NUM_LIT:1>:]<EOL>if (d2 == <NUM_LIT:0>).any():<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>if antisymmetric:<EOL><INDENT>if numtaps % <NUM_LIT:2> == <NUM_LIT:0>:<EOL><INDENT>ftype = <NUM_LIT:4><EOL><DEDENT>else:<EOL><INDENT>ftype = <NUM_LIT:3><EOL><DEDENT><DEDENT>else:<EOL><INDENT>if numtaps % <NUM_LIT:2> == <NUM_LIT:0>:<EOL><INDENT>ftype = <NUM_LIT:2><EOL><DEDENT>else:<EOL><INDENT>ftype = <NUM_LIT:1><EOL><DEDENT><DEDENT>if ftype == <NUM_LIT:2> and gain[-<NUM_LIT:1>] != <NUM_LIT:0.0>:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>elif ftype == <NUM_LIT:3> and (gain[<NUM_LIT:0>] != <NUM_LIT:0.0> or gain[-<NUM_LIT:1>] != <NUM_LIT:0.0>):<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>elif ftype == <NUM_LIT:4> and gain[<NUM_LIT:0>] != <NUM_LIT:0.0>:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if nfreqs is None:<EOL><INDENT>nfreqs = <NUM_LIT:1> + <NUM_LIT:2> ** int(ceil(log(numtaps, <NUM_LIT:2>)))<EOL><DEDENT>eps = np.finfo(float).eps<EOL>for k in range(len(freq)):<EOL><INDENT>if k < len(freq) - <NUM_LIT:1> and freq[k] == freq[k + <NUM_LIT:1>]:<EOL><INDENT>freq[k] = freq[k] - eps<EOL>freq[k + <NUM_LIT:1>] = freq[k + <NUM_LIT:1>] + eps<EOL><DEDENT><DEDENT>x = np.linspace(<NUM_LIT:0.0>, nyq, nfreqs)<EOL>fx = np.interp(x, freq, gain)<EOL>shift = np.exp(-(numtaps - <NUM_LIT:1>) / <NUM_LIT> * <NUM_LIT> * np.pi * x / nyq)<EOL>if ftype > <NUM_LIT:2>:<EOL><INDENT>shift *= <NUM_LIT><EOL><DEDENT>fx2 = fx * shift<EOL>out_full = irfft(fx2)<EOL>if window is not None:<EOL><INDENT>from .signaltools import get_window<EOL>wind = get_window(window, numtaps, fftbins=False)<EOL><DEDENT>else:<EOL><INDENT>wind = <NUM_LIT:1><EOL><DEDENT>out = out_full[:numtaps] * wind<EOL>if ftype == <NUM_LIT:3>:<EOL><INDENT>out[out.size // <NUM_LIT:2>] = <NUM_LIT:0.0><EOL><DEDENT>return out<EOL>

FIR filter design using the window method.

From the given frequencies `freq` and corresponding gains `gain`,
this function constructs an FIR filter with linear phase and
(approximately) the given frequency response.

Parameters
----------
numtaps : int
    The number of taps in the FIR filter.  `numtaps` must be less than
    `nfreqs`.
freq : array_like, 1D
    The frequency sampling points. Typically 0.0 to 1.0 with 1.0 being
    Nyquist.  The Nyquist frequency can be redefined with the argument
    `nyq`.
    The values in `freq` must be nondecreasing.  A value can be repeated
    once to implement a discontinuity.  The first value in `freq` must
    be 0, and the last value must be `nyq`.
gain : array_like
    The filter gains at the frequency sampling points. Certain
    constraints to gain values, depending on the filter type, are applied,
    see Notes for details.
nfreqs : int, optional
    The size of the interpolation mesh used to construct the filter.
    For most efficient behavior, this should be a power of 2 plus 1
    (e.g, 129, 257, etc).  The default is one more than the smallest
    power of 2 that is not less than `numtaps`.  `nfreqs` must be greater
    than `numtaps`.
window : string or (string, float) or float, or None, optional
    Window function to use. Default is "hamming".  See
    `scipy.signal.get_window` for the complete list of possible values.
    If None, no window function is applied.
nyq : float
    Nyquist frequency.  Each frequency in `freq` must be between 0 and
    `nyq` (inclusive).
antisymmetric : bool
    Whether resulting impulse response is symmetric/antisymmetric.
    See Notes for more details.

Returns
-------
taps : ndarray
    The filter coefficients of the FIR filter, as a 1-D array of length
    `numtaps`.

See also
--------
scipy.signal.firwin

Notes
-----
From the given set of frequencies and gains, the desired response is
constructed in the frequency domain.  The inverse FFT is applied to the
desired response to create the associated convolution kernel, and the
first `numtaps` coefficients of this kernel, scaled by `window`, are
returned.

The FIR filter will have linear phase. The type of filter is determined by
the value of 'numtaps` and `antisymmetric` flag.
There are four possible combinations:

   - odd  `numtaps`, `antisymmetric` is False, type I filter is produced
   - even `numtaps`, `antisymmetric` is False, type II filter is produced
   - odd  `numtaps`, `antisymmetric` is True, type III filter is produced
   - even `numtaps`, `antisymmetric` is True, type IV filter is produced

Magnitude response of all but type I filters are subjects to following
constraints:

   - type II  -- zero at the Nyquist frequency
   - type III -- zero at zero and Nyquist frequencies
   - type IV  -- zero at zero frequency

.. versionadded:: 0.9.0

References
----------
.. [1] Oppenheim, A. V. and Schafer, R. W., "Discrete-Time Signal
   Processing", Prentice-Hall, Englewood Cliffs, New Jersey (1989).
   (See, for example, Section 7.4.)

.. [2] Smith, Steven W., "The Scientist and Engineer's Guide to Digital
   Signal Processing", Ch. 17. http://www.dspguide.com/ch17/1.htm

Examples
--------
A lowpass FIR filter with a response that is 1 on [0.0, 0.5], and
that decreases linearly on [0.5, 1.0] from 1 to 0:

>>> from scipy import signal
>>> taps = signal.firwin2(150, [0.0, 0.5, 1.0], [1.0, 1.0, 0.0])
>>> print(taps[72:78])
[-0.02286961 -0.06362756  0.57310236  0.57310236 -0.06362756 -0.02286961]


def remez(numtaps, bands, desired, weight=None, Hz=<NUM_LIT:1>, type='<STR_LIT>',<EOL>maxiter=<NUM_LIT>, grid_density=<NUM_LIT:16>):

<EOL>try:<EOL><INDENT>tnum = {'<STR_LIT>': <NUM_LIT:1>, '<STR_LIT>': <NUM_LIT:2>, '<STR_LIT>': <NUM_LIT:3>}[type]<EOL><DEDENT>except KeyError:<EOL><INDENT>raise ValueError("<STR_LIT>"<EOL>"<STR_LIT>")<EOL><DEDENT>if weight is None:<EOL><INDENT>weight = [<NUM_LIT:1>] * len(desired)<EOL><DEDENT>bands = np.asarray(bands).copy()<EOL>return sigtools._remez(numtaps, bands, desired, weight, tnum, Hz,<EOL>maxiter, grid_density)<EOL>

Calculate the minimax optimal filter using the Remez exchange algorithm.

Calculate the filter-coefficients for the finite impulse response
(FIR) filter whose transfer function minimizes the maximum error
between the desired gain and the realized gain in the specified
frequency bands using the Remez exchange algorithm.

Parameters
----------
numtaps : int
    The desired number of taps in the filter. The number of taps is
    the number of terms in the filter, or the filter order plus one.
bands : array_like
    A monotonic sequence containing the band edges in Hz.
    All elements must be non-negative and less than half the sampling
    frequency as given by `Hz`.
desired : array_like
    A sequence half the size of bands containing the desired gain
    in each of the specified bands.
weight : array_like, optional
    A relative weighting to give to each band region. The length of
    `weight` has to be half the length of `bands`.
Hz : scalar, optional
    The sampling frequency in Hz. Default is 1.
type : {'bandpass', 'differentiator', 'hilbert'}, optional
    The type of filter:

      'bandpass' : flat response in bands. This is the default.

      'differentiator' : frequency proportional response in bands.

      'hilbert' : filter with odd symmetry, that is, type III
                  (for even order) or type IV (for odd order)
                  linear phase filters.

maxiter : int, optional
    Maximum number of iterations of the algorithm. Default is 25.
grid_density : int, optional
    Grid density. The dense grid used in `remez` is of size
    ``(numtaps + 1) * grid_density``. Default is 16.

Returns
-------
out : ndarray
    A rank-1 array containing the coefficients of the optimal
    (in a minimax sense) filter.

See Also
--------
freqz : Compute the frequency response of a digital filter.

References
----------
.. [1] J. H. McClellan and T. W. Parks, "A unified approach to the
       design of optimum FIR linear phase digital filters",
       IEEE Trans. Circuit Theory, vol. CT-20, pp. 697-701, 1973.
.. [2] J. H. McClellan, T. W. Parks and L. R. Rabiner, "A Computer
       Program for Designing Optimum FIR Linear Phase Digital
       Filters", IEEE Trans. Audio Electroacoust., vol. AU-21,
       pp. 506-525, 1973.

Examples
--------
We want to construct a filter with a passband at 0.2-0.4 Hz, and
stop bands at 0-0.1 Hz and 0.45-0.5 Hz. Note that this means that the
behavior in the frequency ranges between those bands is unspecified and
may overshoot.

>>> from scipy import signal
>>> bpass = signal.remez(72, [0, 0.1, 0.2, 0.4, 0.45, 0.5], [0, 1, 0])
>>> freq, response = signal.freqz(bpass)
>>> ampl = np.abs(response)

>>> import matplotlib.pyplot as plt
>>> fig = plt.figure()
>>> ax1 = fig.add_subplot(111)
>>> ax1.semilogy(freq/(2*np.pi), ampl, 'b-')  # freq in Hz
>>> plt.show()


def savgol_coeffs(window_length, polyorder, deriv=<NUM_LIT:0>, delta=<NUM_LIT:1.0>, pos=None,<EOL>use="<STR_LIT>"):

<EOL>if polyorder >= window_length:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>halflen, rem = divmod(window_length, <NUM_LIT:2>)<EOL>if rem == <NUM_LIT:0>:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if pos is None:<EOL><INDENT>pos = halflen<EOL><DEDENT>if not (<NUM_LIT:0> <= pos < window_length):<EOL><INDENT>raise ValueError("<STR_LIT>"<EOL>"<STR_LIT>")<EOL><DEDENT>if use not in ['<STR_LIT>', '<STR_LIT>']:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>x = np.arange(-pos, window_length - pos)<EOL>if use == "<STR_LIT>":<EOL><INDENT>x = x[::-<NUM_LIT:1>]<EOL><DEDENT>order = np.arange(polyorder + <NUM_LIT:1>).reshape(-<NUM_LIT:1>, <NUM_LIT:1>)<EOL>if order.size == <NUM_LIT:1>:<EOL><INDENT>A = np.atleast_2d(x ** order[<NUM_LIT:0>, <NUM_LIT:0>])<EOL><DEDENT>else:<EOL><INDENT>A = x ** order<EOL><DEDENT>y = np.zeros(polyorder + <NUM_LIT:1>)<EOL>y[deriv] = factorial(deriv) / (delta ** deriv)<EOL>coeffs, _, _, _ = lstsq(A, y)<EOL>return coeffs<EOL>

Compute the coefficients for a 1-d Savitzky-Golay FIR filter.

    Parameters
    ----------
    window_length : int
        The length of the filter window (i.e. the number of coefficients).
        `window_length` must be an odd positive integer.
    polyorder : int
        The order of the polynomial used to fit the samples.
        `polyorder` must be less than `window_length`.
    deriv : int, optional
        The order of the derivative to compute.  This must be a
        nonnegative integer.  The default is 0, which means to filter
        the data without differentiating.
    delta : float, optional
        The spacing of the samples to which the filter will be applied.
        This is only used if deriv > 0.
    pos : int or None, optional
        If pos is not None, it specifies evaluation position within the
        window.  The default is the middle of the window.
    use : str, optional
        Either 'conv' or 'dot'.  This argument chooses the order of the
        coefficients.  The default is 'conv', which means that the
        coefficients are ordered to be used in a convolution.  With
        use='dot', the order is reversed, so the filter is applied by
        dotting the coefficients with the data set.

    Returns
    -------
    coeffs : 1-d ndarray
        The filter coefficients.

    References
    ----------
    A. Savitzky, M. J. E. Golay, Smoothing and Differentiation of Data by
    Simplified Least Squares Procedures. Analytical Chemistry, 1964, 36 (8),
    pp 1627-1639.

    See Also
    --------
    savgol_filter

    Notes
    -----

    .. versionadded:: 0.14.0

    Examples
    --------
    >>> savgol_coeffs(5, 2)
    array([-0.08571429,  0.34285714,  0.48571429,  0.34285714, -0.08571429])
    >>> savgol_coeffs(5, 2, deriv=1)
    array([  2.00000000e-01,   1.00000000e-01,   2.00607895e-16,
            -1.00000000e-01,  -2.00000000e-01])

    Note that use='dot' simply reverses the coefficients.

    >>> savgol_coeffs(5, 2, pos=3)
    array([ 0.25714286,  0.37142857,  0.34285714,  0.17142857, -0.14285714])
    >>> savgol_coeffs(5, 2, pos=3, use='dot')
    array([-0.14285714,  0.17142857,  0.34285714,  0.37142857,  0.25714286])

    `x` contains data from the parabola x = t**2, sampled at
    t = -1, 0, 1, 2, 3.  `c` holds the coefficients that will compute the
    derivative at the last position.  When dotted with `x` the result should
    be 6.

    >>> x = array([1, 0, 1, 4, 9])
    >>> c = savgol_coeffs(5, 2, pos=4, deriv=1, use='dot')
    >>> c.dot(x)
    6.0000000000000018


if m == <NUM_LIT:0>:<EOL><INDENT>result = p<EOL><DEDENT>else:<EOL><INDENT>n = len(p)<EOL>if n <= m:<EOL><INDENT>result = np.zeros_like(p[:<NUM_LIT:1>, ...])<EOL><DEDENT>else:<EOL><INDENT>dp = p[:-m].copy()<EOL>for k in range(m):<EOL><INDENT>rng = np.arange(n - k - <NUM_LIT:1>, m - k - <NUM_LIT:1>, -<NUM_LIT:1>)<EOL>dp *= rng.reshape((n - m,) + (<NUM_LIT:1>,) * (p.ndim - <NUM_LIT:1>))<EOL><DEDENT>result = dp<EOL><DEDENT><DEDENT>return result<EOL>

Differentiate polynomials represented with coefficients.

    p must be a 1D or 2D array.  In the 2D case, each column gives
    the coefficients of a polynomial; the first row holds the coefficients
    associated with the highest power.  m must be a nonnegative integer.
    (numpy.polyder doesn't handle the 2D case.)


def _fit_edge(x, window_start, window_stop, interp_start, interp_stop,<EOL>axis, polyorder, deriv, delta, y):

<EOL>x_edge = axis_slice(x, start=window_start, stop=window_stop, axis=axis)<EOL>if axis == <NUM_LIT:0> or axis == -x.ndim:<EOL><INDENT>xx_edge = x_edge<EOL>swapped = False<EOL><DEDENT>else:<EOL><INDENT>xx_edge = x_edge.swapaxes(axis, <NUM_LIT:0>)<EOL>swapped = True<EOL><DEDENT>xx_edge = xx_edge.reshape(xx_edge.shape[<NUM_LIT:0>], -<NUM_LIT:1>)<EOL>poly_coeffs = np.polyfit(np.arange(<NUM_LIT:0>, window_stop - window_start),<EOL>xx_edge, polyorder)<EOL>if deriv > <NUM_LIT:0>:<EOL><INDENT>poly_coeffs = _polyder(poly_coeffs, deriv)<EOL><DEDENT>i = np.arange(interp_start - window_start, interp_stop - window_start)<EOL>values = np.polyval(poly_coeffs, i.reshape(-<NUM_LIT:1>, <NUM_LIT:1>)) / (delta ** deriv)<EOL>shp = list(y.shape)<EOL>shp[<NUM_LIT:0>], shp[axis] = shp[axis], shp[<NUM_LIT:0>]<EOL>values = values.reshape(interp_stop - interp_start, *shp[<NUM_LIT:1>:])<EOL>if swapped:<EOL><INDENT>values = values.swapaxes(<NUM_LIT:0>, axis)<EOL><DEDENT>y_edge = axis_slice(y, start=interp_start, stop=interp_stop, axis=axis)<EOL>y_edge[...] = values<EOL>

Given an n-d array `x` and the specification of a slice of `x` from
`window_start` to `window_stop` along `axis`, create an interpolating
polynomial of each 1-d slice, and evaluate that polynomial in the slice
from `interp_start` to `interp_stop`.  Put the result into the
corresponding slice of `y`.


def _fit_edges_polyfit(x, window_length, polyorder, deriv, delta, axis, y):

halflen = window_length // <NUM_LIT:2><EOL>_fit_edge(x, <NUM_LIT:0>, window_length, <NUM_LIT:0>, halflen, axis,<EOL>polyorder, deriv, delta, y)<EOL>n = x.shape[axis]<EOL>_fit_edge(x, n - window_length, n, n - halflen, n, axis,<EOL>polyorder, deriv, delta, y)<EOL>

Use polynomial interpolation of x at the low and high ends of the axis
to fill in the halflen values in y.

This function just calls _fit_edge twice, once for each end of the axis.


def savgol_filter(x, window_length, polyorder, deriv=<NUM_LIT:0>, delta=<NUM_LIT:1.0>,<EOL>axis=-<NUM_LIT:1>, mode='<STR_LIT>', cval=<NUM_LIT:0.0>):

if mode not in ["<STR_LIT>", "<STR_LIT>", "<STR_LIT>", "<STR_LIT>", "<STR_LIT>"]:<EOL><INDENT>raise ValueError("<STR_LIT>"<EOL>"<STR_LIT>")<EOL><DEDENT>x = np.asarray(x)<EOL>if x.dtype != np.float64 and x.dtype != np.float32:<EOL><INDENT>x = x.astype(np.float64)<EOL><DEDENT>coeffs = savgol_coeffs(window_length, polyorder, deriv=deriv, delta=delta)<EOL>if mode == "<STR_LIT>":<EOL><INDENT>y = convolve1d(x, coeffs, axis=axis, mode="<STR_LIT>")<EOL>_fit_edges_polyfit(x, window_length, polyorder, deriv, delta, axis, y)<EOL><DEDENT>else:<EOL><INDENT>y = convolve1d(x, coeffs, axis=axis, mode=mode, cval=cval)<EOL><DEDENT>return y<EOL>

Apply a Savitzky-Golay filter to an array.

    This is a 1-d filter.  If `x`  has dimension greater than 1, `axis`
    determines the axis along which the filter is applied.

    Parameters
    ----------
    x : array_like
        The data to be filtered.  If `x` is not a single or double precision
        floating point array, it will be converted to type `numpy.float64`
        before filtering.
    window_length : int
        The length of the filter window (i.e. the number of coefficients).
        `window_length` must be a positive odd integer.
    polyorder : int
        The order of the polynomial used to fit the samples.
        `polyorder` must be less than `window_length`.
    deriv : int, optional
        The order of the derivative to compute.  This must be a
        nonnegative integer.  The default is 0, which means to filter
        the data without differentiating.
    delta : float, optional
        The spacing of the samples to which the filter will be applied.
        This is only used if deriv > 0.  Default is 1.0.
    axis : int, optional
        The axis of the array `x` along which the filter is to be applied.
        Default is -1.
    mode : str, optional
        Must be 'mirror', 'constant', 'nearest', 'wrap' or 'interp'.  This
        determines the type of extension to use for the padded signal to
        which the filter is applied.  When `mode` is 'constant', the padding
        value is given by `cval`.  See the Notes for more details on 'mirror',
        'constant', 'wrap', and 'nearest'.
        When the 'interp' mode is selected (the default), no extension
        is used.  Instead, a degree `polyorder` polynomial is fit to the
        last `window_length` values of the edges, and this polynomial is
        used to evaluate the last `window_length // 2` output values.
    cval : scalar, optional
        Value to fill past the edges of the input if `mode` is 'constant'.
        Default is 0.0.

    Returns
    -------
    y : ndarray, same shape as `x`
        The filtered data.

    See Also
    --------
    savgol_coeffs

    Notes
    -----
    Details on the `mode` options:

        'mirror':
            Repeats the values at the edges in reverse order.  The value
            closest to the edge is not included.
        'nearest':
            The extension contains the nearest input value.
        'constant':
            The extension contains the value given by the `cval` argument.
        'wrap':
            The extension contains the values from the other end of the array.

    For example, if the input is [1, 2, 3, 4, 5, 6, 7, 8], and
    `window_length` is 7, the following shows the extended data for
    the various `mode` options (assuming `cval` is 0)::

        mode       |   Ext   |         Input          |   Ext
        -----------+---------+------------------------+---------
        'mirror'   | 4  3  2 | 1  2  3  4  5  6  7  8 | 7  6  5
        'nearest'  | 1  1  1 | 1  2  3  4  5  6  7  8 | 8  8  8
        'constant' | 0  0  0 | 1  2  3  4  5  6  7  8 | 0  0  0
        'wrap'     | 6  7  8 | 1  2  3  4  5  6  7  8 | 1  2  3

    .. versionadded:: 0.14.0

    Examples
    --------
    >>> np.set_printoptions(precision=2)  # For compact display.
    >>> x = np.array([2, 2, 5, 2, 1, 0, 1, 4, 9])

    Filter with a window length of 5 and a degree 2 polynomial.  Use
    the defaults for all other parameters.

    >>> y = savgol_filter(x, 5, 2)
    array([ 1.66,  3.17,  3.54,  2.86,  0.66,  0.17,  1.  ,  4.  ,  9.  ])

    Note that the last five values in x are samples of a parabola, so
    when mode='interp' (the default) is used with polyorder=2, the last
    three values are unchanged.  Compare that to, for example,
    `mode='nearest'`:

    >>> savgol_filter(x, 5, 2, mode='nearest')
    array([ 1.74,  3.03,  3.54,  2.86,  0.66,  0.17,  1.  ,  4.6 ,  7.97])


def _boolrelextrema(data, comparator,<EOL>axis=<NUM_LIT:0>, order=<NUM_LIT:1>, mode='<STR_LIT>'):

if((int(order) != order) or (order < <NUM_LIT:1>)):<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>datalen = data.shape[axis]<EOL>locs = np.arange(<NUM_LIT:0>, datalen)<EOL>results = np.ones(data.shape, dtype=bool)<EOL>main = data.take(locs, axis=axis, mode=mode)<EOL>for shift in xrange(<NUM_LIT:1>, order + <NUM_LIT:1>):<EOL><INDENT>plus = data.take(locs + shift, axis=axis, mode=mode)<EOL>minus = data.take(locs - shift, axis=axis, mode=mode)<EOL>results &= comparator(main, plus)<EOL>results &= comparator(main, minus)<EOL>if(~results.any()):<EOL><INDENT>return results<EOL><DEDENT><DEDENT>return results<EOL>

Calculate the relative extrema of `data`.

Relative extrema are calculated by finding locations where
``comparator(data[n], data[n+1:n+order+1])`` is True.

Parameters
----------
data : ndarray
    Array in which to find the relative extrema.
comparator : callable
    Function to use to compare two data points.
    Should take 2 numbers as arguments.
axis : int, optional
    Axis over which to select from `data`.  Default is 0.
order : int, optional
    How many points on each side to use for the comparison
    to consider ``comparator(n,n+x)`` to be True.
mode : str, optional
    How the edges of the vector are treated.  'wrap' (wrap around) or
    'clip' (treat overflow as the same as the last (or first) element).
    Default 'clip'.  See numpy.take

Returns
-------
extrema : ndarray
    Boolean array of the same shape as `data` that is True at an extrema,
    False otherwise.

See also
--------
argrelmax, argrelmin

Examples
--------
>>> testdata = np.array([1,2,3,2,1])
>>> _boolrelextrema(testdata, np.greater, axis=0)
array([False, False,  True, False, False], dtype=bool)


def argrelmin(data, axis=<NUM_LIT:0>, order=<NUM_LIT:1>, mode='<STR_LIT>'):

return argrelextrema(data, np.less, axis, order, mode)<EOL>

Calculate the relative minima of `data`.

Parameters
----------
data : ndarray
    Array in which to find the relative minima.
axis : int, optional
    Axis over which to select from `data`.  Default is 0.
order : int, optional
    How many points on each side to use for the comparison
    to consider ``comparator(n, n+x)`` to be True.
mode : str, optional
    How the edges of the vector are treated.
    Available options are 'wrap' (wrap around) or 'clip' (treat overflow
    as the same as the last (or first) element).
    Default 'clip'. See numpy.take

Returns
-------
extrema : tuple of ndarrays
    Indices of the minima in arrays of integers.  ``extrema[k]`` is
    the array of indices of axis `k` of `data`.  Note that the
    return value is a tuple even when `data` is one-dimensional.

See Also
--------
argrelextrema, argrelmax

Notes
-----
This function uses `argrelextrema` with np.less as comparator.

.. versionadded:: 0.11.0

Examples
--------
>>> x = np.array([2, 1, 2, 3, 2, 0, 1, 0])
>>> argrelmin(x)
(array([1, 5]),)
>>> y = np.array([[1, 2, 1, 2],
...               [2, 2, 0, 0],
...               [5, 3, 4, 4]])
...
>>> argrelmin(y, axis=1)
(array([0, 2]), array([2, 1]))


def argrelmax(data, axis=<NUM_LIT:0>, order=<NUM_LIT:1>, mode='<STR_LIT>'):

return argrelextrema(data, np.greater, axis, order, mode)<EOL>

Calculate the relative maxima of `data`.

Parameters
----------
data : ndarray
    Array in which to find the relative maxima.
axis : int, optional
    Axis over which to select from `data`.  Default is 0.
order : int, optional
    How many points on each side to use for the comparison
    to consider ``comparator(n, n+x)`` to be True.
mode : str, optional
    How the edges of the vector are treated.
    Available options are 'wrap' (wrap around) or 'clip' (treat overflow
    as the same as the last (or first) element).
    Default 'clip'.  See `numpy.take`.

Returns
-------
extrema : tuple of ndarrays
    Indices of the maxima in arrays of integers.  ``extrema[k]`` is
    the array of indices of axis `k` of `data`.  Note that the
    return value is a tuple even when `data` is one-dimensional.

See Also
--------
argrelextrema, argrelmin

Notes
-----
This function uses `argrelextrema` with np.greater as comparator.

.. versionadded:: 0.11.0

Examples
--------
>>> x = np.array([2, 1, 2, 3, 2, 0, 1, 0])
>>> argrelmax(x)
(array([3, 6]),)
>>> y = np.array([[1, 2, 1, 2],
...               [2, 2, 0, 0],
...               [5, 3, 4, 4]])
...
>>> argrelmax(y, axis=1)
(array([0]), array([1]))


def argrelextrema(data, comparator, axis=<NUM_LIT:0>, order=<NUM_LIT:1>, mode='<STR_LIT>'):

results = _boolrelextrema(data, comparator,<EOL>axis, order, mode)<EOL>return np.where(results)<EOL>

Calculate the relative extrema of `data`.

Parameters
----------
data : ndarray
    Array in which to find the relative extrema.
comparator : callable
    Function to use to compare two data points.
    Should take 2 numbers as arguments.
axis : int, optional
    Axis over which to select from `data`.  Default is 0.
order : int, optional
    How many points on each side to use for the comparison
    to consider ``comparator(n, n+x)`` to be True.
mode : str, optional
    How the edges of the vector are treated.  'wrap' (wrap around) or
    'clip' (treat overflow as the same as the last (or first) element).
    Default is 'clip'.  See `numpy.take`.

Returns
-------
extrema : tuple of ndarrays
    Indices of the maxima in arrays of integers.  ``extrema[k]`` is
    the array of indices of axis `k` of `data`.  Note that the
    return value is a tuple even when `data` is one-dimensional.

See Also
--------
argrelmin, argrelmax

Notes
-----

.. versionadded:: 0.11.0

Examples
--------
>>> x = np.array([2, 1, 2, 3, 2, 0, 1, 0])
>>> argrelextrema(x, np.greater)
(array([3, 6]),)
>>> y = np.array([[1, 2, 1, 2],
...               [2, 2, 0, 0],
...               [5, 3, 4, 4]])
...
>>> argrelextrema(y, np.less, axis=1)
(array([0, 2]), array([2, 1]))


def _identify_ridge_lines(matr, max_distances, gap_thresh):

if(len(max_distances) < matr.shape[<NUM_LIT:0>]):<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>all_max_cols = _boolrelextrema(matr, np.greater, axis=<NUM_LIT:1>, order=<NUM_LIT:1>)<EOL>has_relmax = np.where(all_max_cols.any(axis=<NUM_LIT:1>))[<NUM_LIT:0>]<EOL>if(len(has_relmax) == <NUM_LIT:0>):<EOL><INDENT>return []<EOL><DEDENT>start_row = has_relmax[-<NUM_LIT:1>]<EOL>ridge_lines = [[[start_row],<EOL>[col],<EOL><NUM_LIT:0>] for col in np.where(all_max_cols[start_row])[<NUM_LIT:0>]]<EOL>final_lines = []<EOL>rows = np.arange(start_row - <NUM_LIT:1>, -<NUM_LIT:1>, -<NUM_LIT:1>)<EOL>cols = np.arange(<NUM_LIT:0>, matr.shape[<NUM_LIT:1>])<EOL>for row in rows:<EOL><INDENT>this_max_cols = cols[all_max_cols[row]]<EOL>for line in ridge_lines:<EOL><INDENT>line[<NUM_LIT:2>] += <NUM_LIT:1><EOL><DEDENT>prev_ridge_cols = np.array([line[<NUM_LIT:1>][-<NUM_LIT:1>] for line in ridge_lines])<EOL>for ind, col in enumerate(this_max_cols):<EOL><INDENT>"""<STR_LIT>"""<EOL>line = None<EOL>if(len(prev_ridge_cols) > <NUM_LIT:0>):<EOL><INDENT>diffs = np.abs(col - prev_ridge_cols)<EOL>closest = np.argmin(diffs)<EOL>if diffs[closest] <= max_distances[row]:<EOL><INDENT>line = ridge_lines[closest]<EOL><DEDENT><DEDENT>if(line is not None):<EOL><INDENT>line[<NUM_LIT:1>].append(col)<EOL>line[<NUM_LIT:0>].append(row)<EOL>line[<NUM_LIT:2>] = <NUM_LIT:0><EOL><DEDENT>else:<EOL><INDENT>new_line = [[row],<EOL>[col],<EOL><NUM_LIT:0>]<EOL>ridge_lines.append(new_line)<EOL><DEDENT><DEDENT>for ind in xrange(len(ridge_lines) - <NUM_LIT:1>, -<NUM_LIT:1>, -<NUM_LIT:1>):<EOL><INDENT>line = ridge_lines[ind]<EOL>if line[<NUM_LIT:2>] > gap_thresh:<EOL><INDENT>final_lines.append(line)<EOL>del ridge_lines[ind]<EOL><DEDENT><DEDENT><DEDENT>out_lines = []<EOL>for line in (final_lines + ridge_lines):<EOL><INDENT>sortargs = np.array(np.argsort(line[<NUM_LIT:0>]))<EOL>rows, cols = np.zeros_like(sortargs), np.zeros_like(sortargs)<EOL>rows[sortargs] = line[<NUM_LIT:0>]<EOL>cols[sortargs] = line[<NUM_LIT:1>]<EOL>out_lines.append([rows, cols])<EOL><DEDENT>return out_lines<EOL>

Identify ridges in the 2-D matrix.

Expect that the width of the wavelet feature increases with increasing row
number.

Parameters
----------
matr : 2-D ndarray
    Matrix in which to identify ridge lines.
max_distances : 1-D sequence
    At each row, a ridge line is only connected
    if the relative max at row[n] is within
    `max_distances`[n] from the relative max at row[n+1].
gap_thresh : int
    If a relative maximum is not found within `max_distances`,
    there will be a gap. A ridge line is discontinued if
    there are more than `gap_thresh` points without connecting
    a new relative maximum.

Returns
-------
ridge_lines : tuple
    Tuple of 2 1-D sequences. `ridge_lines`[ii][0] are the rows of the ii-th
    ridge-line, `ridge_lines`[ii][1] are the columns. Empty if none found.
    Each ridge-line will be sorted by row (increasing), but the order
    of the ridge lines is not specified.

References
----------
Bioinformatics (2006) 22 (17): 2059-2065.
doi: 10.1093/bioinformatics/btl355
http://bioinformatics.oxfordjournals.org/content/22/17/2059.long

Examples
--------
>>> data = np.random.rand(5,5)
>>> ridge_lines = _identify_ridge_lines(data, 1, 1)

Notes
-----
This function is intended to be used in conjunction with `cwt`
as part of `find_peaks_cwt`.


def _filter_ridge_lines(cwt, ridge_lines, window_size=None, min_length=None,<EOL>min_snr=<NUM_LIT:1>, noise_perc=<NUM_LIT:10>):

num_points = cwt.shape[<NUM_LIT:1>]<EOL>if min_length is None:<EOL><INDENT>min_length = np.ceil(cwt.shape[<NUM_LIT:0>] / <NUM_LIT:4>)<EOL><DEDENT>if window_size is None:<EOL><INDENT>window_size = np.ceil(num_points / <NUM_LIT:20>)<EOL><DEDENT>window_size = int(window_size)<EOL>hf_window, odd = divmod(window_size, <NUM_LIT:2>)<EOL>row_one = cwt[<NUM_LIT:0>, :]<EOL>noises = np.zeros_like(row_one)<EOL>for ind, val in enumerate(row_one):<EOL><INDENT>window_start = max(ind - hf_window, <NUM_LIT:0>)<EOL>window_end = min(ind + hf_window + odd, num_points)<EOL>noises[ind] = scoreatpercentile(row_one[window_start:window_end],<EOL>per=noise_perc)<EOL><DEDENT>def filt_func(line):<EOL><INDENT>if len(line[<NUM_LIT:0>]) < min_length:<EOL><INDENT>return False<EOL><DEDENT>snr = abs(cwt[line[<NUM_LIT:0>][<NUM_LIT:0>], line[<NUM_LIT:1>][<NUM_LIT:0>]] / noises[line[<NUM_LIT:1>][<NUM_LIT:0>]])<EOL>if snr < min_snr:<EOL><INDENT>return False<EOL><DEDENT>return True<EOL><DEDENT>return list(filter(filt_func, ridge_lines))<EOL>

Filter ridge lines according to prescribed criteria. Intended
to be used for finding relative maxima.

Parameters
----------
cwt : 2-D ndarray
    Continuous wavelet transform from which the `ridge_lines` were defined.
ridge_lines : 1-D sequence
    Each element should contain 2 sequences, the rows and columns
    of the ridge line (respectively).
window_size : int, optional
    Size of window to use to calculate noise floor.
    Default is ``cwt.shape[1] / 20``.
min_length : int, optional
    Minimum length a ridge line needs to be acceptable.
    Default is ``cwt.shape[0] / 4``, ie 1/4-th the number of widths.
min_snr : float, optional
    Minimum SNR ratio. Default 1. The signal is the value of
    the cwt matrix at the shortest length scale (``cwt[0, loc]``), the
    noise is the `noise_perc`th percentile of datapoints contained within a
    window of `window_size` around ``cwt[0, loc]``.
noise_perc : float, optional
    When calculating the noise floor, percentile of data points
    examined below which to consider noise. Calculated using
    scipy.stats.scoreatpercentile.

References
----------
Bioinformatics (2006) 22 (17): 2059-2065. doi: 10.1093/bioinformatics/btl355
http://bioinformatics.oxfordjournals.org/content/22/17/2059.long


def find_peaks_cwt(vector, widths, wavelet=None, max_distances=None, gap_thresh=None,<EOL>min_length=None, min_snr=<NUM_LIT:1>, noise_perc=<NUM_LIT:10>):

if gap_thresh is None:<EOL><INDENT>gap_thresh = np.ceil(widths[<NUM_LIT:0>])<EOL><DEDENT>if max_distances is None:<EOL><INDENT>max_distances = widths / <NUM_LIT><EOL><DEDENT>if wavelet is None:<EOL><INDENT>wavelet = ricker<EOL><DEDENT>cwt_dat = cwt(vector, wavelet, widths)<EOL>ridge_lines = _identify_ridge_lines(cwt_dat, max_distances, gap_thresh)<EOL>filtered = _filter_ridge_lines(cwt_dat, ridge_lines, min_length=min_length,<EOL>min_snr=min_snr, noise_perc=noise_perc)<EOL>max_locs = [x[<NUM_LIT:1>][<NUM_LIT:0>] for x in filtered]<EOL>return sorted(max_locs)<EOL>

Attempt to find the peaks in a 1-D array.

The general approach is to smooth `vector` by convolving it with
`wavelet(width)` for each width in `widths`. Relative maxima which
appear at enough length scales, and with sufficiently high SNR, are
accepted.

Parameters
----------
vector : ndarray
    1-D array in which to find the peaks.
widths : sequence
    1-D array of widths to use for calculating the CWT matrix. In general,
    this range should cover the expected width of peaks of interest.
wavelet : callable, optional
    Should take a single variable and return a 1-D array to convolve
    with `vector`.  Should be normalized to unit area.
    Default is the ricker wavelet.
max_distances : ndarray, optional
    At each row, a ridge line is only connected if the relative max at
    row[n] is within ``max_distances[n]`` from the relative max at
    ``row[n+1]``.  Default value is ``widths/4``.
gap_thresh : float, optional
    If a relative maximum is not found within `max_distances`,
    there will be a gap. A ridge line is discontinued if there are more
    than `gap_thresh` points without connecting a new relative maximum.
    Default is 2.
min_length : int, optional
    Minimum length a ridge line needs to be acceptable.
    Default is ``cwt.shape[0] / 4``, ie 1/4-th the number of widths.
min_snr : float, optional
    Minimum SNR ratio. Default 1. The signal is the value of
    the cwt matrix at the shortest length scale (``cwt[0, loc]``), the
    noise is the `noise_perc`th percentile of datapoints contained within a
    window of `window_size` around ``cwt[0, loc]``.
noise_perc : float, optional
    When calculating the noise floor, percentile of data points
    examined below which to consider noise. Calculated using
    `stats.scoreatpercentile`.  Default is 10.

Returns
-------
peaks_indices : list
    Indices of the locations in the `vector` where peaks were found.
    The list is sorted.

See Also
--------
cwt

Notes
-----
This approach was designed for finding sharp peaks among noisy data,
however with proper parameter selection it should function well for
different peak shapes.

The algorithm is as follows:
 1. Perform a continuous wavelet transform on `vector`, for the supplied
    `widths`. This is a convolution of `vector` with `wavelet(width)` for
    each width in `widths`. See `cwt`
 2. Identify "ridge lines" in the cwt matrix. These are relative maxima
    at each row, connected across adjacent rows. See identify_ridge_lines
 3. Filter the ridge_lines using filter_ridge_lines.

.. versionadded:: 0.11.0

References
----------
.. [1] Bioinformatics (2006) 22 (17): 2059-2065.
    doi: 10.1093/bioinformatics/btl355
    http://bioinformatics.oxfordjournals.org/content/22/17/2059.long

Examples
--------
>>> from scipy import signal
>>> xs = np.arange(0, np.pi, 0.05)
>>> data = np.sin(xs)
>>> peakind = signal.find_peaks_cwt(data, np.arange(1,10))
>>> peakind, xs[peakind], data[peakind]
([32], array([ 1.6]), array([ 0.9995736]))


ep = atleast_1d(roots(den)) + <NUM_LIT><EOL>tz = atleast_1d(roots(num)) + <NUM_LIT><EOL>if len(ep) == <NUM_LIT:0>:<EOL><INDENT>ep = atleast_1d(-<NUM_LIT:1000>) + <NUM_LIT><EOL><DEDENT>ez = r_['<STR_LIT>',<EOL>numpy.compress(ep.imag >= <NUM_LIT:0>, ep, axis=-<NUM_LIT:1>),<EOL>numpy.compress((abs(tz) < <NUM_LIT>) & (tz.imag >= <NUM_LIT:0>), tz, axis=-<NUM_LIT:1>)]<EOL>integ = abs(ez) < <NUM_LIT><EOL>hfreq = numpy.around(numpy.log10(numpy.max(<NUM_LIT:3> * abs(ez.real + integ) +<EOL><NUM_LIT> * ez.imag)) + <NUM_LIT:0.5>)<EOL>lfreq = numpy.around(numpy.log10(<NUM_LIT:0.1> * numpy.min(abs(real(ez + integ)) +<EOL><NUM_LIT:2> * ez.imag)) - <NUM_LIT:0.5>)<EOL>w = logspace(lfreq, hfreq, N)<EOL>return w<EOL>

Find an array of frequencies for computing the response of a filter.

Parameters
----------
num, den : array_like, 1-D
    The polynomial coefficients of the numerator and denominator of the
    transfer function of the filter or LTI system.  The coefficients are
    ordered from highest to lowest degree.
N : int
    The length of the array to be computed.

Returns
-------
w : (N,) ndarray
    A 1-D array of frequencies, logarithmically spaced.

Examples
--------
Find a set of nine frequencies that span the "interesting part" of the
frequency response for the filter with the transfer function

    H(s) = s / (s^2 + 8s + 25)

>>> findfreqs([1, 0], [1, 8, 25], N=9)
array([  1.00000000e-02,   3.16227766e-02,   1.00000000e-01,
         3.16227766e-01,   1.00000000e+00,   3.16227766e+00,
         1.00000000e+01,   3.16227766e+01,   1.00000000e+02])


if worN is None:<EOL><INDENT>w = findfreqs(b, a, <NUM_LIT:200>)<EOL><DEDENT>elif isinstance(worN, int):<EOL><INDENT>N = worN<EOL>w = findfreqs(b, a, N)<EOL><DEDENT>else:<EOL><INDENT>w = worN<EOL><DEDENT>w = atleast_1d(w)<EOL>s = <NUM_LIT> * w<EOL>h = polyval(b, s) / polyval(a, s)<EOL>if plot is not None:<EOL><INDENT>plot(w, h)<EOL><DEDENT>return w, h<EOL>

Compute frequency response of analog filter.

Given the numerator `b` and denominator `a` of a filter, compute its
frequency response::

         b[0]*(jw)**(nb-1) + b[1]*(jw)**(nb-2) + ... + b[nb-1]
 H(w) = -------------------------------------------------------
         a[0]*(jw)**(na-1) + a[1]*(jw)**(na-2) + ... + a[na-1]

Parameters
----------
b : ndarray
    Numerator of a linear filter.
a : ndarray
    Denominator of a linear filter.
worN : {None, int}, optional
    If None, then compute at 200 frequencies around the interesting parts
    of the response curve (determined by pole-zero locations).  If a single
    integer, then compute at that many frequencies.  Otherwise, compute the
    response at the angular frequencies (e.g. rad/s) given in `worN`.
plot : callable
    A callable that takes two arguments. If given, the return parameters
    `w` and `h` are passed to plot. Useful for plotting the frequency
    response inside `freqs`.

Returns
-------
w : ndarray
    The angular frequencies at which h was computed.
h : ndarray
    The frequency response.

See Also
--------
freqz : Compute the frequency response of a digital filter.

Notes
-----
Using Matplotlib's "plot" function as the callable for `plot` produces
unexpected results,  this plots the real part of the complex transfer
function, not the magnitude.  Try ``lambda w, h: plot(w, abs(h))``.

Examples
--------
>>> from scipy.signal import freqs, iirfilter

>>> b, a = iirfilter(4, [1, 10], 1, 60, analog=True, ftype='cheby1')

>>> w, h = freqs(b, a, worN=np.logspace(-1, 2, 1000))

>>> import matplotlib.pyplot as plt
>>> plt.semilogx(w, 20 * np.log10(abs(h)))
>>> plt.xlabel('Frequency')
>>> plt.ylabel('Amplitude response [dB]')
>>> plt.grid()
>>> plt.show()


def freqz(b, a=<NUM_LIT:1>, worN=None, whole=<NUM_LIT:0>, plot=None):

b, a = map(atleast_1d, (b, a))<EOL>if whole:<EOL><INDENT>lastpoint = <NUM_LIT:2> * pi<EOL><DEDENT>else:<EOL><INDENT>lastpoint = pi<EOL><DEDENT>if worN is None:<EOL><INDENT>N = <NUM_LIT><EOL>w = numpy.linspace(<NUM_LIT:0>, lastpoint, N, endpoint=False)<EOL><DEDENT>elif isinstance(worN, int):<EOL><INDENT>N = worN<EOL>w = numpy.linspace(<NUM_LIT:0>, lastpoint, N, endpoint=False)<EOL><DEDENT>else:<EOL><INDENT>w = worN<EOL><DEDENT>w = atleast_1d(w)<EOL>zm1 = exp(-<NUM_LIT> * w)<EOL>h = polyval(b[::-<NUM_LIT:1>], zm1) / polyval(a[::-<NUM_LIT:1>], zm1)<EOL>if plot is not None:<EOL><INDENT>plot(w, h)<EOL><DEDENT>return w, h<EOL>

Compute the frequency response of a digital filter.

Given the numerator `b` and denominator `a` of a digital filter,
compute its frequency response::

           jw               -jw            -jmw
    jw  B(e)    b[0] + b[1]e + .... + b[m]e
 H(e) = ---- = ------------------------------------
           jw               -jw            -jnw
        A(e)    a[0] + a[1]e + .... + a[n]e

Parameters
----------
b : ndarray
    numerator of a linear filter
a : ndarray
    denominator of a linear filter
worN : {None, int, array_like}, optional
    If None (default), then compute at 512 frequencies equally spaced
    around the unit circle.
    If a single integer, then compute at that many frequencies.
    If an array_like, compute the response at the frequencies given (in
    radians/sample).
whole : bool, optional
    Normally, frequencies are computed from 0 to the Nyquist frequency,
    pi radians/sample (upper-half of unit-circle).  If `whole` is True,
    compute frequencies from 0 to 2*pi radians/sample.
plot : callable
    A callable that takes two arguments. If given, the return parameters
    `w` and `h` are passed to plot. Useful for plotting the frequency
    response inside `freqz`.

Returns
-------
w : ndarray
    The normalized frequencies at which h was computed, in radians/sample.
h : ndarray
    The frequency response.

Notes
-----
Using Matplotlib's "plot" function as the callable for `plot` produces
unexpected results,  this plots the real part of the complex transfer
function, not the magnitude.  Try ``lambda w, h: plot(w, abs(h))``.

Examples
--------
>>> from scipy import signal
>>> b = signal.firwin(80, 0.5, window=('kaiser', 8))
>>> w, h = signal.freqz(b)

>>> import matplotlib.pyplot as plt
>>> fig = plt.figure()
>>> plt.title('Digital filter frequency response')
>>> ax1 = fig.add_subplot(111)

>>> plt.plot(w, 20 * np.log10(abs(h)), 'b')
>>> plt.ylabel('Amplitude [dB]', color='b')
>>> plt.xlabel('Frequency [rad/sample]')

>>> ax2 = ax1.twinx()
>>> angles = np.unwrap(np.angle(h))
>>> plt.plot(w, angles, 'g')
>>> plt.ylabel('Angle (radians)', color='g')
>>> plt.grid()
>>> plt.axis('tight')
>>> plt.show()


b, a = normalize(b, a)<EOL>b = (b + <NUM_LIT:0.0>) / a[<NUM_LIT:0>]<EOL>a = (a + <NUM_LIT:0.0>) / a[<NUM_LIT:0>]<EOL>k = b[<NUM_LIT:0>]<EOL>b /= b[<NUM_LIT:0>]<EOL>z = roots(b)<EOL>p = roots(a)<EOL>return z, p, k<EOL>

r"""Return zero, pole, gain (z,p,k) representation from a numerator,
    denominator representation of a linear filter.

    Parameters
    ----------
    b : ndarray
        Numerator polynomial.
    a : ndarray
        Denominator polynomial.

    Returns
    -------
    z : ndarray
        Zeros of the transfer function.
    p : ndarray
        Poles of the transfer function.
    k : float
        System gain.

    Notes
    -----
    If some values of `b` are too close to 0, they are removed. In that case,
    a BadCoefficients warning is emitted.

    The `b` and `a` arrays are interpreted as coefficients for positive,
    descending powers of the transfer function variable.  So the inputs
    :math:`b = [b_0, b_1, ..., b_M]` and :math:`a =[a_0, a_1, ..., a_N]`
    can represent an analog filter of the form:

    .. math::

        H(s) = \frac
        {b_0 s^M + b_1 s^{(M-1)} + \cdots + b_M}
        {a_0 s^N + a_1 s^{(N-1)} + \cdots + a_N}

    or a discrete-time filter of the form:

    .. math::

        H(z) = \frac
        {b_0 z^M + b_1 z^{(M-1)} + \cdots + b_M}
        {a_0 z^N + a_1 z^{(N-1)} + \cdots + a_N}

    This "positive powers" form is found more commonly in controls
    engineering.  If `M` and `N` are equal (which is true for all filters
    generated by the bilinear transform), then this happens to be equivalent
    to the "negative powers" discrete-time form preferred in DSP:

    .. math::

        H(z) = \frac
        {b_0 + b_1 z^{-1} + \cdots + b_M z^{-M}}
        {a_0 + a_1 z^{-1} + \cdots + a_N z^{-N}}

    Although this is true for common filters, remember that this is not true
    in the general case.  If `M` and `N` are not equal, the discrete-time
    transfer function coefficients must first be converted to the "positive
    powers" form before finding the poles and zeros.


z = atleast_1d(z)<EOL>k = atleast_1d(k)<EOL>if len(z.shape) > <NUM_LIT:1>:<EOL><INDENT>temp = poly(z[<NUM_LIT:0>])<EOL>b = zeros((z.shape[<NUM_LIT:0>], z.shape[<NUM_LIT:1>] + <NUM_LIT:1>), temp.dtype.char)<EOL>if len(k) == <NUM_LIT:1>:<EOL><INDENT>k = [k[<NUM_LIT:0>]] * z.shape[<NUM_LIT:0>]<EOL><DEDENT>for i in range(z.shape[<NUM_LIT:0>]):<EOL><INDENT>b[i] = k[i] * poly(z[i])<EOL><DEDENT><DEDENT>else:<EOL><INDENT>b = k * poly(z)<EOL><DEDENT>a = atleast_1d(poly(p))<EOL>if issubclass(b.dtype.type, numpy.complexfloating):<EOL><INDENT>roots = numpy.asarray(z, complex)<EOL>pos_roots = numpy.compress(roots.imag > <NUM_LIT:0>, roots)<EOL>neg_roots = numpy.conjugate(numpy.compress(roots.imag < <NUM_LIT:0>, roots))<EOL>if len(pos_roots) == len(neg_roots):<EOL><INDENT>if numpy.all(numpy.sort_complex(neg_roots) ==<EOL>numpy.sort_complex(pos_roots)):<EOL><INDENT>b = b.real.copy()<EOL><DEDENT><DEDENT><DEDENT>if issubclass(a.dtype.type, numpy.complexfloating):<EOL><INDENT>roots = numpy.asarray(p, complex)<EOL>pos_roots = numpy.compress(roots.imag > <NUM_LIT:0>, roots)<EOL>neg_roots = numpy.conjugate(numpy.compress(roots.imag < <NUM_LIT:0>, roots))<EOL>if len(pos_roots) == len(neg_roots):<EOL><INDENT>if numpy.all(numpy.sort_complex(neg_roots) ==<EOL>numpy.sort_complex(pos_roots)):<EOL><INDENT>a = a.real.copy()<EOL><DEDENT><DEDENT><DEDENT>return b, a<EOL>

Return polynomial transfer function representation from zeros
    and poles

    Parameters
    ----------
    z : ndarray
        Zeros of the transfer function.
    p : ndarray
        Poles of the transfer function.
    k : float
        System gain.

    Returns
    -------
    b : ndarray
        Numerator polynomial.
    a : ndarray
        Denominator polynomial.