3
6Ad]GÁ  ã               @   s   d Z ddlZddlZddlZddljZddlmZ dd„ Z	dd„ Z
d@dd	„ZdAd
d„Zejddd�dBdd„ƒZdCdd„ZdDdd„Zdd„ ZdEdd„ZdFdd„ZdGdd„ZdHdd„Zejjejdƒd� ejjejd ƒd!� ejjejd"ƒd#� ejdId$d%„ƒZejdJd&d'„ƒZejdKd(d)„ƒZejdLd*d+„ƒZejdMd,d-„ƒZejdNd.d/„ƒZejdOd0d1„ƒZ d2Z!ejd3d4ee	ddd5dfd6d7„ƒZ"dPd<d=„Z#G d>d?„ d?e$ƒZ%dS )Qa  
Numerical python functions written for compatibility with MATLAB
commands with the same names. Most numerical python functions can be found in
the `numpy` and `scipy` libraries. What remains here is code for performing
spectral computations.

Spectral functions
-------------------

`cohere`
    Coherence (normalized cross spectral density)

`csd`
    Cross spectral density using Welch's average periodogram

`detrend`
    Remove the mean or best fit line from an array

`psd`
    Power spectral density using Welch's average periodogram

`specgram`
    Spectrogram (spectrum over segments of time)

`complex_spectrum`
    Return the complex-valued frequency spectrum of a signal

`magnitude_spectrum`
    Return the magnitude of the frequency spectrum of a signal

`angle_spectrum`
    Return the angle (wrapped phase) of the frequency spectrum of a signal

`phase_spectrum`
    Return the phase (unwrapped angle) of the frequency spectrum of a signal

`detrend_mean`
    Remove the mean from a line.

`detrend_linear`
    Remove the best fit line from a line.

`detrend_none`
    Return the original line.

`stride_windows`
    Get all windows in an array in a memory-efficient manner

`stride_repeat`
    Repeat an array in a memory-efficient manner

`apply_window`
    Apply a window along a given axis
é    N)Ú	docstringc             C   s   t jt| ƒƒ|  S )z}
    Return x times the hanning window of len(x).

    See Also
    --------
    window_none : Another window algorithm.
    )ÚnpÚhanningÚlen)Úx© r   úz/home/yuhw/wc/wire-cell-python/wcpy/lib/python3.6/site-packages/matplotlib-3.1.1-py3.6-linux-x86_64.egg/matplotlib/mlab.pyÚwindow_hanningA   s    r	   c             C   s   | S )zx
    No window function; simply return x.

    See Also
    --------
    window_hanning : Another window algorithm.
    r   )r   r   r   r   Úwindow_noneL   s    r
   c       
      C   sì   t j| ƒ} | jdk s| jdkr&tdƒ‚|d | jkr@td| ƒ‚t| jƒ}|j|ƒ}t j|ƒrxt|ƒ|krrtdƒ‚|}n|t j	|| j
d�ƒ}| jdkr®|r¦||  |fS ||  S |jƒ }|d d }t|||d�}	|rà|	|  |fS |	|  S dS )	a  
    Apply the given window to the given 1D or 2D array along the given axis.

    Parameters
    ----------
    x : 1D or 2D array or sequence
        Array or sequence containing the data.

    window : function or array.
        Either a function to generate a window or an array with length
        *x*.shape[*axis*]

    axis : integer
        The axis over which to do the repetition.
        Must be 0 or 1.  The default is 0

    return_window : bool
        If true, also return the 1D values of the window that was applied
    é   é   z only 1D or 2D arrays can be usedzaxis(=%s) out of boundszFThe len(window) must be the same as the shape of x for the chosen axis)Údtype)ÚaxisN)r   ÚasarrayÚndimÚ
ValueErrorÚlistÚshapeÚpopÚiterabler   Úonesr   Ústride_repeat)
r   Úwindowr   Úreturn_windowÚxshapeZ
xshapetargÚ
windowValsZxshapeotherZ	otheraxisZwindowValsRepr   r   r   Úapply_windowW   s,    




r   c             C   sþ   |dks|dkrt | t|d�S |dkr4t | t|d�S |dkrJt | t|d�S t|tƒr`td| ƒ‚t|ƒsttd| ƒ‚tj	| ƒ} |dk	r |d	 | j
kr td
| ƒ‚|dkr²| j
dksÂ| rÊ| j
d	krÊ|| ƒS y|| |d�S  tk
� rø   tj||| d�S X dS )a’  
    Return x with its trend removed.

    Parameters
    ----------
    x : array or sequence
        Array or sequence containing the data.

    key : [ 'default' | 'constant' | 'mean' | 'linear' | 'none'] or function
        Specifies the detrend algorithm to use. 'default' is 'mean', which is
        the same as `detrend_mean`. 'constant' is the same. 'linear' is
        the same as `detrend_linear`. 'none' is the same as
        `detrend_none`. The default is 'mean'. See the corresponding
        functions for more details regarding the algorithms. Can also be a
        function that carries out the detrend operation.

    axis : integer
        The axis along which to do the detrending.

    See Also
    --------
    detrend_mean : Implementation of the 'mean' algorithm.
    detrend_linear : Implementation of the 'linear' algorithm.
    detrend_none : Implementation of the 'none' algorithm.
    NÚconstantÚmeanÚdefault)Úkeyr   ÚlinearÚnonez`Unknown value for key %s, must be one of: 'default', 'constant', 'mean', 'linear', or a functionr   zaxis(=%s) out of boundsr   )r   )r   Úarr)r   r   r   )ÚdetrendÚdetrend_meanÚdetrend_linearÚdetrend_noneÚ
