
˽Xc            @` s  d  d l  m Z m Z m Z d  d l Z d  d l Z d  d l Z d  d l Z d d l m	 Z	 m
 Z
 d d l m Z m Z d  d l m Z d  d l m Z d  d l m Z m Z d  d	 l m Z m Z m Z m Z m Z m Z m Z m Z m Z m Z m  Z  m! Z! m" Z" m# Z# m$ Z$ m% Z% m& Z& m' Z' m( Z( m) Z) m* Z* m+ Z+ m, Z, m- Z- m. Z. m/ Z/ m0 Z0 m1 Z1 m2 Z2 m3 Z3 m4 Z4 m5 Z5 m6 Z6 m7 Z7 m8 Z8 m9 Z9 m: Z: m; Z; d  d l Z< d  d l= Z= d  d
 l> m? Z? d d l@ mA ZA d d lB mC ZC mD ZD mE ZE mF ZF mG ZG d d lH mI ZI mJ ZJ d d lK mL ZL e jM jN d k rYe jM jO d k rYd  d l= mP ZP n d  d lQ mP ZP d d d d d d d d d d d d d d d  d! d" d# d$ d% d& d' d( d) d* d+ d, d- d. d/ d0 g ZR i d  d1 6d d2 6d3 d4 6ZS i d  d5 6d  d6 6d3 d7 6d3 d8 6d d9 6d d: 6d; d< 6ZT e e< jU  d= k ZV e jW   ZX d>   ZY d?   ZZ d@   Z[ d4 dA dB  Z\ dC   Z] d4 dD  Z^ dE dF  Z_ dG   Z` dH   Za dI   Zb dJ   Zc dK   Zd dL dL d dM  Ze d4 ef dN  Zg d4 dA dO  Zh dP   Zi d dQ  Zk d d dR  Zl d4 d5 d  dS  Zm d4 d5 d  dT  Zn d dU  Zo dV d dW  Zp d dX  Zq dY   Zr d dV dZ  Zs d d[  Zt d\   Zu d] d^ d_  Zv d] d` da  Zw d] d` db  Zx d] d` dc  Zy d] d` dd  Zz d d  d de  Z{ d  dv dh  Z| di   Z} dV dj d  dk  Z~ dl   Z dm   Z dV d dn  Z dV do d d6 d dp  Z dq   Z dV d dr  Z dV do d ds  Z d dt dV d du  Z d S(w   i    (   t   divisiont   print_functiont   absolute_importNi   (   t   sigtoolst   dlti(   t   upfirdnt   _output_len(   t   callable(   t   NumpyVersion(   t   fftpackt   linalg(&   t   allcloset   anglet   aranget   argsortt   arrayt   asarrayt
   atleast_1dt
   atleast_2dt   castt   dott   expt   expand_dimst   iscomplexobjt   meant   ndarrayt   newaxist   onest   pit   polyt   polyaddt   polydert   polydivt   polymult   polysubt   polyvalt   productt   r_t   ravelt   real_if_closet   reshapet   rootst   sortt   taket	   transposet   uniquet   wheret   zerost
   zeros_like(   t	   factorial(   t
   get_window(   t
   axis_slicet   axis_reverset   odd_extt   even_extt	   const_ext(   t   cheby1t   _validate_sos(   t   firwini   i   (   t   gcdt	   correlatet   fftconvolvet   convolvet
   convolve2dt   correlate2dt   order_filtert   medfiltt	   medfilt2dt   wienert   lfiltert   lfiltict   sosfiltt
   deconvolvet   hilbertt   hilbert2t
   cmplx_sortt   unique_rootst   invrest   invreszt   residuet   residuezt   resamplet   resample_polyt   detrendt
   lfilter_zit
   sosfilt_zit   sosfiltfiltt   choose_conv_methodt   filtfiltt   decimatet   vectorstrengtht   validt   samei   t   fullt   fillt   padt   wrapt   circulart   symmt	   symmetrici   t   reflects   1.9.0.dev-e24486ec         C` sG   y t  |  } Wn2 t k
 rB |  d k r9 t d   n  |  } n X| S(   Ni    i   i   sA   Acceptable mode flags are 'valid' (0), 'same' (1), or 'full' (2).(   i    i   i   (   t	   _modedictt   KeyErrort
   ValueError(   t   modet   val(    (    s7   /tmp/pip-build-7oUkmx/scipy/scipy/signal/signaltools.pyt   _valfrommode9   s    
c         C` sO   y t  |  d >} Wn6 t k
 rJ | d k r= t d   n  |  d >} n X| S(   Ni   i    i   s]   Acceptable boundary flags are 'fill', 'wrap' (or 'circular'), 
  and 'symm' (or 'symmetric').(   i    i   i   (   t   _boundarydictRf   Rg   (   t   boundaryRi   (    (    s7   /tmp/pip-build-7oUkmx/scipy/scipy/signal/signaltools.pyt   _bvalfromboundaryD   s    c         C` s   |  d k r t  t  } } xG t | |  D]6 \ } } | | k sJ t } n  | | k s) t } q) q) W| pl | s~ t d   n  | St S(   s  
    If in 'valid' mode, returns whether or not the input arrays need to be
    swapped depending on whether `shape1` is at least as large as `shape2` in
    every dimension.

    This is important for some of the correlation and convolution
    implementations in this module, where the larger array input needs to come
    before the smaller array input when operating in this mode.

    Note that if the mode provided is not 'valid', False is immediately
    returned.
    R[   sO   For 'valid' mode, one must be at least as large as the other in every dimension(   t   Truet   zipt   FalseRg   (   Rh   t   shape1t   shape2t   ok1t   ok2t   d1t   d2(    (    s7   /tmp/pip-build-7oUkmx/scipy/scipy/signal/signaltools.pyt   _inputs_swap_neededP   s    	t   autoc         C` s  t  |   }  t  |  } |  j | j k o5 d k n rB |  | S|  j | j k rc t d   n  y t | } Wn t k
 r t d   n X| d
 k r t |  t |  | |  St |  | |  r t j	 |  | |  S| d k r | j
 |  j
 k pt | |  j | j  } | r'| |  }  } n  | d k rg  t |  j | j  D] \ } } | | d ^ qI} t j | |  j  }	 t j |  | |	 |  }
 n g  t |  j | j  D] \ } } | | d ^ q} t j | |  j  } g  |  j D] } t d |  ^ q} |  j   | | <| d k r=t j | |  j  }	 n' | d	 k rdt j |  j |  j  }	 n  t j | | |	 |  }
 | rt |
  }
 n  |
 S(   s  
    Cross-correlate two N-dimensional arrays.

    Cross-correlate `in1` and `in2`, with the output size determined by the
    `mode` argument.

    Parameters
    ----------
    in1 : array_like
        First input.
    in2 : array_like
        Second input. Should have the same number of dimensions as `in1`.
    mode : str {'full', 'valid', 'same'}, optional
        A string indicating the size of the output:

        ``full``
           The output is the full discrete linear cross-correlation
           of the inputs. (Default)
        ``valid``
           The output consists only of those elements that do not
           rely on the zero-padding. In 'valid' mode, either `in1` or `in2`
           must be at least as large as the other in every dimension.
        ``same``
           The output is the same size as `in1`, centered
           with respect to the 'full' output.
    method : str {'auto', 'direct', 'fft'}, optional
        A string indicating which method to use to calculate the correlation.

        ``direct``
           The correlation is determined directly from sums, the definition of
           correlation.
        ``fft``
           The Fast Fourier Transform is used to perform the correlation more
           quickly (only available for numerical arrays.)
        ``auto``
           Automatically chooses direct or Fourier method based on an estimate
           of which is faster (default).  See `convolve` Notes for more detail.

           .. versionadded:: 0.19.0

    Returns
    -------
    correlate : array
        An N-dimensional array containing a subset of the discrete linear
        cross-correlation of `in1` with `in2`.

    See Also
    --------
    choose_conv_method : contains more documentation on `method`.

    Notes
    -----
    The correlation z of two d-dimensional arrays x and y is defined as::

        z[...,k,...] = sum[..., i_l, ...] x[..., i_l,...] * conj(y[..., i_l - k,...])

    This way, if x and y are 1-D arrays and ``z = correlate(x, y, 'full')`` then
      
    .. math::

          z[k] = (x * y)(k - N + 1) 
               = \sum_{l=0}^{||x||-1}x_l y_{l-k+N-1}^{*}

    for :math:`k = 0, 1, ..., ||x|| + ||y|| - 2`

    where :math:`||x||` is the length of ``x``, :math:`N = \max(||x||,||y||)`,
    and :math:`y_m` is 0 when m is outside the range of y.

    ``method='fft'`` only works for numerical arrays as it relies on
    `fftconvolve`. In certain cases (i.e., arrays of objects or when
    rounding integers can lose precision), ``method='direct'`` is always used.

    Examples
    --------
    Implement a matched filter using cross-correlation, to recover a signal
    that has passed through a noisy channel.

    >>> from scipy import signal
    >>> sig = np.repeat([0., 1., 1., 0., 1., 0., 0., 1.], 128)
    >>> sig_noise = sig + np.random.randn(len(sig))
    >>> corr = signal.correlate(sig_noise, np.ones(128), mode='same') / 128

    >>> import matplotlib.pyplot as plt
    >>> clock = np.arange(64, len(sig), 128)
    >>> fig, (ax_orig, ax_noise, ax_corr) = plt.subplots(3, 1, sharex=True)
    >>> ax_orig.plot(sig)
    >>> ax_orig.plot(clock, sig[clock], 'ro')
    >>> ax_orig.set_title('Original signal')
    >>> ax_noise.plot(sig_noise)
    >>> ax_noise.set_title('Signal with noise')
    >>> ax_corr.plot(corr)
    >>> ax_corr.plot(clock, corr[clock], 'ro')
    >>> ax_corr.axhline(0.5, ls=':')
    >>> ax_corr.set_title('Cross-correlated with rectangular pulse')
    >>> ax_orig.margins(0, 0.1)
    >>> fig.tight_layout()
    >>> fig.show()

    i    s/   in1 and in2 should have the same dimensionalitys5   Acceptable mode flags are 'valid', 'same', or 'full'.t   fftRx   R]   R[   i   R\   (   s   fftRx   (   R   t   ndimRg   Re   Rf   R>   t   _reverse_and_conjt   _np_conv_okt   npR<   t   sizeRw   t   shapeRo   t   emptyt   dtypeR   t   _correlateNDR/   t   slicet   copy(   t   in1t   in2Rh   t   methodRi   t   swapped_inputst   it   jt   pst   outt   zt
   in1zpaddedt   sc(    (    s7   /tmp/pip-build-7oUkmx/scipy/scipy/signal/signaltools.pyR<   o   sD    d"66%c         C` sw   t  |  } t |  j  } | | d } | | } g  t t |   D] } t | | | |  ^ qF } |  t |  S(   Ni   (   R   R   R   t   ranget   lenR   t   tuple(   t   arrt   newshapet	   currshapet   startindt   endindt   kt   myslice(    (    s7   /tmp/pip-build-7oUkmx/scipy/scipy/signal/signaltools.pyt	   _centered  s    
6c      
   C` s  t  |   }  t  |  } |  j | j k o5 d k n rB |  | S|  j | j k sc t d   n( |  j d k s | j d k r t g   St |  j  } t | j  } t j |  j t	  p t j | j t	  } | | d } t
 | | |  r| | |  | f \ }  } } } n  g  | D] } t j j t |   ^ q} t g  | D] }	 t d t |	   ^ qI }
 | rt st j t  rzQ t j j |  |  } t j j | |  } t j j | | |  |
 j   } Wd t st j   n  XnS t j |  |  } t j | |  } t j | |  |
 j   } | sG| j } n  | d k rW| S| d k rpt | |  S| d k rt | | | d  St d   d S(	   s  Convolve two N-dimensional arrays using FFT.

    Convolve `in1` and `in2` using the fast Fourier transform method, with
    the output size determined by the `mode` argument.

    This is generally much faster than `convolve` for large arrays (n > ~500),
    but can be slower when only a few output values are needed, and can only
    output float arrays (int or object array inputs will be cast to float).

    As of v0.19, `convolve` automatically chooses this method or the direct
    method based on an estimation of which is faster.

    Parameters
    ----------
    in1 : array_like
        First input.
    in2 : array_like
        Second input. Should have the same number of dimensions as `in1`.
        If operating in 'valid' mode, either `in1` or `in2` must be
        at least as large as the other in every dimension.
    mode : str {'full', 'valid', 'same'}, optional
        A string indicating the size of the output:

        ``full``
           The output is the full discrete linear convolution
           of the inputs. (Default)
        ``valid``
           The output consists only of those elements that do not
           rely on the zero-padding.
        ``same``
           The output is the same size as `in1`, centered
           with respect to the 'full' output.

    Returns
    -------
    out : array
        An N-dimensional array containing a subset of the discrete linear
        convolution of `in1` with `in2`.

    Examples
    --------
    Autocorrelation of white noise is an impulse.

    >>> from scipy import signal
    >>> sig = np.random.randn(1000)
    >>> autocorr = signal.fftconvolve(sig, sig[::-1], mode='full')

    >>> import matplotlib.pyplot as plt
    >>> fig, (ax_orig, ax_mag) = plt.subplots(2, 1)
    >>> ax_orig.plot(sig)
    >>> ax_orig.set_title('White noise')
    >>> ax_mag.plot(np.arange(-len(sig)+1,len(sig)), autocorr)
    >>> ax_mag.set_title('Autocorrelation')
    >>> fig.tight_layout()
    >>> fig.show()

    Gaussian blur implemented using FFT convolution.  Notice the dark borders
    around the image, due to the zero-padding beyond its boundaries.
    The `convolve2d` function allows for other types of image boundaries,
    but is far slower.

    >>> from scipy import misc
    >>> face = misc.face(gray=True)
    >>> kernel = np.outer(signal.gaussian(70, 8), signal.gaussian(70, 8))
    >>> blurred = signal.fftconvolve(face, kernel, mode='same')

    >>> fig, (ax_orig, ax_kernel, ax_blurred) = plt.subplots(3, 1,
    ...                                                      figsize=(6, 15))
    >>> ax_orig.imshow(face, cmap='gray')
    >>> ax_orig.set_title('Original')
    >>> ax_orig.set_axis_off()
    >>> ax_kernel.imshow(kernel, cmap='gray')
    >>> ax_kernel.set_title('Gaussian kernel')
    >>> ax_kernel.set_axis_off()
    >>> ax_blurred.imshow(blurred, cmap='gray')
    >>> ax_blurred.set_title('Blurred')
    >>> ax_blurred.set_axis_off()
    >>> fig.show()

    i    s/   in1 and in2 should have the same dimensionalityi   NR]   R\   R[   s5   Acceptable mode flags are 'valid', 'same', or 'full'.(   R   Rz   Rg   R~   R   R   R}   t
   issubdtypeR   t   complexRw   R	   t   helpert   next_fast_lent   intR   R   t   _rfft_mt_safet
   _rfft_lockt   acquireRp   Ry   t   rfftnt   irfftnR   t   releaset   fftnt   ifftnt   realR   (   R   R   Rh   t   s1t   s2t   complex_resultR   t   dt   fshapet   szt   fslicet   sp1t   sp2t   ret(    (    s7   /tmp/pip-build-7oUkmx/scipy/scipy/signal/signaltools.pyR=     sH    Q"
!+.'t   buifcc         C` sM   t  |   t k r" |  j j | k Sx$ |  D] } | j j | k r) t Sq) Wt S(   sl  
    See if a list of arrays are all numeric.

    Parameters
    ----------
    ndarrays : array or list of arrays
        arrays to check if numeric.
    numeric_kinds : string-like
        The dtypes of the arrays to be checked. If the dtype.kind of
        the ndarrays are not in this string the function returns False and
        otherwise returns True.
    (   t   typeR   R   t   kindRp   Rn   (   t   arrayst   kindst   array_(    (    s7   /tmp/pip-build-7oUkmx/scipy/scipy/signal/signaltools.pyt   _numeric_arrays  s    c         C` s%   d } x |  D] } | | 9} q W| S(   sb   
    Product of a list of numbers.
    Faster than np.prod for short lists like array shapes.
    i   (    (   t   iterableR$   t   x(    (    s7   /tmp/pip-build-7oUkmx/scipy/scipy/signal/signaltools.pyt   _prod  s    c   	      C` so  | d k r` g  t  |  j | j  D] \ } } | | d ^ q" } |  j d k rW d n d } n | d k r |  j } |  j d k r | j |  j k r d } q d } qd } nl | d	 k rg  t  |  j | j  D] \ } } | | d ^ q } |  j d k rd
 n d } n t d   |  j | j t |  } t d   |  j | j t |  D  } | | | k  S(   s  
    See if using `fftconvolve` or `_correlateND` is faster. The boolean value
    returned depends on the sizes and shapes of the input values.

    The big O ratios were found to hold across different machines, which makes
    sense as it's the ratio that matters (the effective speed of the computer
    is found in both big O constants). Regardless, this had been tuned on an
    early 2015 MacBook Pro with 8GB RAM and an Intel i5 processor.
    R]   i   gyNi@g|s$a@R\   gbξi@g{AƊ@g@R[   gsGH|@g~J S9@s   mode is invalidc         s` s"   |  ] } | t  j |  Vq d  S(   N(   t   matht   log(   t   .0t   n(    (    s7   /tmp/pip-build-7oUkmx/scipy/scipy/signal/signaltools.pys	   <genexpr>  s    (   Ro   R   Rz   R~   Rg   R   t   sumR   (	   R   t   hRh   R   R   t	   out_shapet   big_O_constantt   direct_timet   fft_time(    (    s7   /tmp/pip-build-7oUkmx/scipy/scipy/signal/signaltools.pyt   _fftconv_faster  s$    
6				6c         C` s*   t  d d d  g |  j } |  | j   S(   sO   
    Reverse array `x` in all dimensions and perform the complex conjugate
    iN(   R   t   NoneRz   t   conj(   R   t   reverse(    (    s7   /tmp/pip-build-7oUkmx/scipy/scipy/signal/signaltools.pyR{     s    c         C` sD   |  j  | j  k o d k n } | oC |  j | j k pC | d k S(   s   
    See if numpy supports convolution of `volume` and `kernel` (i.e. both are
    1D ndarrays and of the appropriate shape).  Numpy's 'same' mode uses the
    size of the larger input, while Scipy's uses the size of the first input.
    i   R\   (   Rz   R~   (   t   volumet   kernelRh   t
   np_conv_ok(    (    s7   /tmp/pip-build-7oUkmx/scipy/scipy/signal/signaltools.pyR|     s    "c         C` s  xH d d g D]: } t  t |  r |  j | k s@ | j | k rG t Sq q Wt g  |  | g D] } t | g d d ^ q[  r t t j |   j    t t j |  j    } | t t	 |  j
 | j
   9} | d t j d  j d k r t Sn  t |  | g  rt St S(   Nt
   complex256t
   complex192R   t   uii   t   floati   (   t   hasattrR}   R   Rp   t   anyR   R   t   abst   maxt   minR~   t   finfot   nmantRn   (   R   R   t   not_fft_conv_suppR   t	   max_value(    (    s7   /tmp/pip-build-7oUkmx/scipy/scipy/signal/signaltools.pyt   _fftconvolve_valid  s    44 t   passc   
      C` s   t  j |  |  } d } x@ t d d  D]/ } d | } | j  |  } | d k r( Pq( q( W| d k rp | } n( | d 9} | j | |  } t |  } | | }	 |	 S(   s  
    Returns the time the statement/function took, in seconds.

    Faster, less precise version of IPython's timeit. `stmt` can be a statement
    written as a string or a callable.

    Will do only 1 loop (like IPython's timeit) with no repetitions
    (unlike IPython) for very slow functions.  For fast functions, only does
    enough loops to take 5 ms, which seems to produce similar results (on
    Windows at least), and avoids doing an extraneous cycle that isn't
    measured.

    i    i
   g{Gzt?i   gMb@?(   t   timeitt   TimerR   t   repeatR   (
   t   stmtt   setupR   t   timerR   t   pt   numbert   bestt   rt   sec(    (    s7   /tmp/pip-build-7oUkmx/scipy/scipy/signal/signaltools.pyt   _timeit_fast  s    
	

c   	      ` s  t  |    t  |    | r i  } x6 d d g D](  t      f d    |  <q1 W| d | d k  rw d n d } | | f St j d k r d n d } t t |  r  j | k s   j | k r d Sn  t g     g D] } t | g d d	 ^ q  rt	 t j
   j    t	 t j
    j    } | t	 t  j   j   9} | d t j d
  j d k rd Sn  t    g  rt      rd Sn  d S(   s!  
    Find the fastest convolution/correlation method.

    This primarily exists to be called during the ``method='auto'`` option in
    `convolve` and `correlate`, but can also be used when performing many
    convolutions of the same input shapes and dtypes, determining
    which method to use for all of them, either to avoid the overhead of the
    'auto' option or to use accurate real-world measurements.

    Parameters
    ----------
    in1 : array_like
        The first argument passed into the convolution function.
    in2 : array_like
        The second argument passed into the convolution function.
    mode : str {'full', 'valid', 'same'}, optional
        A string indicating the size of the output:

        ``full``
           The output is the full discrete linear convolution
           of the inputs. (Default)
        ``valid``
           The output consists only of those elements that do not
           rely on the zero-padding.
        ``same``
           The output is the same size as `in1`, centered
           with respect to the 'full' output.
    measure : bool, optional
        If True, run and time the convolution of `in1` and `in2` with both
        methods and return the fastest. If False (default), predict the fastest
        method using precomputed values.

    Returns
    -------
    method : str
        A string indicating which convolution method is fastest, either
        'direct' or 'fft'
    times : dict, optional
        A dictionary containing the times (in seconds) needed for each method.
        This value is only returned if ``measure=True``.

    See Also
    --------
    convolve
    correlate

    Notes
    -----
    For large n, ``measure=False`` is accurate and can quickly determine the
    fastest method to perform the convolution.  However, this is not as
    accurate for small n (when any dimension in the input or output is small).

    In practice, we found that this function estimates the faster method up to
    a multiplicative factor of 5 (i.e., the estimated method is *at most* 5
    times slower than the fastest method). The estimation values were tuned on
    an early 2015 MacBook Pro with 8GB RAM but we found that the prediction
    held *fairly* accurately across different machines.

    If ``measure=True``, time the convolutions. Because this function uses
    `fftconvolve`, an error will be thrown if it does not support the inputs.
    There are cases when `fftconvolve` supports the inputs but this function
    returns `direct` (e.g., to protect against floating point integer
    precision).

    .. versionadded:: 0.19

    Examples
    --------
    Estimate the fastest method for a given input:

    >>> from scipy import signal
    >>> a = np.random.randn(1000)
    >>> b = np.random.randn(1000000)
    >>> method = signal.choose_conv_method(a, b, mode='same')
    >>> method
    'fft'

    This can then be applied to other arrays of the same dtype and shape:

    >>> c = np.random.randn(1000)
    >>> d = np.random.randn(1000000)
    >>> # `method` works with correlate and convolve
    >>> corr1 = signal.correlate(a, b, mode='same', method=method)
    >>> corr2 = signal.correlate(c, d, mode='same', method=method)
    >>> conv1 = signal.convolve(a, b, mode='same', method=method)
    >>> conv2 = signal.convolve(c, d, mode='same', method=method)

    Ry   t   directc           ` s   t     d  d  S(   NRh   R   (   R>   (    (   R   R   Rh   R   (    s7   /tmp/pip-build-7oUkmx/scipy/scipy/signal/signaltools.pyt   <lambda>  s   i   i    R   R   R   R   R   i   I       (   R   R   t   syst   maxsizeR   R}   R   R   R   R   R   R   R   R~   R   R   R   (	   R   R   Rh   t   measuret   timest   chosen_methodt   fftconv_unsupR   R   (    (   R   R   Rh   R   s7   /tmp/pip-build-7oUkmx/scipy/scipy/signal/signaltools.pyRW   2  s*    Y& 
44 c         C` s!  t  |   } t  |  } | j | j k o5 d k n rB | | St | | j | j  rj | | } } n  | d k r t | | d | } n  | d k r t | | d | } | j j d k r t j	 |  } n  | j
 | j  St | | |  rt j | | |  St | t |  | d  S(   s  
    Convolve two N-dimensional arrays.

    Convolve `in1` and `in2`, with the output size determined by the
    `mode` argument.

    Parameters
    ----------
    in1 : array_like
        First input.
    in2 : array_like
        Second input. Should have the same number of dimensions as `in1`.
    mode : str {'full', 'valid', 'same'}, optional
        A string indicating the size of the output:

        ``full``
           The output is the full discrete linear convolution
           of the inputs. (Default)
        ``valid``
           The output consists only of those elements that do not
           rely on the zero-padding. In 'valid' mode, either `in1` or `in2`
           must be at least as large as the other in every dimension.
        ``same``
           The output is the same size as `in1`, centered
           with respect to the 'full' output.
    method : str {'auto', 'direct', 'fft'}, optional
        A string indicating which method to use to calculate the convolution.

        ``direct``
           The convolution is determined directly from sums, the definition of
           convolution.
        ``fft``
           The Fourier Transform is used to perform the convolution by calling
           `fftconvolve`.
        ``auto``
           Automatically chooses direct or Fourier method based on an estimate
           of which is faster (default).  See Notes for more detail.

           .. versionadded:: 0.19.0

    Returns
    -------
    convolve : array
        An N-dimensional array containing a subset of the discrete linear
        convolution of `in1` with `in2`.

    See Also
    --------
    numpy.polymul : performs polynomial multiplication (same operation, but
                    also accepts poly1d objects)
    choose_conv_method : chooses the fastest appropriate convolution method
    fftconvolve

    Notes
    -----
    By default, `convolve` and `correlate` use ``method='auto'``, which calls
    `choose_conv_method` to choose the fastest method using pre-computed
    values (`choose_conv_method` can also measure real-world timing with a
    keyword argument). Because `fftconvolve` relies on floating point numbers,
    there are certain constraints that may force `method=direct` (more detail
    in `choose_conv_method` docstring).

    Examples
    --------
    Smooth a square pulse using a Hann window:

    >>> from scipy import signal
    >>> sig = np.repeat([0., 1., 0.], 100)
    >>> win = signal.hann(50)
    >>> filtered = signal.convolve(sig, win, mode='same') / sum(win)

    >>> import matplotlib.pyplot as plt
    >>> fig, (ax_orig, ax_win, ax_filt) = plt.subplots(3, 1, sharex=True)
    >>> ax_orig.plot(sig)
    >>> ax_orig.set_title('Original pulse')
    >>> ax_orig.margins(0, 0.1)
    >>> ax_win.plot(win)
    >>> ax_win.set_title('Filter impulse response')
    >>> ax_win.margins(0, 0.1)
    >>> ax_filt.plot(filtered)
    >>> ax_filt.set_title('Filtered signal')
    >>> ax_filt.margins(0, 0.1)
    >>> fig.tight_layout()
    >>> fig.show()

    i    Rx   Rh   Ry   R   R   (   R   Rz   Rw   R   RW   R=   R   R   R}   t   aroundt   astypeR|   R>   R<   R{   (   R   R   Rh   R   R   R   R   (    (    s7   /tmp/pip-build-7oUkmx/scipy/scipy/signal/signaltools.pyR>     s     W"c         C` sh   t  |  } | j } x= t t |   D]) } | | d d k r( t d   q( q( Wt j |  | |  S(   s  
    Perform an order filter on an N-dimensional array.

    Perform an order filter on the array in.  The domain argument acts as a
    mask centered over each pixel.  The non-zero elements of domain are
    used to select elements surrounding each input pixel which are placed
    in a list.   The list is sorted, and the output for that pixel is the
    element corresponding to rank in the sorted list.

    Parameters
    ----------
    a : ndarray
        The N-dimensional input array.
    domain : array_like
        A mask array with the same number of dimensions as `a`.
        Each dimension should have an odd number of elements.
    rank : int
        A non-negative integer which selects the element from the
        sorted list (0 corresponds to the smallest element, 1 is the
        next smallest element, etc.).

    Returns
    -------
    out : ndarray
        The results of the order filter in an array with the same
        shape as `a`.

    Examples
    --------
    >>> from scipy import signal
    >>> x = np.arange(25).reshape(5, 5)
    >>> domain = np.identity(3)
    >>> x
    array([[ 0,  1,  2,  3,  4],
           [ 5,  6,  7,  8,  9],
           [10, 11, 12, 13, 14],
           [15, 16, 17, 18, 19],
           [20, 21, 22, 23, 24]])
    >>> signal.order_filter(x, domain, 0)
    array([[  0.,   0.,   0.,   0.,   0.],
           [  0.,   0.,   1.,   2.,   0.],
           [  0.,   5.,   6.,   7.,   0.],
           [  0.,  10.,  11.,  12.,   0.],
           [  0.,   0.,   0.,   0.,   0.]])
    >>> signal.order_filter(x, domain, 2)
    array([[  6.,   7.,   8.,   9.,   4.],
           [ 11.,  12.,  13.,  14.,   9.],
           [ 16.,  17.,  18.,  19.,  14.],
           [ 21.,  22.,  23.,  24.,  19.],
           [ 20.,  21.,  22.,  23.,  24.]])

    i   i   sI   Each dimension of domain argument  should have an odd number of elements.(   R   R   R   R   Rg   R   t   _order_filterND(   t   at   domaint   rankR~   R   (    (    s7   /tmp/pip-build-7oUkmx/scipy/scipy/signal/signaltools.pyRA     s    5	c         C` s   t  |   }  | d k r+ d g |  j } n  t |  } | j d k rd t j | j   |  j  } n  x: t |  j  D]) } | | d d k rt t	 d   qt qt Wt
 |  } t | d d } | d } t j |  | |  S(	   s  
    Perform a median filter on an N-dimensional array.

    Apply a median filter to the input array using a local window-size
    given by `kernel_size`.

    Parameters
    ----------
    volume : array_like
        An N-dimensional input array.
    kernel_size : array_like, optional
        A scalar or an N-length list 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 size is 3 for each dimension.

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

    i   i   i   s*   Each element of kernel_size should be odd.t   axisi    N(    (   R   R   Rz   R   R   R}   R   t   itemR   Rg   R   R$   R   R   (   R   t   kernel_sizeR   R   t   numelst   order(    (    s7   /tmp/pip-build-7oUkmx/scipy/scipy/signal/signaltools.pyRB   \  s    
c         C` s)  t  |   }  | d k r+ d g |  j } n  t  |  } | j d k rd t j | j   |  j  } n  t |  t |  d  t	 | d d } t |  d t |  d  t	 | d d | d } | d k r t
 t |  d d } n  |  | } | d | | 9} | | 7} t | | k  | |  } | S(	   s  
    Perform a Wiener filter on an N-dimensional array.

    Apply a Wiener filter to the N-dimensional array `im`.

    Parameters
    ----------
    im : ndarray
        An N-dimensional array.
    mysize : int or array_like, optional
        A scalar or an N-length list giving the size of the Wiener filter
        window in each dimension.  Elements of mysize should be odd.
        If mysize is a scalar, then this scalar is used as the size
        in each dimension.
    noise : float, optional
        The noise-power to use. If None, then noise is estimated as the
        average of the local variance of the input.

    Returns
    -------
    out : ndarray
        Wiener filtered result with the same shape as `im`.

    i   R\   R   i    i   i   N(    (   R   R   Rz   R   R}   R   R   R<   R   R$   R   R&   R.   (   t   imt   mysizet   noiset   lMeant   lVart   resR   (    (    s7   /tmp/pip-build-7oUkmx/scipy/scipy/signal/signaltools.pyRD     s     (

c         C` s   t  |   }  t  |  } |  j | j k o5 d k n sI t d   n  t | |  j | j  rq | |  }  } n  t |  } t |  } t j   6 t j	 d t
 j  t j |  | d | | |  } Wd QX| S(   sN
  
    Convolve two 2-dimensional arrays.

    Convolve `in1` and `in2` with output size determined by `mode`, and
    boundary conditions determined by `boundary` and `fillvalue`.

    Parameters
    ----------
    in1 : array_like
        First input.
    in2 : array_like
        Second input. Should have the same number of dimensions as `in1`.
        If operating in 'valid' mode, either `in1` or `in2` must be
        at least as large as the other in every dimension.
    mode : str {'full', 'valid', 'same'}, optional
        A string indicating the size of the output:

        ``full``
           The output is the full discrete linear convolution
           of the inputs. (Default)
        ``valid``
           The output consists only of those elements that do not
           rely on the zero-padding.
        ``same``
           The output is the same size as `in1`, centered
           with respect to the 'full' output.

    boundary : str {'fill', 'wrap', 'symm'}, optional
        A flag indicating how to handle boundaries:

        ``fill``
           pad input arrays with fillvalue. (default)
        ``wrap``
           circular boundary conditions.
        ``symm``
           symmetrical boundary conditions.

    fillvalue : scalar, optional
        Value to fill pad input arrays with. Default is 0.

    Returns
    -------
    out : ndarray
        A 2-dimensional array containing a subset of the discrete linear
        convolution of `in1` with `in2`.

    Examples
    --------
    Compute the gradient of an image by 2D convolution with a complex Scharr
    operator.  (Horizontal operator is real, vertical is imaginary.)  Use
    symmetric boundary condition to avoid creating edges at the image
    boundaries.

    >>> from scipy import signal
    >>> from scipy import misc
    >>> ascent = misc.ascent()
    >>> scharr = np.array([[ -3-3j, 0-10j,  +3 -3j],
    ...                    [-10+0j, 0+ 0j, +10 +0j],
    ...                    [ -3+3j, 0+10j,  +3 +3j]]) # Gx + j*Gy
    >>> grad = signal.convolve2d(ascent, scharr, boundary='symm', mode='same')

    >>> import matplotlib.pyplot as plt
    >>> fig, (ax_orig, ax_mag, ax_ang) = plt.subplots(3, 1, figsize=(6, 15))
    >>> ax_orig.imshow(ascent, cmap='gray')
    >>> ax_orig.set_title('Original')
    >>> ax_orig.set_axis_off()
    >>> ax_mag.imshow(np.absolute(grad), cmap='gray')
    >>> ax_mag.set_title('Gradient magnitude')
    >>> ax_mag.set_axis_off()
    >>> ax_ang.imshow(np.angle(grad), cmap='hsv') # hsv is cyclic, like angles
    >>> ax_ang.set_title('Gradient orientation')
    >>> ax_ang.set_axis_off()
    >>> fig.show()

    i   s(   convolve2d inputs must both be 2D arrayst   ignorei   N(   R   Rz   Rg   Rw   R   Rj   Rm   t   warningst   catch_warningst   simplefilterR}   t   ComplexWarningR   t   _convolve2d(   R   R   Rh   Rl   t	   fillvalueRi   t   bvalR   (    (    s7   /tmp/pip-build-7oUkmx/scipy/scipy/signal/signaltools.pyR?     s    L"$c   	      C` s  t  |   }  t  |  } |  j | j k o5 d k n sI t d   n  t | |  j | j  } | rw | |  }  } n  t |  } t |  } t j   6 t j	 d t
 j  t j |  | d | | |  } Wd QX| r | d d d  d d d  f } n  | S(   s
  
    Cross-correlate two 2-dimensional arrays.

    Cross correlate `in1` and `in2` with output size determined by `mode`, and
    boundary conditions determined by `boundary` and `fillvalue`.

    Parameters
    ----------
    in1 : array_like
        First input.
    in2 : array_like
        Second input. Should have the same number of dimensions as `in1`.
        If operating in 'valid' mode, either `in1` or `in2` must be
        at least as large as the other in every dimension.
    mode : str {'full', 'valid', 'same'}, optional
        A string indicating the size of the output:

        ``full``
           The output is the full discrete linear cross-correlation
           of the inputs. (Default)
        ``valid``
           The output consists only of those elements that do not
           rely on the zero-padding.
        ``same``
           The output is the same size as `in1`, centered
           with respect to the 'full' output.

    boundary : str {'fill', 'wrap', 'symm'}, optional
        A flag indicating how to handle boundaries:

        ``fill``
           pad input arrays with fillvalue. (default)
        ``wrap``
           circular boundary conditions.
        ``symm``
           symmetrical boundary conditions.

    fillvalue : scalar, optional
        Value to fill pad input arrays with. Default is 0.

    Returns
    -------
    correlate2d : ndarray
        A 2-dimensional array containing a subset of the discrete linear
        cross-correlation of `in1` with `in2`.

    Examples
    --------
    Use 2D cross-correlation to find the location of a template in a noisy
    image:

    >>> from scipy import signal
    >>> from scipy import misc
    >>> face = misc.face(gray=True) - misc.face(gray=True).mean()
    >>> template = np.copy(face[300:365, 670:750])  # right eye
    >>> template -= template.mean()
    >>> face = face + np.random.randn(*face.shape) * 50  # add noise
    >>> corr = signal.correlate2d(face, template, boundary='symm', mode='same')
    >>> y, x = np.unravel_index(np.argmax(corr), corr.shape)  # find the match

    >>> import matplotlib.pyplot as plt
    >>> fig, (ax_orig, ax_template, ax_corr) = plt.subplots(3, 1,
    ...                                                     figsize=(6, 15))
    >>> ax_orig.imshow(face, cmap='gray')
    >>> ax_orig.set_title('Original')
    >>> ax_orig.set_axis_off()
    >>> ax_template.imshow(template, cmap='gray')
    >>> ax_template.set_title('Template')
    >>> ax_template.set_axis_off()
    >>> ax_corr.imshow(corr, cmap='gray')
    >>> ax_corr.set_title('Cross-correlation')
    >>> ax_corr.set_axis_off()
    >>> ax_orig.plot(x, y, 'ro')
    >>> fig.show()

    i   s)   correlate2d inputs must both be 2D arraysR  i    Ni(   R   Rz   Rg   Rw   R   Rj   Rm   R  R  R  R}   R  R   R  (	   R   R   Rh   Rl   R  R   Ri   R	  R   (    (    s7   /tmp/pip-build-7oUkmx/scipy/scipy/signal/signaltools.pyR@     s    M"$%c         C` s   t  |   } | d k r( d g d } n  t  |  } | j d k r^ t j | j   d  } n  x- | D]% } | d d k re t d   qe qe Wt j | |  S(   s  
    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.

    i   i   i   s*   Each element of kernel_size should be odd.N(    (	   R   R   R   R}   R   R   Rg   R   t
   _medfilt2d(   t   inputR   t   imageR~   (    (    s7   /tmp/pip-build-7oUkmx/scipy/scipy/signal/signaltools.pyRC   ~  s    ic      	   ` s  t  j |  } t |  d k rt  j      t  j |  }   j d k rl | j d k rl t d   n  t  j |  }   | | g } | d
 k	 r,t  j |  } | j | j k r t d   n  t | j  }   j d d | | <t	 |  } | j | k r| j d
 g } | d k  r1| | j 7} n  x t
 | j  D] } | | k r~| j | | | k r~| j | | | <qA| | k r| j | | | k r| j | | | <qA| | k r| j | d k rd | | <qAt d | | j f   qAWt  j j j | | |  } n  | j |  n  t  j |   }	 |	 j d k r]t d |	   n  t  j   d |	   t  j | d |	 d t }   | d   t  j | d |	 d t } t  j   f d	   | |  }
 |
 j t d
  g } | d
 k	 r t | j |  | | <|
 | c | 7<n  t |
 j | t    d  | | <|
 | } | d
 k r_| St |
 j | t    d d
  | | <|
 | } | | f Sn; | d
 k rt j   | | |  St j   | | | |  Sd
 S(   s?  
    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, optional
        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.

    See Also
    --------
    lfiltic : Construct initial conditions for `lfilter`.
    lfilter_zi : Compute initial state (steady state of step response) for
                 `lfilter`.
    filtfilt : A forward-backward filter, to obtain a filter with linear phase.
    savgol_filter : A Savitzky-Golay filter.
    sosfilt: Filter data using cascaded second-order sections.
    sosfiltfilt: A forward-backward filter using second-order sections.

    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[M]*x[n-M]
                             - a[1]*y[n-1] - ... - a[N]*y[n-N]

    where `M` is the degree of the numerator, `N` is the degree of the
    denominator, and `n` is the sample number.  It is implemented using
    the following difference equations (assuming M = N)::

         a[0]*y[n] = b[0] * x[n]               + d[0][n-1]
           d[0][n] = b[1] * x[n] - a[1] * y[n] + d[1][n-1]
           d[1][n] = b[2] * x[n] - a[2] * y[n] + d[2][n-1]
         ...
         d[N-2][n] = b[N-1]*x[n] - a[N-1]*y[n] + d[N-1][n-1]
         d[N-1][n] = b[N] * x[n] - a[N] * y[n]

    where `d` are the state variables.

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

                             -1              -M
                 b[0] + b[1]z  + ... + b[M] z
         Y(z) = -------------------------------- X(z)
                             -1              -N
                 a[0] + a[1]z  + ... + a[N] z

    Examples
    --------
    Generate a noisy signal to be filtered:

    >>> from scipy import signal
    >>> import matplotlib.pyplot as plt
    >>> t = np.linspace(-1, 1, 201)
    >>> x = (np.sin(2*np.pi*0.75*t*(1-t) + 2.1) +
    ...      0.1*np.sin(2*np.pi*1.25*t + 1) +
    ...      0.18*np.cos(2*np.pi*3.85*t))
    >>> xn = x + np.random.randn(len(t)) * 0.08

    Create an order 3 lowpass butterworth filter:

    >>> b, a = signal.butter(3, 0.05)

    Apply the filter to xn.  Use lfilter_zi to choose the initial condition of
    the filter:

    >>> zi = signal.lfilter_zi(b, a)
    >>> z, _ = signal.lfilter(b, a, xn, zi=zi*xn[0])

    Apply the filter again, to have a result filtered at an order the same as
    filtfilt:

    >>> z2, _ = signal.lfilter(b, a, z, zi=zi*z[0])

    Use filtfilt to apply the filter:

    >>> y = signal.filtfilt(b, a, xn)

    Plot the original signal and the various filtered versions:

    >>> plt.figure
    >>> plt.plot(t, xn, 'b', alpha=0.75)
    >>> plt.plot(t, z, 'r--', t, z2, 'r', t, y, 'k')
    >>> plt.legend(('noisy signal', 'lfilter, once', 'lfilter, twice',
    ...             'filtfilt'), loc='best')
    >>> plt.grid(True)
    >>> plt.show()

    i   s+   object of too small depth for desired arrayi    s/   Unexpected shape for zi: expected %s, found %s.t   fdgFDGOs   input type '%s' not supportedR   R   c         ` s   t  j   |   S(   N(   R}   R>   (   t   y(   t   b(    s7   /tmp/pip-build-7oUkmx/scipy/scipy/signal/signaltools.pyR   L  s    N(   R}   R   R   R   Rz   Rg   R   t   listR   R   R   t   stridest   libt   stride_trickst
   as_stridedt   appendt   result_typet   chart   NotImplementedErrorR   Rp   t   apply_along_axisR   R   t   _linear_filter(   R  R   R   R   t   zit   inputst   expected_shapeR  R   R   t   out_fullt   indR   t   zf(    (   R  s7   /tmp/pip-build-7oUkmx/scipy/scipy/signal/signaltools.pyRE     sj    v##%
(
c   
   	   C` s  t  j |  d } t  j |   d } t | |  } t |  } | j j d k rh | j t  j  } n  t | | j  } | d k r t | | j  } nD t |  } t  j |  } | | k  r t
 | t | |  f } n  t  j |  } | | k  rt
 | t | |  f } n  xA t |  D]3 }	 t  j |  |	 d | | |	  d d | |	 <q$WxG t |  D]9 }	 | |	 c t  j | |	 d | | |	  d d 8<qhW| S(   s  
    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 = {z_0[-1], z_1[-1], ..., z_K-1[-1]}``,
        where ``K = max(M, N)``.

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

    i   t   buiR   i    N(   R}   R~   R   R   R   R   R   t   float64R/   R   R%   R   R   (
   R  R   R  R   t   Nt   Mt   KR  t   Lt   m(    (    s7   /tmp/pip-build-7oUkmx/scipy/scipy/signal/signaltools.pyRF   b  s*    (17c   	      C` s   t  |   } t  |  } t |  } t |  } | | k rK g  } | } nL t | | d t  } d | d )t | | |  } | t | | d d } | | f S(   ss  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)

    i   i    Rh   R]   (   R   R   R   R   RE   R>   (	   t   signalt   divisort   numt   denR#  t   Dt   quott   remR  (    (    s7   /tmp/pip-build-7oUkmx/scipy/scipy/signal/signaltools.pyRH     s    )	
c         C` s4  t  |   }  t |   r' t d   n  | d k rC |  j | } n  | d k r^ t d   n  t j |  | d | } t |  } | d d k r d | d <| | d <d | d | d +n d | d <d | d | d d +|  j d k rt	 g |  j } t
 d  | | <| | } n  t j | | d | }  |  S(   s  
    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`

    See Also
    --------
    scipy.fftpack.hilbert : Return Hilbert transform of a periodic sequence x.

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

    Examples
    ---------
    In this example we use the Hilbert transform to determine the amplitude
    envelope and instantaneous frequency of an amplitude-modulated signal.

    >>> import numpy as np
    >>> import matplotlib.pyplot as plt
    >>> from scipy.signal import hilbert, chirp

    >>> duration = 1.0
    >>> fs = 400.0
    >>> samples = int(fs*duration)
    >>> t = np.arange(samples) / fs

    We create a chirp of which the frequency increases from 20 Hz to 100 Hz and
    apply an amplitude modulation.

    >>> signal = chirp(t, 20.0, t[-1], 100.0)
    >>> signal *= (1.0 + 0.5 * np.sin(2.0*np.pi*3.0*t) )

    The amplitude envelope is given by magnitude of the analytic signal. The
    instantaneous frequency can be obtained by differentiating the
    instantaneous phase in respect to time. The instantaneous phase corresponds
    to the phase angle of the analytic signal.

    >>> analytic_signal = hilbert(signal)
    >>> amplitude_envelope = np.abs(analytic_signal)
    >>> instantaneous_phase = np.unwrap(np.angle(analytic_signal))
    >>> instantaneous_frequency = (np.diff(instantaneous_phase) /
    ...                            (2.0*np.pi) * fs)

    >>> fig = plt.figure()
    >>> ax0 = fig.add_subplot(211)
    >>> ax0.plot(t, signal, label='signal')
    >>> ax0.plot(t, amplitude_envelope, label='envelope')
    >>> ax0.set_xlabel("time in seconds")
    >>> ax0.legend()
    >>> ax1 = fig.add_subplot(212)
    >>> ax1.plot(t[1:], instantaneous_frequency)
    >>> ax1.set_xlabel("time in seconds")
    >>> ax1.set_ylim(0.0, 120.0)

    References
    ----------
    .. [1] Wikipedia, "Analytic signal".
           http://en.wikipedia.org/wiki/Analytic_signal
    .. [2] Leon Cohen, "Time-Frequency Analysis", 1995. Chapter 2.
    .. [3] Alan V. Oppenheim, Ronald W. Schafer. Discrete-Time Signal
           Processing, Third Edition, 2009. Chapter 12.
           ISBN 13: 978-1292-02572-8

    s   x must be real.i    s   N must be positive.R   i   i   N(   R   R   Rg   R   R   R	   Ry   R/   Rz   R   R   t   ifft(   R   R#  R   t   XfR   R  (    (    s7   /tmp/pip-build-7oUkmx/scipy/scipy/signal/signaltools.pyRI     s(    Z
c   	      B` sC  e  |   }  |  j d k r* e d   n  e |   rE e d   n  | d k r] |  j } nx e | e  r | d k r e d   n  | | f } n? e |  d k s e	 j
 e	 j |  d k  r e d   n  e j |  | d d } e | d d	  } e | d d	  } x e d  D] } e d
 | d  } | | } | d d k r~d | d <| | d <d | d | d +n d | d <d | d | d d +d | d e   e   f d Uq W| d d  e f | e d d  f } |  j } x0 | d k r%| d d  e f } | d 8} qWe j | | d d }  |  S(   s  
    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

    i   s   x must be 2-D.s   x must be real.i    s   N must be positive.s@   When given as a tuple, N must hold exactly two positive integerst   axesi   R   s   h%ds   h%d = hN(   i    i   (   i    i   (   R   Rz   Rg   R   R   R   t
   isinstanceR   R   R}   R   R   R	   t   fft2R/   R   t   evalt   globalst   localsR   t   ifft2(	   R   R#  R0  t   h1t   h2R   R   t   N1R   (    (    s7   /tmp/pip-build-7oUkmx/scipy/scipy/signal/signaltools.pyRJ   Q  s@    0

#*	c         C` sO   t  |   }  t |   r- t t |    } n t |   } t |  | d  | f S(   s  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`.

    i    (   R   R   R   R   R+   (   R   t   indx(    (    s7   /tmp/pip-build-7oUkmx/scipy/scipy/signal/signaltools.pyRK     s
    gMbP?R   c         C` sh  | d k r t  j } n< | d k r0 t  j } n$ | d k rH t  j } n t d   t |   d }  t |  } t |   \ }  } g  } g  } d	 } |  d
 d | } g  } x t t	 |    D] }	 |  |	 }
 t |
 |  | k  r| j
 |
  | |  } | | | <| | c d 7<q | j
 |
  |
 } |
 g } | d 7} | j
 d  q Wt |  t |  f S(   s  
    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])

    R   t   maximumR   t   minimumt   avgR   sJ   `rtype` must be one of {'max', 'maximum', 'min', 'minimum', 'avg', 'mean'}g      ?ii    i   i   (   s   maxs   maximum(   s   mins   minimum(   s   avgs   mean(   R}   R   R   R   Rg   R   R   RK   R   R   R  R   (   R   t   tolt   rtypet   comprootR;  t   poutt   multt   curpt	   samerootsR   t   tr(    (    s7   /tmp/pip-build-7oUkmx/scipy/scipy/signal/signaltools.pyRL     s8    +

	
R>  c         C` s  | } t  |  \ } } t |  | d  }  t | d | d | \ } } g  } x6 t t |   D]" } | j | | g | |  qa Wt t |   }	 t |  d k r t | |	  }
 n	 d g }
 d } x t t |   D] } g  } xE t t |   D]1 } | | k r | j | | g | |  q q Wxp t | |  D]^ } | } | j | | g | | | d  t	 |
 |  | t t |    }
 | d 7} qDWq Wt
 |
  }
 x: t |
 d d d d r|
 j d d k r|
 d }
 qW|
 |	 f S(   s$  
    Compute b(s) and a(s) from partial fraction expansion.

    If `M` is the degree of numerator `b` and `N` the degree of denominator
    `a`::

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

    then the partial-fraction expansion H(s) is defined as::

               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

    This function is used for polynomials in positive powers of s or z,
    such as analog filters or digital filters in controls engineering.  For
    negative powers of z (typical for digital filters in DSP), use `invresz`.

    Parameters
    ----------
    r : array_like
        Residues.
    p : array_like
        Poles.
    k : array_like
        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.

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

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

    i    R?  R@  i   t   rtolg+=i(   RK   R+   RL   R   R   t   extendR   R   R!   R   R'   R   R   (   R   R   R   R?  R@  t   extraR;  RB  RC  R   R  t   tempt   lR'  t   t2(    (    s7   /tmp/pip-build-7oUkmx/scipy/scipy/signal/signaltools.pyRM     s4    : 	#$#/c         C` s%  t  t |  | f  \ }  } | d } t |  |  \ } }  t |  } | d } t | d | d | \ } }	 g  } x6 t t |   D]" }
 | j | |
 g |	 |
  q Wt |  } d } xRt t |   D]>}
 |  j   } g  } xE t t |   D]1 } | |
 k r | j | | g |	 |  q q Wt	 t
 |   } |	 |
 } x t | d d  D] } | | k rt t | d  |  } t | t | d   } t | |  } t | |  } n  t | | |
  t | | |
  t | |  | | | d <qaW| | 7} q W| | | | f S(   s  
    Compute partial-fraction expansion of b(s) / a(s).

    If `M` is the degree of numerator `b` and `N` the degree of denominator
    `a`::

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

    then the partial-fraction expansion H(s) is defined as::

               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

    This function is used for polynomials in positive powers of s or z,
    such as analog filters or digital filters in controls engineering.  For
    negative powers of z (typical for digital filters in DSP), use `residuez`.

    Parameters
    ----------
    b : array_like
        Numerator polynomial coefficients.
    a : array_like
        Denominator polynomial coefficients.

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

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

    i    g        R?  R@  ii   (   t   mapR   R    R)   RL   R   R   RH  R   R   R   R!   R   R"   R#   R1   (   R  R   R?  R@  t   rscaleR   R   R   RB  RC  R   R;  t   bnt   pnRK  t   ant   sigR'  t   term1t   term2(    (    s7   /tmp/pip-build-7oUkmx/scipy/scipy/signal/signaltools.pyRO   H  s:    2

 #
!!c         C` s  t  t |  | f  \ }  } | d } |  d d d  | d d d  } } t | |  \ } } | g  k rv g  } n | d d d  } | d d d  }  t |  }	 |	 d }
 t |	 d | d | \ } } g  }	 x6 t t |   D]" } |	 j | | g | |  q Wt |	  }	 d } xxt t |   D]d} | j   } g  } xE t t |   D]1 } | | k r_| j | | g | |  q_q_Wt	 t
 |   d d d  } | | } x t | d d  D] } | | k r3t t | d  |  } t | t | d   } t | |  } t | |  } n  t | d | |  t | d | |  t | |  | | | | |
 | | d <qW| | 7} q4W|
 | |	 | f S(	   s  
    Compute partial-fraction expansion of b(z) / a(z).

    If `M` is the degree of numerator `b` and `N` the degree of denominator
    `a`::

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

    then the partial-fraction expansion H(z) is defined as::

                 r[0]                   r[-1]
         = --------------- + ... + ---------------- + k[0] + k[1]z**(-1) ...
           (1-p[0]z**(-1))         (1-p[-1]z**(-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]
        -------------- + ------------------ + ... + ------------------
        (1-p[i]z**(-1))  (1-p[i]z**(-1))**2         (1-p[i]z**(-1))**n

    This function is used for polynomials in negative powers of z,
    such as digital filters in DSP.  For positive powers, use `residue`.

    Parameters
    ----------
    b : array_like
        Numerator polynomial coefficients.
    a : array_like
        Denominator polynomial coefficients.

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

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

    i    Nig        R?  R@  i   g      ?(   RM  R   R    R)   RL   R   R   RH  R   R   R   R!   R   R"   R#   R1   (   R  R   R?  R@  t   gaint   brevt   arevt   krevR   R   R   RB  RC  R   R;  RO  RP  RK  RQ  RR  R'  RS  RT  (    (    s7   /tmp/pip-build-7oUkmx/scipy/scipy/signal/signaltools.pyRP     sB    0
'	
 #
[c         C` s  t  |  } t |  \ } } t |  | d  }  t | d | d | \ } } g  } x6 t t |   D]" } | j | | g | |  qg Wt t |   }	 t |  d k r t	 | |	  }
 n	 d g }
 d } t  |
  d d d  } x t t |   D] } g  } xE t t |   D]1 } | | k r| j | | g | |  qqWx} t | |  D]k } | } | j | | g | | | d  t
 | |  | t t |   d d d   } | d 7} qcWq Wt | d d d   }
 |
 |	 f S(   s.  
    Compute b(z) and a(z) from partial fraction expansion.

    If `M` is the degree of numerator `b` and `N` the degree of denominator
    `a`::

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

    then the partial-fraction expansion H(z) is defined as::

                 r[0]                   r[-1]
         = --------------- + ... + ---------------- + k[0] + k[1]z**(-1) ...
           (1-p[0]z**(-1))         (1-p[-1]z**(-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]
        -------------- + ------------------ + ... + ------------------
        (1-p[i]z**(-1))  (1-p[i]z**(-1))**2         (1-p[i]z**(-1))**n

    This function is used for polynomials in negative powers of z,
    such as digital filters in DSP.  For positive powers, use `invres`.

    Parameters
    ----------
    r : array_like
        Residues.
    p : array_like
        Poles.
    k : array_like
        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.

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

    See Also
    --------
    residuez, unique_roots, invres

    i    R?  R@  Nii   (   R   RK   R+   RL   R   R   RH  R   R   R!   R   R'   (   R   R   R   R?  R@  RI  R;  RB  RC  R   R  RV  RJ  RK  R'  RL  (    (    s7   /tmp/pip-build-7oUkmx/scipy/scipy/signal/signaltools.pyRN     s2    9 	#$0c         C` s4  t  |   }  t j |  d | } |  j | } | d k	 r t |  r^ | t j |   } nQ t | t  r | j | f k r t	 d   n  | } n t j
 t | |   } d g |  j } t |  | | <| | _ | | } | f | _ n  t d  g |  j }	 t |  j  } | | | <t t j | |   }
 t | d  } t d |
 d d  |	 | <| |	 | |	 <t |
 d d d  |	 | <| |	 | |	 <t j | d | t |  t |  } |  j j d	 k r| j } n  | d k r| St d |  | d | d | t |  | d } | | f Sd S(
   s  
    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.

    See Also
    --------
    decimate : Downsample the signal after applying an FIR or IIR filter.
    resample_poly : Resample using polyphase filtering and an FIR filter.

    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.

    As noted, `resample` uses FFT transformations, which can be very
    slow if the number of input or output samples is large and prime;
    see `scipy.fftpack.fft`.

    Examples
    --------
    Note that the end of the resampled data rises to meet the first
    sample of the next cycle:

    >>> from scipy import signal

    >>> x = np.linspace(0, 10, 20, endpoint=False)
    >>> y = np.cos(-x**2/6.0)
    >>> f = signal.resample(y, 100)
    >>> xnew = np.linspace(0, 10, 100, endpoint=False)

    >>> import matplotlib.pyplot as plt
    >>> plt.plot(x, y, 'go-', xnew, f, '.-', 10, y[0], 'ro')
    >>> plt.legend(['data', 'resampled'], loc='best')
    >>> plt.show()
    R   s(   window must have the same length as datai   R,  i    i   t   FN(   RY  R,  (   R   R	   Ry   R   R   R   t   fftfreqR2  R   Rg   t	   ifftshiftR2   Rz   R   R   R  R   R}   R=  R/   R/  R   R   R  R   R   (   R   R*  t   tR   t   windowt   Xt   Nxt   WR   t   slR#  t   YR  t   new_t(    (    s7   /tmp/pip-build-7oUkmx/scipy/scipy/signal/signaltools.pyRQ   P  s@    Q		

)5t   kaiserg      @c      	   C` sJ  t  |   }  t |  } t |  } | d k  s< | d k  rK t d   n  t | |  } | | } | | } | | k o d k n r |  j   S|  j | | } | | t | |  } t | t t	 j
 f  rt  |  } | j d k r t d   n  | j d d } | } n@ t | |  }	 d |	 }
 d |	 } t d | d |
 d | } | | 9} | | | } d } | | | } xB t t |  | | |  j | | |  | | k  r| d 7} qWt	 j t	 j |  | t	 j |  f  } | | } t | |  | | d	 | } t d
  g |  j } t | |  | | <| | S(   s  
    Resample `x` along the given axis using polyphase filtering.

    The signal `x` is upsampled by the factor `up`, a zero-phase low-pass
    FIR filter is applied, and then it is downsampled by the factor `down`.
    The resulting sample rate is ``up / down`` times the original sample
    rate. Values beyond the boundary of the signal are assumed to be zero
    during the filtering step.

    Parameters
    ----------
    x : array_like
        The data to be resampled.
    up : int
        The upsampling factor.
    down : int
        The downsampling factor.
    axis : int, optional
        The axis of `x` that is resampled. Default is 0.
    window : string, tuple, or array_like, optional
        Desired window to use to design the low-pass filter, or the FIR filter
        coefficients to employ. See below for details.

    Returns
    -------
    resampled_x : array
        The resampled array.

    See Also
    --------
    decimate : Downsample the signal after applying an FIR or IIR filter.
    resample : Resample up or down using the FFT method.

    Notes
    -----
    This polyphase method will likely be faster than the Fourier method
    in `scipy.signal.resample` when the number of samples is large and
    prime, or when the number of samples is large and `up` and `down`
    share a large greatest common denominator. The length of the FIR
    filter used will depend on ``max(up, down) // gcd(up, down)``, and
    the number of operations during polyphase filtering will depend on
    the filter length and `down` (see `scipy.signal.upfirdn` for details).

    The argument `window` specifies the FIR low-pass filter design.

    If `window` is an array_like it is assumed to be the FIR filter
    coefficients. Note that the FIR filter is applied after the upsampling
    step, so it should be designed to operate on a signal at a sampling
    frequency higher than the original by a factor of `up//gcd(up, down)`.
    This function's output will be centered with respect to this array, so it
    is best to pass a symmetric filter with an odd number of samples if, as
    is usually the case, a zero-phase filter is desired.

    For any other type of `window`, the functions `scipy.signal.get_window`
    and `scipy.signal.firwin` are called to generate the appropriate filter
    coefficients.

    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 * up / float(down)``.

    Examples
    --------
    Note that the end of the resampled data rises to meet the first
    sample of the next cycle for the FFT method, and gets closer to zero
    for the polyphase method:

    >>> from scipy import signal

    >>> x = np.linspace(0, 10, 20, endpoint=False)
    >>> y = np.cos(-x**2/6.0)
    >>> f_fft = signal.resample(y, 100)
    >>> f_poly = signal.resample_poly(y, 100, 20)
    >>> xnew = np.linspace(0, 10, 100, endpoint=False)

    >>> import matplotlib.pyplot as plt
    >>> plt.plot(xnew, f_fft, 'b.-', xnew, f_poly, 'r.-')
    >>> plt.plot(x, y, 'ko-')
    >>> plt.plot(10, y[0], 'bo', 10, 0., 'ro')  # boundaries
    >>> plt.legend(['resample', 'resamp_poly', 'data'], loc='best')
    >>> plt.show()
    i   s   up and down must be >= 1s   window must be 1-Di   g      ?i
   R]  i    R   N(   R   R   Rg   R;   R   R   t   boolR2  R  R}   R   Rz   R~   R   R:   R   R   t   concatenateR/   R   R   R   (   R   t   upt   downR   R]  t   g_t   n_outt   half_lenR   t   max_ratet   f_ct	   n_pre_padt
   n_post_padt   n_pre_removet   n_pre_remove_endR  t   keep(    (    s7   /tmp/pip-build-7oUkmx/scipy/scipy/signal/signaltools.pyRR     sF    S


	


!*
c         C` s  t  |   }  t  |  } |  j d k r6 t d   n  | j d k rT t d   n  | j } t |   }  t |  } | d k j   r t d   n  t t d t | j |    } t	 | d d } t
 |  } t |  } | r | d } | d } n  | | f S(   s  
    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`.
    i   s)   events cannot have dimensions more than 1s)   period cannot have dimensions more than 1i    s   periods must be positivey               @R   (   R   Rz   Rg   R   R   R   R   R   t   TR   R   R   (   t   eventst   periodt   scalarperiodt   vectorst
   vectormeant   strengtht   phase(    (    s7   /tmp/pip-build-7oUkmx/scipy/scipy/signal/signaltools.pyRZ   K	  s&    /
 
t   linearc         C` s  | d k r t  d   n  t |   }  |  j j } | d k rH d } n  | d k rt |  t t |  |  |  } | S|  j } | | } t t t	 d | | f   } t
 j | | k  r t  d	   n  t |  d
 } t |  }	 | d k  r | |	 } n  t	 | d |  | d
 |	  f }
 t t |  t |
   | t |  | f  } | j   } | j j d k r| j |  } n  x t |  D] } | | d
 | | } t | d f |  } t | t d
 | d
  d |  | d d  d f <t | | | | d
  } t j | | |  \ } } } } | | t | |  | | <qWt | |
 d  } t | t |   } t t d
 |	   } | |  d g | | } t | t |   } | Sd S(   sb  
    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 = 1000
    >>> noise = randgen.randn(npoints)
    >>> x = 3 + 2*np.linspace(0, 1, npoints) + noise
    >>> (signal.detrend(x) - noise).max() < 0.01
    True

    R{  RK  t   constantt   cs*   Trend type must be 'linear' or 'constant'.t   dfDFR   i    s>   Breakpoints must be less than length of data along given axis.i   i   g      ?N(   R{  RK  R|  R}  (   R|  R}  (   Rg   R   R   R  R   R   R   R*   R-   R%   R}   R   R   R(   R,   R   R   R   R   R   R   R   R   R   R
   t   lstsqR   R+   R  (   t   dataR   R   t   bpR   R   t   dshapeR#  t   Nregt   rnkt   newdimst   newdataR'  t   Nptst   ARa  t   coeft   residsR   t   st   tdshapet   valst   olddims(    (    s7   /tmp/pip-build-7oUkmx/scipy/scipy/signal/signaltools.pyRS   	  sJ    %		
#5"c         C` s  t  j |   }  |  j d k r- t d   n  t  j |  } | j d k rZ t d   n  x0 t |  d k r | d d k r | d } q] W| j d k  r t d   n  | d d k r |  | d }  | | d } n  t t |  t |    } t |  | k  r0t  j | t  j | t |   f } n; t |   | k  rkt  j |  t  j | t |    f }  n  t  j	 | d  t
 j |  j } |  d | d |  d } t  j
 j | |  } | S(   s
  
    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.

    See Also
    --------
    lfilter, lfiltic, filtfilt

    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.

    i   s   Numerator b must be 1-D.s   Denominator a must be 1-D.i    g        s3   There must be at least one nonzero `a` coefficient.g      ?(   R}   R   Rz   Rg   R   R~   R   R%   R/   t   eyeR
   t	   companionRs  t   solve(   R  R   R   t   IminusAt   BR  (    (    s7   /tmp/pip-build-7oUkmx/scipy/scipy/signal/signaltools.pyRT   	  s,    Y%))#c         C` s   t  j |   }  |  j d k s1 |  j d d k r@ t d   n  |  j d } t  j | d f  } d } xq t |  D]c } |  | d d  f } |  | d d  f } | t | |  | | <| | j   | j   9} qu W| S(	   s  
    Compute an initial state `zi` for the sosfilt 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
    ----------
    sos : array_like
        Array of second-order filter coefficients, must have shape
        ``(n_sections, 6)``. See `sosfilt` for the SOS filter format
        specification.

    Returns
    -------
    zi : ndarray
        Initial conditions suitable for use with ``sosfilt``, shape
        ``(n_sections, 2)``.

    See Also
    --------
    sosfilt, zpk2sos

    Notes
    -----
    .. versionadded:: 0.16.0

    Examples
    --------
    Filter a rectangular pulse that begins at time 0, with and without
    the use of the `zi` argument of `scipy.signal.sosfilt`.

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

    >>> sos = signal.butter(9, 0.125, output='sos')
    >>> zi = signal.sosfilt_zi(sos)
    >>> x = (np.arange(250) < 100).astype(int)
    >>> f1 = signal.sosfilt(sos, x)
    >>> f2, zo = signal.sosfilt(sos, x, zi=zi)

    >>> plt.plot(x, 'k--', label='x')
    >>> plt.plot(f1, 'b', alpha=0.5, linewidth=2, label='filtered')
    >>> plt.plot(f2, 'g', alpha=0.25, linewidth=4, label='filtered with zi')
    >>> plt.legend(loc='best')
    >>> plt.show()

    i   i   i   s!   sos must be shape (n_sections, 6)i    g      ?Ni   (	   R}   R   Rz   R   Rg   R   R   RT   R   (   t   sost
   n_sectionsR  t   scalet   sectionR  R   (    (    s7   /tmp/pip-build-7oUkmx/scipy/scipy/signal/signaltools.pyRU   q
  s    3"c   !   
   C` s  t  j |   }  t  j |  } t t |   t |   d } | d k r |  d | d d } | | } | t  j g   t  j g   f S| d k s | | j d k r t  j | | | j d  } n  | j d } | d k s | d | k r | }	 n | }	 t  j	 |	 | f  }
 t  j	 |  } d | d <t
 |  | t  j	 |	  d | d |
 d d  d f <x> t d |  D]- } |
 d |  d f |
 | d  | f <qqW|
 d d d  } t
 |  | |
 d d d  d d } | d d d  } |	 | k rt  j | |
 | | f  } n] t  j	 d |	 d | f  } | |
 | d |	  d |  f <| | | |	 d  | d  f <t
 |  | |  } t
 |  | | d d d d  f  d d d d  f } t
 |  | | d d d d  f  d d d d  f } t
 |  | |  } | | } |	 | k r)| } nH | d d |	  f } | d |	 d  f } t  j | | f d d } | j d k rt j | |  d } nY | j d | j d  j } t j | |  d j } | j | j d  | j d f  } |	 | k rt  j | | f  } nU t  j	 d |	 d | f  } | | d |	  d |  f <| | |	 d  | d  f <| j | j  } | } |	 | k r| | 7} nZ | d d |	  f c | d d |	  f 7<| d |	 d  f c | d |	 d  f 7<| d d |  f } | d | d  f }  | d k sB| | j d k rt  j | | | j d  } t  j |  | | j d  }  t  j | | | j d  } n  | | |  f S(	   s7  Forward-backward IIR filter that uses Gustafsson's method.

    Apply the IIR filter defined by `(b,a)` to `x` twice, first forward
    then backward, using Gustafsson's initial conditions [1]_.

    Let ``y_fb`` be the result of filtering first forward and then backward,
    and let ``y_bf`` be the result of filtering first backward then forward.
    Gustafsson's method is to compute initial conditions for the forward
    pass and the backward pass such that ``y_fb == y_bf``.

    Parameters
    ----------
    b : scalar or 1-D ndarray
        Numerator coefficients of the filter.
    a : scalar or 1-D ndarray
        Denominator coefficients of the filter.
    x : ndarray
        Data to be filtered.
    axis : int, optional
        Axis of `x` to be filtered.  Default is -1.
    irlen : int or None, optional
        The length of the nonnegligible part of the impulse response.
        If `irlen` is None, or if the length of the signal is less than
        ``2 * irlen``, then no part of the impulse response is ignored.

    Returns
    -------
    y : ndarray
        The filtered data.
    x0 : ndarray
        Initial condition for the forward filter.
    x1 : ndarray
        Initial condition for the backward filter.

    Notes
    -----
    Typically the return values `x0` and `x1` are not needed by the
    caller.  The intended use of these return values is in unit tests.

    References
    ----------
    .. [1] F. Gustaffson. Determining the initial states in forward-backward
           filtering. Transactions on Signal Processing, 46(4):988-992, 1996.

    i   i    i   iR  NR   .(   R}   R   R   R   R   Rz   t   swapaxesR   R   R/   RE   R   t   hstackRf  R
   R  R(   Rs  R   (!   R  R   R   R   t   irlenR   R  R  R   R'  t   ObsR  R   t   Obsrt   St   SrR$  t   y_ft   y_fbt   y_bt   y_bft   delta_y_bf_fbt   deltat   start_mt   end_mt   ic_optt   delta2dt   ic_opt0R`  t   wict   y_optt   x0t   x1(    (    s7   /tmp/pip-build-7oUkmx/scipy/scipy/signal/signaltools.pyt   _filtfilt_gust
  sx    1
	

5+
%   88
	$,.t   oddc      
   C` s  t  j |   }  t  j |  } t  j |  } | d k rH t d   n  | d k r t |  | | d | d | \ } }	 }
 | St | | | | d t t |  t |    \ } } t |  |  } d g | j	 } | j
 | | <t  j | |  } t | d d d | } t |  | | d | d	 | | \ } } t | d
 d d | } t |  | t | d | d | d	 | | \ } } t | d | } | d k rt | d
 | d | d | } n  | S(   s  
    A forward-backward filter.

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

    The function provides options for handling the edges of the signal.

    When `method` is "pad", the function pads 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 the end points. On
    both the forward and backward passes, the initial condition of the
    filter is found by using `lfilter_zi` and scaling it by the end point of
    the extended data.

    When `method` is "gust", Gustafsson's method [1]_ is used.  Initial
    conditions are chosen for the forward and backward passes so that the
    forward-backward filter gives the same result as the backward-forward
    filter.

    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))``.
    method : str, optional
        Determines the method for handling the edges of the signal, either
        "pad" or "gust".  When `method` is "pad", the signal is padded; the
        type of padding is determined by `padtype` and `padlen`, and `irlen`
        is ignored.  When `method` is "gust", Gustafsson's method is used,
        and `padtype` and `padlen` are ignored.
    irlen : int or None, optional
        When `method` is "gust", `irlen` specifies the length of the
        impulse response of the filter.  If `irlen` is None, no part
        of the impulse response is ignored.  For a long signal, specifying
        `irlen` can significantly improve the performance of the filter.

    Returns
    -------
    y : ndarray
        The filtered output with the same shape as `x`.

    See Also
    --------
    sosfiltfilt, lfilter_zi, lfilter, lfiltic, savgol_filter, sosfilt

    Notes
    -----
    The option to use Gustaffson's method was added in scipy version 0.16.0.

    References
    ----------
    .. [1] F. Gustaffson, "Determining the initial states in forward-backward
           filtering", Transactions on Signal Processing, Vol. 46, pp. 988-992,
           1996.

    Examples
    --------
    The examples will use several functions from `scipy.signal`.

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

    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.

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

    The following example demonstrates the option ``method="gust"``.

    First, create a filter.

    >>> b, a = signal.ellip(4, 0.01, 120, 0.125)  # Filter to be applied.
    >>> np.random.seed(123456)

    `sig` is a random input signal to be filtered.

    >>> n = 60
    >>> sig = np.random.randn(n)**3 + 3*np.random.randn(n).cumsum()

    Apply `filtfilt` to `sig`, once using the Gustafsson method, and
    once using padding, and plot the results for comparison.

    >>> fgust = signal.filtfilt(b, a, sig, method="gust")
    >>> fpad = signal.filtfilt(b, a, sig, padlen=50)
    >>> plt.plot(sig, 'k-', label='input')
    >>> plt.plot(fgust, 'b-', linewidth=4, label='gust')
    >>> plt.plot(fpad, 'c-', linewidth=1.5, label='pad')
    >>> plt.legend(loc='best')
    >>> plt.show()

    The `irlen` argument can be used to improve the performance
    of Gustafsson's method.

    Estimate the impulse response length of the filter.

    >>> z, p, k = signal.tf2zpk(b, a)
    >>> eps = 1e-9
    >>> r = np.max(np.abs(p))
    >>> approx_impulse_len = int(np.ceil(np.log(eps) / np.log(r)))
    >>> approx_impulse_len
    137

    Apply the filter to a longer signal, with and without the `irlen`
    argument.  The difference between `y1` and `y2` is small.  For long
    signals, using `irlen` gives a significant performance improvement.

    >>> x = np.random.randn(5000)
    >>> y1 = signal.filtfilt(b, a, x, method='gust')
    >>> y2 = signal.filtfilt(b, a, x, method='gust', irlen=approx_impulse_len)
    >>> print(np.max(np.abs(y1 - y2)))
    1.80056858312e-10

    R_   t   gusts   method must be 'pad' or 'gust'.R   R  t   ntapsi   t   stopR  t   startii    (   s   padR  (   R}   R   R   Rg   R  t   _validate_padR   R   RT   Rz   R~   R(   R3   RE   R4   (   R  R   R   R   t   padtypet   padlenR   R  R  t   z1t   z2t   edget   extR  t   zi_shapeR  R   t   y0(    (    s7   /tmp/pip-build-7oUkmx/scipy/scipy/signal/signaltools.pyRX   j  s,    '$(4"c         C` s  |  d
 k r t d |    n  |  d	 k r4 d } n  | d	 k rM | d } n | } | j | | k ry t d |   n  |  d	 k	 r | d k r |  d k r t | | d | } q |  d k r t | | d | } q t | | d | } n | } | | f S(   s'   Helper to validate padding for filtfiltt   evenR  R|  sY   Unknown value '%s' given to padtype.  padtype must be 'even', 'odd', 'constant', or None.i    i   sF   The length of the input vector x must be at least padlen, which is %d.R   N(   R  R  s   constantN(   R   Rg   R   R6   R5   R7   (   R  R  R   R   R  R  R  (    (    s7   /tmp/pip-build-7oUkmx/scipy/scipy/signal/signaltools.pyR  .  s&    	c   
   	   C` sn  t  j |  } t |   \ }  } | d k	 } | r t  j |  } t | j  } d | | <t | g |  } | j | k r t d | | j | | | j f   n  t |  } n  x t	 |  D] } | rt
 |  | d d  f |  | d d  f | | d | | \ } | | <q t
 |  | d d  f |  | d d  f | |  } q W| rd| | f n | }	 |	 S(   sR
  
    Filter data along one dimension using cascaded second-order sections

    Filter a data sequence, `x`, using a digital IIR filter defined by
    `sos`. This is implemented by performing `lfilter` for each
    second-order section.  See `lfilter` for details.

    Parameters
    ----------
    sos : array_like
        Array of second-order filter coefficients, must have shape
        ``(n_sections, 6)``. Each row corresponds to a second-order
        section, with the first three columns providing the numerator
        coefficients and the last three providing the denominator
        coefficients.
    x : array_like
        An N-dimensional input array.
    axis : int, optional
        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 cascaded filter delays.  It is a (at
        least 2D) vector of shape ``(n_sections, ..., 2, ...)``, where
        ``..., 2, ...`` denotes the shape of `x`, but with ``x.shape[axis]``
        replaced by 2.  If `zi` is None or is not given then initial rest
        (i.e. all zeros) is assumed.
        Note that these initial conditions are *not* the same as the initial
        conditions given by `lfiltic` or `lfilter_zi`.

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

    See Also
    --------
    zpk2sos, sos2zpk, sosfilt_zi, sosfiltfilt, sosfreqz

    Notes
    -----
    The filter function is implemented as a series of second-order filters
    with direct-form II transposed structure. It is designed to minimize
    numerical precision errors for high-order filters.

    .. versionadded:: 0.16.0

    Examples
    --------
    Plot a 13th-order filter's impulse response using both `lfilter` and
    `sosfilt`, showing the instability that results from trying to do a
    13th-order filter in a single stage (the numerical error pushes some poles
    outside of the unit circle):

    >>> import matplotlib.pyplot as plt
    >>> from scipy import signal
    >>> b, a = signal.ellip(13, 0.009, 80, 0.05, output='ba')
    >>> sos = signal.ellip(13, 0.009, 80, 0.05, output='sos')
    >>> x = signal.unit_impulse(700)
    >>> y_tf = signal.lfilter(b, a, x)
    >>> y_sos = signal.sosfilt(sos, x)
    >>> plt.plot(y_tf, 'r', label='TF')
    >>> plt.plot(y_sos, 'k', label='SOS')
    >>> plt.legend(loc='best')
    >>> plt.show()

    i   sy   Invalid zi shape. With axis=%r, an input with shape %r, and an sos array with %d sections, zi must have shape %r, got %r.Ni   R  (   R}   R   R9   R   R  R   R   Rg   R0   R   RE   (
   R  R   R   R  R  t   use_zit
   x_zi_shapeR   R  R   (    (    s7   /tmp/pip-build-7oUkmx/scipy/scipy/signal/signaltools.pyRG   Q  s&    G
")#9c         C` s  t  |   \ }  } d | d } | t |  d d  d f d k j   |  d d  d f d k j    8} t | | | | d | \ } } t |   }	 d g | j }
 d |
 | <| g |
 |	 _ t | d d d | } t |  | d | d	 |	 | \ } } t | d
 d d | } t |  t	 | d | d | d	 |	 | \ } } t	 | d | } | d k rt | d
 | d | d | } n  | S(   s/  
    A forward-backward filter using cascaded second-order sections.

    See `filtfilt` for more complete information about this method.

    Parameters
    ----------
    sos : array_like
        Array of second-order filter coefficients, must have shape
        ``(n_sections, 6)``. Each row corresponds to a second-order
        section, with the first three columns providing the numerator
        coefficients and the last three providing the denominator
        coefficients.
    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 * (2 * len(sos) + 1 - min((sos[:, 2] == 0).sum(),
                                        (sos[:, 5] == 0).sum()))

        The extra subtraction at the end attempts to compensate for poles
        and zeros at the origin (e.g. for odd-order filters) to yield
        equivalent estimates of `padlen` to those of `filtfilt` for
        second-order section filters built with `scipy.signal` functions.

    Returns
    -------
    y : ndarray
        The filtered output with the same shape as `x`.

    See Also
    --------
    filtfilt, sosfilt, sosfilt_zi, sosfreqz

    Notes
    -----
    .. versionadded:: 0.18.0
    i   i   Ni    i   R  R  R   R  R  i(
   R9   R   R   R  RU   Rz   R   R3   RG   R4   (   R  R   R   R  R  R  R  R  R  R  R  t   x_0R  R   t   y_0(    (    s7   /tmp/pip-build-7oUkmx/scipy/scipy/signal/signaltools.pyRV     s"    3K
%1"t   iirc   
   
   C` sb  t  | t  s t d   n  | d k	 rI t  | t  rI t d   n  | d k r | d k rj d } n  t t | d d | d d d  } n | d	 k r | d k r d
 } n  t t | d d |    } nO t  | t  r| j   } t j	 | j
 j | j j f  d } n t d   | d k rGt j d t  t } n  t d  g |  j } t | j  d k r| rt |  d | d | d | j
 } qZ|  j | | t |  j | |  }	 t | j
 |  d d d | d | } t d |	 d  | | <n[ | r&t | j
 | j |  d | } n t | j
 | j |  d | } t d d |  | | <| | S(   s/  
    Downsample the signal after applying an anti-aliasing 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. For downsampling factors higher than 13, it is
        recommended to call `decimate` multiple times.
    n : int, optional
        The order of the filter (1 less than the length for 'fir'). Defaults to
        8 for 'iir' and 30 for 'fir'.
    ftype : str {'iir', 'fir'} or ``dlti`` instance, optional
        If 'iir' or 'fir', specifies the type of lowpass filter. If an instance
        of an `dlti` object, uses that object to filter before downsampling.
    axis : int, optional
        The axis along which to decimate.
    zero_phase : bool, optional
        Prevent phase shift by filtering with `filtfilt` instead of `lfilter`
        when using an IIR filter, and shifting the outputs back by the filter's
        group delay when using an FIR filter. A value of ``True`` is
        recommended, since a phase shift is generally not desired. Using
        ``None`` defaults to ``False`` for backwards compatibility. This
        default will change to ``True`` in a future release, so it is best to
        set this argument explicitly.

        .. versionadded:: 0.18.0

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

    See Also
    --------
    resample : Resample up or down using the FFT method.
    resample_poly : Resample using polyphase filtering and an FIR filter.

    Notes
    -----
    The ``zero_phase`` keyword was added in 0.18.0.
    The possibility to use instances of ``dlti`` as ``ftype`` was added in
    0.18.0.
    s   q must be an integers   n must be an integert   firi   i   g      ?R]  t   hammingR  i   g?g?s   invalid ftypes    Note: Decimate's zero_phase keyword argument will default to True in a future release. Until then, decimate defaults to one-way filtering for backwards compatibility. Ideally, always set this argument explicitly.R   Rg  Rh  N(   R2  R   t	   TypeErrorR   R   R:   R8   t   _as_tfR}   R   R*  R~   R+  Rg   R  t   warnt   FutureWarningRp   R   Rz   R   RR   R   Re  R   RX   RE   (
   R   t   qR   t   ftypeR   t
   zero_phaset   systemRa  R  Rj  (    (    s7   /tmp/pip-build-7oUkmx/scipy/scipy/signal/signaltools.pyRY     s@    2	)	(		$&$!(   Rd  g      @(   t
   __future__R    R   R   R  t	   threadingR   R   t    R   R   t   _upfirdnR   R   t   scipy._lib.sixR   t   scipy._lib._versionR   t   scipyR	   R
   t   numpyR   R   R   R   R   R   R   R   R   R   R   R   R   R   R   R   R   R   R   R   R   R    R!   R"   R#   R$   R%   R&   R'   R(   R)   R*   R+   R,   R-   R.   R/   R0   R}   R   t   scipy.specialR1   t   windowsR2   t   _arraytoolsR3   R4   R5   R6   R7   t   filter_designR8   R9   t   fir_filter_designR:   t   version_infot   majort   minorR;   t	   fractionst   __all__Re   Rk   t   __version__R   t   LockR   Rj   Rm   Rw   R<   R   R=   R   R   R   R{   R|   R   R   Rp   RW   R>   RA   R   RB   RD   R?   R@   RC   RE   RF   RH   RI   RJ   RK   RL   RM   RO   RP   RN   RQ   RR   RZ   RS   RT   RU   R  RX   R  RG   RV   RY   (    (    (    s7   /tmp/pip-build-7oUkmx/scipy/scipy/signal/signaltools.pyt   <module>   s   ($&				
		$		
	#{q	>*3`e'D	8s<	LWU]Vw	NR		F	#`J