ó
Ë½÷Xc           @` sû   d  Z  d d l m Z m Z m Z d d l Z d d l m Z d d l	 m
 Z
 m Z d d l m Z d d d	 d
 g Z d d d d „ Z d d d d „ Z d d d d „ Z d d d d „ Z d „  Z d d d d d „ Z d d d d d d d „ Z d S(   s-   
Functions for identifying peaks in signals.
i    (   t   divisiont   print_functiont   absolute_importN(   t   xrange(   t   cwtt   ricker(   t   scoreatpercentilet	   argrelmint	   argrelmaxt   argrelextremat   find_peaks_cwti   t   clipc         C` s  t  | ƒ | k s | d k  r- t d ƒ ‚ n  |  j | } t j d | ƒ } t j |  j d t ƒ} |  j | d | d | ƒ} x t d | d ƒ D]{ }	 |  j | |	 d | d | ƒ}
 |  j | |	 d | d | ƒ} | | | |
 ƒ M} | | | | ƒ M} | j	 ƒ  r“ | Sq“ W| S(   sÌ  
    Calculate the relative extrema of `data`.

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

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

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

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

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

    i   s   Order must be an int >= 1i    t   dtypet   axist   mode(
   t   intt
   ValueErrort   shapet   npt   aranget   onest   boolt   takeR   t   any(   t   datat
   comparatorR   t   orderR   t   datalent   locst   resultst   maint   shiftt   plust   minus(    (    s9   /tmp/pip-build-7oUkmx/scipy/scipy/signal/_peak_finding.pyt   _boolrelextrema   s    )c         C` s   t  |  t j | | | ƒ S(   s~  
    Calculate the relative minima of `data`.

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

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

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

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

    .. versionadded:: 0.11.0

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

    (   R	   R   t   less(   R   R   R   R   (    (    s9   /tmp/pip-build-7oUkmx/scipy/scipy/signal/_peak_finding.pyR   K   s    2c         C` s   t  |  t j | | | ƒ S(   s~  
    Calculate the relative maxima of `data`.

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

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

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

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

    .. versionadded:: 0.11.0

    Examples
    --------
    >>> from scipy.signal import argrelmax
    >>> x = np.array([2, 1, 2, 3, 2, 0, 1, 0])
    >>> argrelmax(x)
    (array([3, 6]),)
    >>> y = np.array([[1, 2, 1, 2],
    ...               [2, 2, 0, 0],
    ...               [5, 3, 4, 4]])
    ...
    >>> argrelmax(y, axis=1)
    (array([0]), array([1]))
    (   R	   R   t   greater(   R   R   R   R   (    (    s9   /tmp/pip-build-7oUkmx/scipy/scipy/signal/_peak_finding.pyR   €   s    1c         C` s%   t  |  | | | | ƒ } t j | ƒ S(   s¿  
    Calculate the relative extrema of `data`.

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

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

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

    Notes
    -----

    .. versionadded:: 0.11.0

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

    (   R"   R   t   where(   R   R   R   R   R   R   (    (    s9   /tmp/pip-build-7oUkmx/scipy/scipy/signal/_peak_finding.pyR	   ´   s    3	c         C` s  t  | ƒ |  j d k  r( t d ƒ ‚ n  t |  t j d d d d ƒ} t j | j d d ƒ ƒ d } t  | ƒ d k r{ g  S| d } g  t j | | ƒ d D] } | g | g d g ^ q } g  } t j | d d d ƒ }	 t j d |  j d ƒ }
 x—|	 D]} |
 | | } x | D] } | d c d 7<qWt j	 g  | D] } | d d ^ q?ƒ } xÕ t
 | ƒ D]Ç \ } } d } t  | ƒ d k rÓt j | | ƒ } t j | ƒ } | | | | k rÓ| | } qÓn  | d k	 r| d j | ƒ | d j | ƒ d | d <qi| g | g d g } | j | ƒ qiWxU t t  | ƒ d d d ƒ D]7 } | | } | d | k rQ| j | ƒ | | =qQqQWqý Wg  } x| | | D]p } t j	 t j | d ƒ ƒ } t j | ƒ t j | ƒ }	 }
 | d |	 | <| d |
 | <| j |	 |
 g ƒ q¡W| S(	   sž  
    Identify ridges in the 2-D matrix.

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

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

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

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

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

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

    i    s5   Max_distances must have at least as many rows as matrR   i   R   iÿÿÿÿi   N(   t   lenR   R   R"   R   R$   R%   R   R   t   arrayt	   enumeratet   Nonet   abst   argmint   appendR   t   argsortt
   zeros_like(   t   matrt   max_distancest
   gap_thresht   all_max_colst
   has_relmaxt	   start_rowt   colt   ridge_linest   final_linest   rowst   colst   rowt   this_max_colst   linet   prev_ridge_colst   indt   diffst   closestt   new_linet	   out_linest   sortargs(    (    s9   /tmp/pip-build-7oUkmx/scipy/scipy/signal/_peak_finding.pyt   _identify_ridge_linesì   sZ    .
6*	#
i
   c         ` s-  ˆ  j  d } ˆ d k r6 t j ˆ  j  d d ƒ ‰ n  | d k rX t j | d ƒ } n  t | ƒ } t | d ƒ \ } } ˆ  d d d … f }	 t j |	 ƒ ‰ xa t |	 ƒ D]S \ }
 } t |
 | d ƒ } t	 |
 | | | ƒ } t
 |	 | | !d | ƒˆ |
 <q« W‡  ‡ ‡ ‡ f d †  } t t | | ƒ ƒ S(	   sd  
    Filter ridge lines according to prescribed criteria. Intended
    to be used for finding relative maxima.

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

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

    i   i    i   i   i   Nt   perc         ` sd   t  |  d ƒ ˆ k  r t St ˆ  |  d d |  d d f ˆ |  d d ƒ } | ˆ k  r` t St S(   Ni    i   (   R&   t   FalseR*   t   True(   R<   t   snr(   R   t
   min_lengtht   min_snrt   noises(    s9   /tmp/pip-build-7oUkmx/scipy/scipy/signal/_peak_finding.pyt	   filt_func™  s    6(   R   R)   R   t   ceilR   t   divmodR.   R(   t   maxt   minR   t   listt   filter(   R   R6   t   window_sizeRI   RJ   t
   noise_perct
   num_pointst	   hf_windowt   oddt   row_oneR>   t   valt   window_startt
   window_endRL   (    (   R   RI   RJ   RK   s9   /tmp/pip-build-7oUkmx/scipy/scipy/signal/_peak_finding.pyt   _filter_ridge_linesd  s     #c      	   C` sÜ   t  j | ƒ } | d k r1 t  j | d ƒ } n  | d k rJ | d } n  | d k r_ t } n  t |  | | ƒ } t | | | ƒ }	 t | |	 d | d | d | ƒ}
 t  j g  |
 D] } | d d ^ q± ƒ } | j ƒ  | S(   sw  
    Attempt to find the peaks in a 1-D array.

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

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

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

    See Also
    --------
    cwt

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

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

    .. versionadded:: 0.11.0

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

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

    i    g      @RI   RJ   RT   i   N(	   R   t   asarrayR)   RM   R   R   RD   R\   t   sort(   t   vectort   widthst   waveletR0   R1   RI   RJ   RT   t   cwt_datR6   t   filteredt   xt   max_locs(    (    s9   /tmp/pip-build-7oUkmx/scipy/scipy/signal/_peak_finding.pyR
   ¤  s    W	*
(   t   __doc__t
   __future__R    R   R   t   numpyR   t   scipy._lib.sixR   t   scipy.signal.waveletsR   R   t   scipy.statsR   t   __all__R"   R   R   R	   RD   R)   R\   R
   (    (    (    s9   /tmp/pip-build-7oUkmx/scipy/scipy/signal/_peak_finding.pyt   <module>   s   ;548	x?