isinstanceÚstrr   Úcallabler   r   r   Ú	TypeErrorÚapply_along_axis)r   r    r   r   r   r   r$   �   s*    

"r$   z3.1r%   )Úalternativec             C   s   t | |d�S )a£  
    Return x minus its mean along the specified axis.

    Parameters
    ----------
    x : array or sequence
        Array or sequence containing the data
        Can have any dimensionality

    axis : integer
        The axis along which to take the mean.  See numpy.mean for a
        description of this argument.

    See Also
    --------
    detrend_mean : Same as `demean` except for the default *axis*.
    )r   )r%   )r   r   r   r   r   ÚdemeanÉ   s    r.   c             C   s>   t j| ƒ} |dk	r,|d | jkr,td| ƒ‚| | j|dd� S )aã  
    Return x minus the mean(x).

    Parameters
    ----------
    x : array or sequence
        Array or sequence containing the data
        Can have any dimensionality

    axis : integer
        The axis along which to take the mean.  See numpy.mean for a
        description of this argument.

    See Also
    --------
    detrend_linear : Another detrend algorithm.
    detrend_none : Another detrend algorithm.
    detrend : A wrapper around all the detrend algorithms.
    Nr   zaxis(=%s) out of boundsT)Úkeepdims)r   r   r   r   r   )r   r   r   r   r   r%   ß   s    
c             C   s   | S )a   
    Return x: no detrending.

    Parameters
    ----------
    x : any object
        An object containing the data

    axis : integer
        This parameter is ignored.
        It is included for compatibility with detrend_mean

    See Also
    --------
    detrend_mean : Another detrend algorithm.
    detrend_linear : Another detrend algorithm.
    detrend : A wrapper around all the detrend algorithms.
    r   )r   r   r   r   r   r'   û   s    r'   c             C   s†   t j| ƒ} | jdkrtdƒ‚| js2t jd| jd�S t j| jtd�}t j	|| dd�}|d |d  }| j
ƒ ||j
ƒ   }| || |  S )	aß  
    Return x minus best fit line; 'linear' detrending.

    Parameters
    ----------
    y : 0-D or 1-D array or sequence
        Array or sequence containing the data

    axis : integer
        The axis along which to take the mean.  See numpy.mean for a
        description of this argument.

    See Also
    --------
    detrend_mean : Another detrend algorithm.
    detrend_none : Another detrend algorithm.
    detrend : A wrapper around all the detrend algorithms.
    r   zy cannot have ndim > 1g        )r   )Úbiasr   )r   r   )r   r   )r   r   r   r   Úarrayr   ÚarangeÚsizeÚfloatÚcovr   )Úyr   ÚCÚbÚar   r   r   r&     s    

r&   c             C   s  |dkrd}||krt dƒ‚|dk r,t dƒ‚tj| ƒ} | jdkrHt dƒ‚|dkrx|dkrx|dkrj| tj S | tj jƒ S || jkrŠt dƒ‚t|ƒ}t|ƒ}|| }|dkrÚ|| jd	 | | f}| j	d || j	d  f}n.| jd
 | | |f}|| j	d  | j	d f}tj
jj| ||d�S )a~  
    Get all windows of x with length n as a single array,
    using strides to avoid data duplication.

    .. warning::

        It is not safe to write to the output array.  Multiple
        elements may point to the same piece of memory,
        so modifying one value may change others.

    Parameters
    ----------
    x : 1D array or sequence
        Array or sequence containing the data.

    n : integer
        The number of data points in each window.

    noverlap : integer
        The overlap between adjacent windows.
        Default is 0 (no overlap)

    axis : integer
        The axis along which the windows will run.

    References
    ----------
    `stackoverflow: Rolling window for 1D arrays in Numpy?
    <http://stackoverflow.com/a/6811241>`_
    `stackoverflow: Using strides for an efficient moving average filter
    <http://stackoverflow.com/a/4947453>`_
    Nr   znoverlap must be less than nr   zn cannot be less than 1z%only 1-dimensional arrays can be usedz(n cannot be greater than the length of x)r   Ústrideséÿÿÿÿr;   )r   r   r   r   ÚnewaxisÚ	transposer3   Úintr   r:   ÚlibÚstride_tricksÚ
as_strided)r   ÚnÚnoverlapr   Ústepr   r:   r   r   r   Ústride_windows7  s0    !



rE   c             C   s¸   |dkrt dƒ‚tj| ƒ} | jdkr,t dƒ‚|dkrR|dkrFtj| ƒS tj| ƒjS |dk rbt dƒ‚t|ƒ}|dkrŒ|| jf}d| jd f}n| j|f}| jd df}tj	j
j| ||d�S )a¨  
    Repeat the values in an array in a memory-efficient manner.  Array x is
    stacked vertically n times.

    .. warning::

        It is not safe to write to the output array.  Multiple
        elements may point to the same piece of memory, so
        modifying one value may change others.

    Parameters
    ----------
    x : 1D array or sequence
        Array or sequence containing the data.

    n : integer
        The number of time to repeat the array.

    axis : integer
        The axis along which the data will run.

    References
    ----------
    `stackoverflow: Repeat NumPy array without replicating data?
    <http://stackoverflow.com/a/5568169>`_
    r   r   zaxis must be 0 or 1z%only 1-dimensional arrays can be usedzn cannot be less than 1)r   r:   )r   r   )r   r   r   r   Ú
atleast_2dÚTr>   r3   r:   r?   r@   rA   )r   rB   r   r   r:   r   r   r   r   {  s$    




r   c             C   s`  |dkrd}n|| k}|dkr"d}|dkr.d}|dkr:t }|dkrFt}|dkrRd}|
dksb|
dkrhd}
n|
dkr|td|
 ƒ‚| r’|
dkr’tdƒ‚tj| ƒ} |sªtj|ƒ}|dksº|dkrÐtj| ƒrÊd}qäd}n|dkrätd| ƒ‚t| ƒ|k �rt| ƒ}tj| |ƒ} d| |d…< | �rHt|ƒ|k �rHt|ƒ}tj||ƒ}d||d…< |dk�rV|}|
dk�rfd}	n|	dk�rtd}	|dk�r¬|}|d �rž|d d d }n|d }d}n2|dk�rÞ|d �rÎ|d d }n|d d }d}t| ||dd�}t	||dd�}t
||ddd�\}}tjj||dd�d|…dd…f }tjj|d| ƒd|… }|�s¬t|||ƒ}t	||dd�}t
||dd�}tjj||dd�d|…dd…f }tj|ƒ| }nz|
dk�rÆtj|ƒ| }n`|
d	k�rêtj|ƒtj|ƒjƒ  }n<|
d
k�sþ|
dk�r
tj|ƒ}n|
dk�r&|tj|ƒjƒ  }|
dk�r |d �sHtdddƒ}ntdddƒ}||  |9  < |	�rŠ|| }|tj|ƒd jƒ  }n|tj|ƒjƒ d  }tj|d t| ƒ|d  d || ƒ| }|dk�r$tj||d… |d|… fƒ}tj||d…dd…f |d|…dd…f fdƒ}n|d �s>|d  d9  < |
dk�rVtj|dd�}|||fS )zê
    This is a helper function that implements the commonality between the
    psd, csd, spectrogram and complex, magnitude, angle, and phase spectrums.
    It is *NOT* meant to be used outside of mlab and may change at any time.
    NTr   r   é   r   ÚpsdÚcomplexÚ	magnitudeÚangleÚphasezeUnknown value for mode %s, must be one of: 'default', 'psd', 'complex', 'magnitude', 'angle', 'phase'z*x and y must be equal if mode is not 'psd'ÚtwosidedÚonesidedzPUnknown value for sides %s, must be one of: 'default', 'onesided', or 'twosided'Fr   g      ð?g       @)r   )r   r   )rB   r   )rI   rJ   rK   rL   rM   )rO   rN   r;   r;   r;   )r'   r	   r   r   r   Úiscomplexobjr   ÚresizerE   r$   r   ÚfftÚfftfreqÚconjÚabsÚsumrL   Úslicer2   ÚconcatenateÚunwrap)r   r6   ÚNFFTÚFsÚdetrend_funcr   rC   Úpad_toÚsidesÚscale_by_freqÚmodeZ	same_datarB   ZnumFreqsZ
freqcenterZscaling_factorÚresultr   ÚfreqsZresultYÚslcÚtr   r   r   Ú_spectral_helper²  s¼    









""




*


re   c       	      C   sš   |dks|dks|dkr$t d| ƒ‚|dkr4t| ƒ}t| dt| ƒ|t|d||d|d�\}}}|dkrj|j}|jd	kr’|jd
 d
kr’|dd…df }||fS )zÐ
    This is a helper function that implements the commonality between the
    complex, magnitude, angle, and phase spectrums.
    It is *NOT* meant to be used outside of mlab and may change at any time.
    NrI   r   z2_single_spectrum_helper does not work with %s moder   F)r   r6   rZ   r[   r\   r   rC   r]   r^   r_   r`   rJ   r   r   )r   r   re   r'   Úrealr   r   )	r   r`   r[   r   r]   r^   Úspecrb   Ú_r   r   r   Ú_single_spectrum_helperP  s     ri   aË  
    Fs : scalar
        The sampling frequency (samples per time unit).  It is used
        to calculate the Fourier frequencies, freqs, in cycles per time
        unit. The default value is 2.

    window : callable or ndarray
        A function or a vector of length *NFFT*.  To create window vectors see
        `window_hanning`, `window_none`, `numpy.blackman`, `numpy.hamming`,
        `numpy.bartlett`, `scipy.signal`, `scipy.signal.get_window`, etc.  The
        default is `window_hanning`.  If a function is passed as the argument,
        it must take a data segment as an argument and return the windowed
        version of the segment.

    sides : {'default', 'onesided', 'twosided'}
        Specifies which sides of the spectrum to return.  Default gives the
        default behavior, which returns one-sided for real data and both
        for complex data.  'onesided' forces the return of a one-sided
        spectrum, while 'twosided' forces two-sided.
)ÚSpectralaê  
    pad_to : int
        The number of points to which the data segment is padded when
        performing the FFT.  While not increasing the actual resolution of
        the spectrum (the minimum distance between resolvable peaks),
        this can give more points in the plot, allowing for more
        detail. This corresponds to the *n* parameter in the call to fft().
        The default is None, which sets *pad_to* equal to the length of the
        input signal (i.e. no padding).
)ZSingle_SpectrumaÜ  
    pad_to : int
        The number of points to which the data segment is padded when
        performing the FFT.  This can be different from *NFFT*, which
        specifies the number of data points used.  While not increasing
        the actual resolution of the spectrum (the minimum distance between
        resolvable peaks), this can give more points in the plot,
        allowing for more detail. This corresponds to the *n* parameter
        in the call to fft(). The default is None, which sets *pad_to*
        equal to *NFFT*

    NFFT : int
        The number of data points used in each block for the FFT.
        A power 2 is most efficient.  The default value is 256.
        This should *NOT* be used to get zero padding, or the scaling of the
        result will be incorrect. Use *pad_to* for this instead.

    detrend : {'none', 'mean', 'linear'} or callable, default 'none'
        The function applied to each segment before fft-ing, designed to
        remove the mean or linear trend.  Unlike in MATLAB, where the
        *detrend* parameter is a vector, in Matplotlib is it a function.
        The :mod:`~matplotlib.mlab` module defines `.detrend_none`,
        `.detrend_mean`, and `.detrend_linear`, but you can use a custom
        function as well.  You can also use a string to choose one of the
        functions: 'none' calls `.detrend_none`. 'mean' calls `.detrend_mean`.
        'linear' calls `.detrend_linear`.

    scale_by_freq : bool, optional
        Specifies whether the resulting density values should be scaled
        by the scaling frequency, which gives density in units of Hz^-1.
        This allows for integration over the returned frequency values.
        The default is True for MATLAB compatibility.
)ZPSDc	             C   s*   t | d||||||||d�
\}	}
|	j|
fS )a‘  
    Compute the power spectral density.

    The power spectral density :math:`P_{xx}` by Welch's average
    periodogram method.  The vector *x* is divided into *NFFT* length
    segments.  Each segment is detrended by function *detrend* and
    windowed by function *window*.  *noverlap* gives the length of
    the overlap between segments.  The :math:`|\mathrm{fft}(i)|^2`
    of each segment :math:`i` are averaged to compute :math:`P_{xx}`.

    If len(*x*) < *NFFT*, it will be zero padded to *NFFT*.

    Parameters
    ----------
    x : 1-D array or sequence
        Array or sequence containing the data

    %(Spectral)s

    %(PSD)s

    noverlap : integer
        The number of points of overlap between segments.
        The default value is 0 (no overlap).

    Returns
    -------
    Pxx : 1-D array
        The values for the power spectrum `P_{xx}` (real valued)

    freqs : 1-D array
        The frequencies corresponding to the elements in *Pxx*

    References
    ----------
    Bendat & Piersol -- Random Data: Analysis and Measurement Procedures, John
    Wiley & Sons (1986)

    See Also
    --------
    specgram
        `specgram` differs in the default overlap; in not returning the mean of
        the segment periodograms; and in returning the times of the segments.

    magnitude_spectrum : returns the magnitude spectrum.

    csd : returns the spectral density between two signals.
    N)
r   r6   rZ   r[   r$   r   rC   r]   r^   r_   )Úcsdrf   )r   rZ   r[   r$   r   rC   r]   r^   r_   ÚPxxrb   r   r   r   rI   ³  s    3rI   c
             C   sn   |dkrd}t | |||||||||	dd�\}
}}|
jdkrf|
jd dkrV|
jdd�}
n|
dd…df }
|
|fS )	a  
    Compute the cross-spectral density.

    The cross spectral density :math:`P_{xy}` by Welch's average
    periodogram method.  The vectors *x* and *y* are divided into
    *NFFT* length segments.  Each segment is detrended by function
    *detrend* and windowed by function *window*.  *noverlap* gives
    the length of the overlap between segments.  The product of
    the direct FFTs of *x* and *y* are averaged over each segment
    to compute :math:`P_{xy}`, with a scaling to correct for power
    loss due to windowing.

    If len(*x*) < *NFFT* or len(*y*) < *NFFT*, they will be zero
    padded to *NFFT*.

    Parameters
    ----------
    x, y : 1-D arrays or sequences
        Arrays or sequences containing the data

    %(Spectral)s

    %(PSD)s

    noverlap : integer
        The number of points of overlap between segments.
        The default value is 0 (no overlap).

    Returns
    -------
    Pxy : 1-D array
        The values for the cross spectrum `P_{xy}` before scaling (real valued)

    freqs : 1-D array
        The frequencies corresponding to the elements in *Pxy*

    References
    ----------
    Bendat & Piersol -- Random Data: Analysis and Measurement Procedures, John
    Wiley & Sons (1986)

    See Also
    --------
    psd : equivalent to setting ``y = x``.
    NrH   rI   )r   r6   rZ   r[   r\   r   rC   r]   r^   r_   r`   r   r   )r   r   )re   r   r   r   )r   r6   rZ   r[   r$   r   rC   r]   r^   r_   ÚPxyrb   rh   r   r   r   rk   ì  s    0

rk   c             C   s   t | ||||dd�S )aX  
    Compute the complex-valued frequency spectrum of *x*.  Data is padded to a
    length of *pad_to* and the windowing function *window* is applied to the
    signal.

    Parameters
    ----------
    x : 1-D array or sequence
        Array or sequence containing the data

    %(Spectral)s

    %(Single_Spectrum)s

    Returns
    -------
    spectrum : 1-D array
        The values for the complex spectrum (complex valued)

    freqs : 1-D array
        The frequencies corresponding to the elements in *spectrum*

    See Also
    --------
    magnitude_spectrum
        Returns the absolute value of this function.
    angle_spectrum
        Returns the angle of this function.
    phase_spectrum
        Returns the phase (unwrapped angle) of this function.
    specgram
        Can return the complex spectrum of segments within the signal.
    rJ   )r   r[   r   r]   r^   r`   )ri   )r   r[   r   r]   r^   r   r   r   Úcomplex_spectrum,  s    $
rn   c             C   s   t | ||||dd�S )aÐ  
    Compute the magnitude (absolute value) of the frequency spectrum of
    *x*.  Data is padded to a length of *pad_to* and the windowing function
    *window* is applied to the signal.

    Parameters
    ----------
    x : 1-D array or sequence
        Array or sequence containing the data

    %(Spectral)s

    %(Single_Spectrum)s

    Returns
    -------
    spectrum : 1-D array
        The values for the magnitude spectrum (real valued)

    freqs : 1-D array
        The frequencies corresponding to the elements in *spectrum*

    See Also
    --------
    psd
        Returns the power spectral density.
    complex_spectrum
        This function returns the absolute value of `complex_spectrum`.
    angle_spectrum
        Returns the angles of the corresponding frequencies.
    phase_spectrum
        Returns the phase (unwrapped angle) of the corresponding frequencies.
    specgram
        Can return the complex spectrum of segments within the signal.
    rK   )r   r[   r   r]   r^   r`   )ri   )r   r[   r   r]   r^   r   r   r   Úmagnitude_spectrumT  s    &
ro   c             C   s   t | ||||dd�S )a¬  
    Compute the angle of the frequency spectrum (wrapped phase spectrum) of
    *x*.  Data is padded to a length of *pad_to* and the windowing function
    *window* is applied to the signal.

    Parameters
    ----------
    x : 1-D array or sequence
        Array or sequence containing the data

    %(Spectral)s

    %(Single_Spectrum)s

    Returns
    -------
    spectrum : 1-D array
        The values for the angle spectrum in radians (real valued)

    freqs : 1-D array
        The frequencies corresponding to the elements in *spectrum*

    See Also
    --------
    complex_spectrum
        This function returns the angle value of `complex_spectrum`.
    magnitude_spectrum
        Returns the magnitudes of the corresponding frequencies.
    phase_spectrum
        Returns the phase (unwrapped angle) of the corresponding frequencies.
    specgram
        Can return the complex spectrum of segments within the signal.
    rL   )r   r[   r   r]   r^   r`   )ri   )r   r[   r   r]   r^   r   r   r   Úangle_spectrum~  s    $
rp   c             C   s   t | ||||dd�S )a¬  
    Compute the phase of the frequency spectrum (unwrapped angle spectrum) of
    *x*.  Data is padded to a length of *pad_to* and the windowing function
    *window* is applied to the signal.

    Parameters
    ----------
    x : 1-D array or sequence
        Array or sequence containing the data

    %(Spectral)s

    %(Single_Spectrum)s

    Returns
    -------
    spectrum : 1-D array
        The values for the phase spectrum in radians (real valued)

    freqs : 1-D array
        The frequencies corresponding to the elements in *spectrum*

    See Also
    --------
    complex_spectrum
        This function returns the phase value of `complex_spectrum`.
    magnitude_spectrum
        Returns the magnitudes of the corresponding frequencies.
    angle_spectrum
        Returns the angle (wrapped phase) of the corresponding frequencies.
    specgram
        Can return the complex spectrum of segments within the signal.
    rM   )r   r[   r   r]   r^   r`   )ri   )r   r[   r   r]   r^   r   r   r   Úphase_spectrum¦  s    $
rq   c
             C   sv   |dkrd}|dkrd}t | ƒ|kr:tjd|t | ƒf ƒ t| d|||||||||	d�\}
}}|	dkrl|
j}
|
||fS )a&  
    Compute a spectrogram.

    Compute and plot a spectrogram of data in x.  Data are split into
    NFFT length segments and the spectrum of each section is
    computed.  The windowing function window is applied to each
    segment, and the amount of overlap of each segment is
    specified with noverlap.

    Parameters
    ----------
    x : array_like
        1-D array or sequence.

    %(Spectral)s

    %(PSD)s

    noverlap : int, optional
        The number of points of overlap between blocks.  The default
        value is 128.
    mode : str, optional
        What sort of spectrum to use, default is 'psd'.
            'psd'
                Returns the power spectral density.

            'complex'
                Returns the complex-valued frequency spectrum.

            'magnitude'
                Returns the magnitude spectrum.

            'angle'
                Returns the phase spectrum without unwrapping.

            'phase'
                Returns the phase spectrum with unwrapping.

    Returns
    -------
    spectrum : array_like
        2-D array, columns are the periodograms of successive segments.

    freqs : array_like
        1-D array, frequencies corresponding to the rows in *spectrum*.

    t : array_like
        1-D array, the times corresponding to midpoints of segments
        (i.e the columns in *spectrum*).

    See Also
    --------
    psd : differs in the overlap and in the return values.
    complex_spectrum : similar, but with complex valued frequencies.
    magnitude_spectrum : similar single segment when mode is 'magnitude'.
    angle_spectrum : similar to single segment when mode is 'angle'.
    phase_spectrum : similar to single segment when mode is 'phase'.

    Notes
    -----
    detrend and scale_by_freq only apply when *mode* is set to 'psd'.

    Né€   rH   zQOnly one segment is calculated since parameter NFFT (=%d) >= signal length (=%d).)r   r6   rZ   r[   r\   r   rC   r]   r^   r_   r`   rJ   )r   ÚcbookÚ_warn_externalre   rf   )r   rZ   r[   r$   r   rC   r]   r^   r_   r`   rg   rb   rd   r   r   r   ÚspecgramÎ  s     C
ru   zwCoherence is calculated by averaging over *NFFT*
length segments.  Your signal is too short for your choice of *NFFT*.
rH   r   r   c
             C   sŒ   t | ƒd| k rttƒ‚t| ||||||||	ƒ	\}
}t|||||||||	ƒ	\}}t| |||||||||	ƒ
\}}tj|ƒd |
|  }||fS )aH  
    The coherence between *x* and *y*.  Coherence is the normalized
    cross spectral density:

    .. math::

        C_{xy} = \frac{|P_{xy}|^2}{P_{xx}P_{yy}}

    Parameters
    ----------
    x, y
        Array or sequence containing the data

    %(Spectral)s

    %(PSD)s

    noverlap : integer
        The number of points of overlap between blocks.  The default value
        is 0 (no overlap).

    Returns
    -------
    The return value is the tuple (*Cxy*, *f*), where *f* are the
    frequencies of the coherence vector. For cohere, scaling the
    individual densities by the sampling frequency has no effect,
    since the factors cancel out.

    See Also
    --------
    :func:`psd`, :func:`csd` :
        For information about the methods used to compute :math:`P_{xy}`,
        :math:`P_{xx}` and :math:`P_{yy}`.
    r   )r   r   Ú
_coh_errorrI   rk   r   rU   )r   r6   rZ   r[   r$   r   rC   r]   r^   r_   rl   ÚfZPyyrm   ZCxyr   r   r   Úcohere,  s    &


rx   ú#ú,Ú Fc                sî  ˆdkrt ƒ ‰ˆ	dkri ‰	ddl}ddl}tj| ƒ‰t|ƒ}G dd„ dƒ}|dkrZ|ˆƒ‰tjˆ|d�}‡‡fdd„}||ƒ ‡‡	fd	d
„‰‡fdd„‰dd„ ‰
|jj	‰‡‡‡fdd„‰ˆˆ|jdddƒƒ‰ˆt
tjƒ‰ˆtd+ƒ‰ˆtdƒ‰ˆˆ
dƒ‰
‡‡‡fdd„‰ˆˆ|jdddƒƒ‰‡
‡‡‡‡‡fdd„‰ddddœ}‡ ‡‡‡
‡‡fdd„}ˆdk}|�r^x<|D ]4}t|ƒ�r’|dk	�r’|d j|ƒ�r’�qf|}P �qfW tdƒ‰ˆjdƒ g ‰t ƒ }xÂt|ƒD ]”\}}|jƒ jƒ jddƒ}dj‡fd d!„|D ƒƒ}t|ƒ�s
d"| }|j||ƒ}|j|dƒ}|dk�r@ˆj|d#|  ƒ n
ˆj|ƒ |d ||< �qÄW n tˆtƒ�r~d$d!„ ˆjd%ƒD ƒ‰|||ƒ}|dk�rštd&ƒ‚ˆjdƒ tjˆ|d�}||ƒ |�rúx8t|ƒ}t|ƒ�rò|dk	�rò|d j|ƒ�rò�qÂP �qÂW g }g }x˜t|ƒD ]Œ\}}t|ƒ�s"�q|dk	�r@|d j|ƒ�r@�q|jdgt|ƒt|ƒ  ƒ |jd'd!„ t |ˆ|ƒD ƒƒ |j‡fd(d!„t ˆ|ƒD ƒƒ �qW ˆj!ƒ  t|ƒ�s²dS |	�rÚtj"|ƒ�rÚtj#j$j%|ˆ|d)�}ntj&j%|ˆd*�}|S ),a.  
    Load data from comma/space/tab delimited file in *fname* into a
    numpy record array and return the record array.

    If *names* is *None*, a header row is required to automatically
    assign the recarray names.  The headers will be lower cased,
    spaces will be converted to underscores, and illegal attribute
    name characters removed.  If *names* is not *None*, it is a
    sequence of names to use for the column names.  In this case, it
    is assumed there is no header row.


    - *fname*: can be a filename or a file handle.  Support for gzipped
      files is automatic, if the filename ends in '.gz'

    - *comments*: the character used to indicate the start of a comment
      in the file, or *None* to switch off the removal of comments

    - *skiprows*: is the number of rows from the top to skip

    - *checkrows*: is the number of rows to check to validate the column
      data type.  When set to zero all rows are validated.

    - *converterd*: if not *None*, is a dictionary mapping column number or
      munged column name to a converter function.

    - *names*: if not None, is a list of header names.  In this case, no
      header will be read from the file

    - *missingd* is a dictionary mapping munged column names to field values
      which signify that the field does not contain actual data and should
      be masked, e.g., '0000-00-00' or 'unused'

    - *missing*: a string whose value signals a missing field regardless of
      the column it appears in

    - *use_mrecords*: if True, return an mrecords.fromrecords record array if
      any of the data are missing

    - *dayfirst*: default is False so that MM-DD-YY has precedence over
      DD-MM-YY.  See
      http://labix.org/python-dateutil#head-b95ce2094d189a89f80f5ae52a05b4ab7b41af47
      for further information.

    - *yearfirst*: default is False so that MM-DD-YY has precedence over
      YY-MM-DD. See
      http://labix.org/python-dateutil#head-b95ce2094d189a89f80f5ae52a05b4ab7b41af47
      for further information.

      If no rows are found, *None* is returned
    Nr   c               @   s@   e Zd ZdZdd„ Zdd„ Zdd„ Zdd	„ Zd
d„ Zdd„ Z	dS )z_csv2rec.<locals>.FHaC  
        For space-delimited files, we want different behavior than
        comma or tab.  Generally, we want multiple spaces to be
        treated as a single separator, whereas with comma and tab we
        want multiple commas to return multiple (empty) fields.  The
        join/strip trick below effects this.
        c             S   s
   || _ d S )N)Úfh)Úselfr|   r   r   r   Ú__init__ª  s    z_csv2rec.<locals>.FH.__init__c             S   s   | j jƒ  d S )N)r|   Úclose)r}   r   r   r   r   ­  s    z_csv2rec.<locals>.FH.closec             S   s   | j j|ƒ d S )N)r|   Úseek)r}   Úargr   r   r   r€   °  s    z_csv2rec.<locals>.FH.seekc             S   s   dj |jƒ ƒS )Nú )ÚjoinÚsplit)r}   Úsr   r   r   Úfix³  s    z_csv2rec.<locals>.FH.fixc             S   s   | j t| jƒƒS )N)r†   Únextr|   )r}   r   r   r   Ú__next__¶  s    z_csv2rec.<locals>.FH.__next__c             s   s    x| j D ]}| j|ƒV  qW d S )N)r|   r†   )r}   Úliner   r   r   Ú__iter__¹  s    z_csv2rec.<locals>.FH.__iter__N)
Ú__name__Ú
__module__Ú__qualname__Ú__doc__r~   r   r€   r†   rˆ   rŠ   r   r   r   r   ÚFH¢  s   r�   r‚   )Ú	delimiterc                s0   ˆr(x"t | ƒD ]\}}|ˆd krP qW ˆ | fS )Nr   )Ú	enumerate)ÚreaderÚiÚrow)r|   Úskiprowsr   r   Úprocess_skiprowsÂ  s
    z"_csv2rec.<locals>.process_skiprowsc                s   |ˆ kp|ˆj | ƒkp|dkS )z.Should the value val in column name be masked?r{   )Úget)ÚnameÚval)ÚmissingÚmissingdr   r   Ú	ismissingÌ  s    z_csv2rec.<locals>.ismissingc                s   ‡ ‡‡fdd„}|S )Nc                s   ˆ| |ƒrˆ S ˆ|ƒS d S )Nr   )r˜   r™   )r   Úfuncrœ   r   r   ÚnewfuncÑ  s    
z5_csv2rec.<locals>.with_default_value.<locals>.newfuncr   )r�   r   rž   )rœ   )r   r�   r   Úwith_default_valueÐ  s    z$_csv2rec.<locals>.with_default_valuec             S   s$   | dkrdS | dkrdS t dƒ‚d S )NÚTrueTÚFalseFzinvalid bool)r   )r   r   r   r   ÚmyboolØ  s
    z_csv2rec.<locals>.myboolc                s   ˆ | ˆˆd�}|S )N)ÚdayfirstÚ	yearfirstr   )r   Úd)Ú
dateparserr£   r¤   r   r   Úmydateparserâ  s    z_csv2rec.<locals>.mydateparserr   r{   c                s<   ˆ | ˆˆd�}|j dks,|jdks,|jdkr4tdƒ‚|jƒ S )N)r£   r¤   r   z
not a date)ÚhourÚminuteÚsecondr   Údate)r   r¥   )r¦   r£   r¤   r   r   Úmydateî  s    z_csv2rec.<locals>.mydatec                s`   ˆ ˆˆˆˆˆg}xB||j |ƒd … D ],}y|| |ƒ W n tk
rL   w$Y nX |S W tdƒ‚d S )Nz,Could not find a working conversion function)ÚindexÚ	Exceptionr   )r˜   Úitemr�   Úfuncs)r¢   r¬   r§   ÚmyfloatÚmyintÚmystrr   r   Úget_func÷  s    z_csv2rec.<locals>.get_funcZreturn_Zfile_Úprint_)ÚreturnÚfileÚprintc       	         sÞ   d }d}xÐ| D ]È}t |ƒr2|d k	r2|d j|ƒr2q|dkrHˆgt |ƒ }ˆ rV|ˆ krVP |d7 }xvttˆ|ƒƒD ]d\}\}}ˆj|ƒ}|d kr–ˆj|ƒ}|d krÀ|| }t |jƒ ƒrÊˆ|||ƒ}n
ˆ|d ƒ}|||< qnW qW |S )Nr   r   )r   Ú
startswithr‘   Úzipr—   Ústrip)	r’   ÚcommentsÚ
convertersr“   r”   Újr˜   r¯   r�   )Ú	checkrowsÚ
converterdr´   r¢   ÚnamesrŸ   r   r   Úget_converters	  s,    



z _csv2rec.<locals>.get_convertersz~!@#$%^&*()-=+~\|}[]{';: /?.>,<ú"rh   c                s   g | ]}|ˆ kr|‘qS r   r   )Ú.0Úc)Údeleter   r   ú
<listcomp>8  s    z_csv2rec.<locals>.<listcomp>zcolumn%dz_%dc             S   s   g | ]}|j ƒ ‘qS r   )r»   )rÄ   rB   r   r   r   rÇ   F  s    rz   z)Could not find any valid data in CSV filec             S   s   g | ]\}}}|||ƒ‘qS r   r   )rÄ   r�   r˜   r™   r   r   r   rÇ   f  s   c                s   g | ]\}}ˆ ||ƒ‘qS r   r   )rÄ   r˜   r™   )rœ   r   r   rÇ   h  s   )rÁ   Úmask)rÁ   r;   )'ÚdictÚdateutil.parserÚdatetimers   Úto_filehandler)   Úcsvr’   ÚparserÚparser4   r   Únanr>   r«   r   r¹   ÚsetÚaddr‘   r»   ÚlowerÚreplacerƒ   r—   Úappendr(   r„   r   r€   r‡   Úextendrº   r   ÚanyÚmaZmrecordsÚfromrecordsÚrec)Úfnamer¼   r•   r¿   r�   rÀ   rÁ   rš   r›   Zuse_mrecordsr£   r¤   ÚdateutilrË   r�   r’   r–   ZitemdrÂ   Z
needheaderr”   ÚheadersÚseenr“   r¯   Úcntr½   ÚrowsÚrowmasksÚrr   )r¿   rÀ   r¦   r£   rÆ   r|   r´   rœ   rš   r›   r¢   r¬   r§   r±   r²   r³   rÁ   r•   rŸ   r¤   r   Ú_csv2rec^  s°    7














rã   c               @   s:   e Zd ZdZddd„Zdd„ Zdd„ ZeZd	d
„ ZeZ	dS )ÚGaussianKDEa‰  
    Representation of a kernel-density estimate using Gaussian kernels.

    Parameters
    ----------
    dataset : array_like
        Datapoints to estimate from. In case of univariate data this is a 1-D
        array, otherwise a 2-D array with shape (# of dims, # of data).

    bw_method : str, scalar or callable, optional
        The method used to calculate the estimator bandwidth.  This can be
        'scott', 'silverman', a scalar constant or a callable.  If a
        scalar, this will be used directly as `kde.factor`.  If a
        callable, it should take a `GaussianKDE` instance as only
        parameter and return a scalar. If None (default), 'scott' is used.

    Attributes
    ----------
    dataset : ndarray
        The dataset with which `gaussian_kde` was initialized.

    dim : int
        Number of dimensions.

    num_dp : int
        Number of datapoints.

    factor : float
        The bandwidth factor, obtained from `kde.covariance_factor`, with which
        the covariance matrix is multiplied.

    covariance : ndarray
        The covariance matrix of `dataset`, scaled by the calculated bandwidth
        (`kde.factor`).

    inv_cov : ndarray
        The inverse of `covariance`.

    Methods
    -------
    kde.evaluate(points) : ndarray
        Evaluate the estimated pdf on a provided set of points.

    kde(points) : ndarray
        Same as kde.evaluate(points)

    Nc                sV  t j|ƒˆ_t jˆjƒjdks&tdƒ‚t jˆjƒj\ˆ_ˆ_t	ˆ t
ƒ}ˆ d krPnx|rfˆ dkrfˆjˆ_nb|r|ˆ dkr|ˆjˆ_nLt jˆ ƒr¢| r¢dˆ_‡ fdd„ˆ_n&tˆ ƒrÀˆ ˆ_‡fdd„ˆ_ntd	ƒ‚ˆjƒ ˆ_tˆd
ƒ�st jt jˆjddd�ƒˆ_t jjˆjƒˆ_ˆjˆjd  ˆ_ˆjˆjd  ˆ_t jt jjdt j ˆj ƒƒˆj ˆ_d S )Nr   z.`dataset` input should have multiple elements.ÚscottZ	silvermanzuse constantc                  s   ˆ S )Nr   r   )Ú	bw_methodr   r   Ú<lambda>º  s    z&GaussianKDE.__init__.<locals>.<lambda>c                  s
   ˆ j ˆ ƒS )N)Ú
_bw_methodr   )r}   r   r   rç   ½  s    zB`bw_method` should be 'scott', 'silverman', a scalar or a callableZ_data_inv_covF)Úrowvarr0   r   )r   rF   Údatasetr1   r3   r   r   ÚdimÚnum_dpr(   r)   Úscotts_factorÚcovariance_factorÚsilverman_factorÚisscalarrè   r*   ÚfactorÚhasattrr5   Zdata_covarianceÚlinalgÚinvZdata_inv_covZ
covarianceÚinv_covÚsqrtÚdetÚpiÚnorm_factor)r}   rê   ræ   ZisStringr   )ræ   r}   r   r~   ª  s>    



zGaussianKDE.__init__c             C   s   t j| jd| jd  ƒS )Ng      ð?é   g      ð¿)r   Úpowerrì   rë   )r}   r   r   r   rí   Õ  s    zGaussianKDE.scotts_factorc             C   s&   t j| j| jd  d d| jd  ƒS )Ng       @g      @g      ð?rú   g      ð¿)r   rû   rì   rë   )r}   r   r   r   rï   Ø  s    zGaussianKDE.silverman_factorc       	      C   s&  t j|ƒ}t j|ƒj\}}|| jkr6tdj|| jƒƒ‚t j|ƒ}|| jkr®xÌt	| jƒD ]R}| j
dd…|t jf | }t j| j|ƒ}t j|| dd�d }|t j| ƒ }qVW njxht	|ƒD ]\}| j
|dd…|t jf  }t j| j|ƒ}t j|| dd�d }t jt j| ƒdd�||< q¸W || j }|S )a  Evaluate the estimated pdf on a set of points.

        Parameters
        ----------
        points : (# of dimensions, # of points)-array
            Alternatively, a (# of dimensions,) vector can be passed in and
            treated as a single point.

        Returns
        -------
        values : (# of points,)-array
            The values at each point.

        Raises
        ------
        ValueError : if the dimensionality of the input points is different
                     than the dimensionality of the KDE.

        z2points have dimension {}, dataset has dimension {}Nr   )r   g       @)r   rF   r1   r   rë   r   ÚformatÚzerosrì   Úrangerê   r<   Údotrõ   rV   Úexprù   )	r}   Úpointsrë   Znum_mra   r“   ÚdiffZtdiffÚenergyr   r   r   Úevaluateß  s&    




zGaussianKDE.evaluate)N)
r‹   rŒ   r�   rŽ   r~   rí   rï   rî   r  Ú__call__r   r   r   r   rä   v  s   /
+0rä   )r   N)NN)r   )N)N)Nr   )r   )
NNNNNNNNNN)NNNN)NNNNNNNN)NNNNNNNN)NNNN)NNNN)NNNN)NNNN)	NNNNNNNNN)ry   r   r   rz   NNr{   NFFF)&rŽ   rÍ   ÚinspectÚnumpyr   Úmatplotlib.cbookrs   Ú
matplotlibr   r	   r
   r   r$   Ú
deprecatedr.   r%   r'   r&   rE   r   re   ri   ÚinterpdÚupdateÚcleandocÚdedent_interpdrI   rk   rn   ro   rp   rq   ru   rv   rx   rã   Úobjecträ   r   r   r   r   Ú<module>6   sx   

8
:

&
D
7  
  



	

 
 7 > & ( & &  X0  
  