a
    Sic                  
   @   s  d Z ddlZddlmZ ddlZddlmZmZm	Z	 dd Z
dd Zd5d	d
Zd6ddZd7ddZdd Zedd8ddZd9ddZd:ddZd;ddZejjdddd ejd<ddZejd=d d!Zd"Zeed#Zejf d$d%iejje_ eed&Zejf d$d'iejje_ eed(Z ejf d$d)iejje _ eed*Z!ejf d$d+iejje!_ ejd>d,d-Z"ejd.d/ee
ddd0dfd1d2Z#G d3d4 d4Z$dS )?a  
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 and kernel density estimations.

.. _NumPy: https://numpy.org
.. _SciPy: https://www.scipy.org

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
    N)Number)_api
_docstringcbookc                 C   s   t t| |  S )z
    Return *x* times the Hanning (or Hann) window of len(*x*).

    See Also
    --------
    window_none : Another window algorithm.
    )nphanninglenx r   K/var/www/html/django/DPS/env/lib/python3.9/site-packages/matplotlib/mlab.pywindow_hanning=   s    r   c                 C   s   | S )zz
    No window function; simply return *x*.

    See Also
    --------
    window_hanning : Another window algorithm.
    r   r	   r   r   r   window_noneH   s    r   c                 C   s   |du s|dv rt | t|dS |dkr4t | t|dS |dkrJt | t|dS t|rt| } |dur|d | jkrtd| d|du r| jd	ks|s| jdkr|| S z|| |d
W S  t	y   tj
||| d Y S 0 ntd|ddS )al  
    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
        The detrending algorithm to use. 'default', 'mean', and 'constant' are
        the same as `detrend_mean`. '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 : int
        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)keyaxislinearnone   zaxis(=z) out of boundsr   r   )r   arrzUnknown value for key: zH, must be one of: 'default', 'constant', 'mean', 'linear', or a function)detrenddetrend_meandetrend_lineardetrend_nonecallabler   asarrayndim
ValueError	TypeErrorapply_along_axis)r
   r   r   r   r   r   r   S   s&    
 
r   c                 C   s>   t | } |du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 : int
        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    
r   c                 C   s   | S )a  
    Return *x*: no detrending.

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

    axis : int
        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      s    r   c                 C   s   t | } | jdkrtd| js2t jd| jdS t j| jtd}t j	|| dd}|d |d  }| 
 ||
   }| || |  S )ab  
    Return *x* minus best fit line; 'linear' detrending.

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

    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        )dtype)bias)r   r   )r   r   )r   r   r   r    arrayr%   arangesizefloatcovr   )yr
   Cbar   r   r   r      s    

r   z3.6c                 C   s0   |du rd}t | dkr"tdt| |||S )al  
    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 : int
        The number of data points in each window.
    noverlap : int, default: 0 (no overlap)
        The overlap between adjacent windows.
    axis : int
        The axis along which the windows will run.

    References
    ----------
    `stackoverflow: Rolling window for 1D arrays in Numpy?
    <https://stackoverflow.com/a/6811241>`_
    `stackoverflow: Using strides for an efficient moving average filter
    <https://stackoverflow.com/a/4947453>`_
    Nr   r   z%only 1-dimensional arrays can be used)r   r   r    _stride_windows)r
   nnoverlapr   r   r   r   stride_windows   s
    r3   c                 C   sH  t tjjdrJ|dkrJ||kr&tdtjjj| |ddd d ||  jS ||krZtd|dk rjtdt| } |dkr|dkr|dkr| tj S | tj jS || j	krt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 )
Nsliding_window_viewr   znoverlap must be less than nr   r   zn cannot be less than 1z(n cannot be greater than the length of x)shapestrides)hasattrr   libstride_tricksr    r4   Tr   newaxisr)   intr6   r7   
as_strided)r
   r1   r2   r   stepr6   r7   r   r   r   r0      s8    



r0   c                 C   sT  |du rd}n|| u }|du r"d}|du r.d}|du r:t }|du rFt}|du rRd}|
du sb|
dkrfd}
tjg d|
d	 |s|
dkrtd
t| } |st|}|du s|dkrt| rd}nd}tjg d|d t| |k rt| }t	| |} d| |d< |s<t||k r<t|}t	||}d||d< |du rJ|}|
dkrZd}	n|	du rhd}	|dkr|}|d r|d d d }n|d }d}n2|dkr|d r|d d }n|d d }d}t
|s|t|| j}t||krtdt| ||}t||dd}||d }tjj||ddd|ddf }tj|d| d| }|st|||}t||dd}||d }tjj||ddd|ddf }t|| }nz|
dkrt|| }n`|
dkrt|t|  }n<|
dks|
dkr(t|}n|
dkrD|t|  }|
dkr|d sftddd}ntddd}||  |9  < |	r|| }|t|d   }n|t| d  }t|d t| |d  d || | }|dkrtj|| dd}tj|| dd}n|d s2|d  d9  < |
dkrJtj|dd}|||fS )z
    Private helper implementing the common parts between the psd, csd,
    spectrogram and complex, magnitude, angle, and phase spectrums.
    NT   r      r   psd)r   rB   complex	magnitudeanglephasemodez*x and y must be equal if mode is not 'psd'twosidedonesided)r   rJ   rI   )sidesFr   g      ?       @z7The window length must match the data's first dimensionr   )r5   r   )r1   r   rD   rE   rF   rC   r5   )r   r   r   check_in_listr    r   r   iscomplexobjr   resizeiterableonesr%   r0   r   reshapefftfftfreqconjabssumrE   slicer(   rollunwrap)r
   r,   NFFTFsdetrend_funcwindowr2   pad_torK   scale_by_freqrH   Z	same_datar1   ZnumFreqsZ
freqcenterZscaling_factorresultfreqsZresultYslctr   r   r   _spectral_helper#  s    









""




*


re   c           	      C   s   t jg d| d |du r"t|}t|dt||t|d||d| d\}}}| dkrX|j}|jdkr|jd	 d	kr|dddf }||fS )
zu
    Private helper implementing the commonality between the complex, magnitude,
    angle, and phase spectrums.
    )rC   rD   rE   rF   rG   Nr   Fr
   r,   r[   r\   r]   r^   r2   r_   rK   r`   rH   rC   r@   r   )r   rM   r   re   r   realr   r6   )	rH   r
   r\   r^   r_   rK   specrb   _r   r   r   _single_spectrum_helper  s    rj   aL  Fs : float, default: 2
    The sampling frequency (samples per time unit).  It is used to calculate
    the Fourier frequencies, *freqs*, in cycles per time unit.

window : callable or ndarray, default: `.window_hanning`
    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.  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'}, optional
    Which sides of the spectrum to return. 'default' is one-sided for real
    data and two-sided for complex data. 'onesided' forces the return of a
    one-sided spectrum, while 'twosided' forces two-sided.a  pad_to : int, optional
    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 `~numpy.fft.fft`.  The default is None, which sets *pad_to*
    equal to the length of the input signal (i.e. no padding).af  pad_to : int, optional
    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 `~numpy.fft.fft`. The default is None,
    which sets *pad_to* equal to *NFFT*

NFFT : int, default: 256
    The number of data points used in each block for the FFT.  A power 2 is
    most efficient.  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 it is 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, default: True
    Whether the resulting density values should be scaled by the scaling
    frequency, which gives density in units of 1/Hz.  This allows for
    integration over the returned frequency values.  The default is True for
    MATLAB compatibility.)SpectralZSingle_SpectrumZ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 : int, default: 0 (no overlap)
        The number of points of overlap between segments.

    Returns
    -------
    Pxx : 1-D array
        The values for the power spectrum :math:`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
   r,   r[   r\   r   r^   r2   r_   rK   r`   )csdrg   )r
   r[   r\   r   r^   r2   r_   rK   r`   Pxxrb   r   r   r   rB     s
    2
rB   c
                 C   sn   |du 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 : int, default: 0 (no overlap)
        The number of points of overlap between segments.

    Returns
    -------
    Pxy : 1-D array
        The values for the cross spectrum :math:`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``.
    NrA   rB   rf   r@   r   r   r   )re   r   r6   r   )r
   r,   r[   r\   r   r^   r2   r_   rK   r`   Pxyrb   ri   r   r   r   rl   N  s    0

rl   a9  Compute the {quantity} 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}

{Single_Spectrum}

Returns
-------
spectrum : 1-D array
    The {quantity}.
freqs : 1-D array
    The frequencies corresponding to the elements in *spectrum*.

See Also
--------
psd
    Returns the power spectral density.
complex_spectrum
    Returns the complex-valued frequency spectrum.
magnitude_spectrum
    Returns the absolute value of the `complex_spectrum`.
angle_spectrum
    Returns the angle of the `complex_spectrum`.
phase_spectrum
    Returns the phase (unwrapped angle) of the `complex_spectrum`.
specgram
    Can return the complex spectrum of segments within the signal.
rC   quantityz!complex-valued frequency spectrumrD   z4magnitude (absolute value) of the frequency spectrumrE   z8angle of the frequency spectrum (wrapped phase spectrum)rF   z:phase of the frequency spectrum (unwrapped phase spectrum)c
                 C   s|   |du rd}|du rd}t | |kr@td| dt |  d t| d|||||||||	d\}
}}|	dkrr|
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, default: 128
        The number of points of overlap between blocks.
    mode : str, default: 'psd'
        What sort of spectrum to use:
            '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
        2D 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   rA   z6Only one segment is calculated since parameter NFFT (=z) >= signal length (=z).rf   rC   )r   r   warn_externalre   rg   )r
   r[   r\   r   r^   r2   r_   rK   r`   rH   rh   rb   rd   r   r   r   specgram  s(    >

rr   rA   r@   r   c
                 C   s   t | d| k rtdt| ||||||||		\}
}t|||||||||		\}}t| |||||||||	
\}}t|d |
|  }||fS )a  
    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 : int, default: 0 (no overlap)
        The number of points of overlap between segments.

    Returns
    -------
    Cxy : 1-D array
        The coherence vector.
    freqs : 1-D array
            The frequencies for the elements in *Cxy*.

    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@   zvCoherence is calculated by averaging over *NFFT* length segments.  Your signal is too short for your choice of *NFFT*.)r   r    rB   rl   r   rV   )r
   r,   r[   r\   r   r^   r2   r_   rK   r`   rm   fZPyyrn   ZCxyr   r   r   cohere  s    $rt   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 )GaussianKDEap  
    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 2D 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 passed to the constructor.
    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                    sD  t |_t jjdks&tdt jj\__ d u rFnrt	
 dr\j_n\t	
 drrj_nFt trd_ fdd_n&t r _fdd_ntd	 _td
st t jjddd_t jj_jjd  _jjd  _t t 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>      z&GaussianKDE.__init__.<locals>.<lambda>c                      s
      S rw   )
_bw_methodr   selfr   r   ry     rz   zB`bw_method` should be 'scott', 'silverman', a scalar or a callableZ_data_inv_covF)rowvarr&   r@   )r   
atleast_2ddatasetr'   r)   r    r6   dimnum_dpr   
_str_equalscotts_factorcovariance_factorsilverman_factor
isinstancer   r{   r   factorr8   r+   Zdata_covariancelinalginvZdata_inv_cov
covarianceinv_covsqrtdetpinorm_factor)r}   r   rx   r   )rx   r}   r   __init__w  s@    




zGaussianKDE.__init__c                 C   s   t | jd| jd  S )N         r   powerr   r   r|   r   r   r   r     s    zGaussianKDE.scotts_factorc                 C   s&   t | j| jd  d d| jd  S )NrL   g      @r   r   r   r|   r   r   r   r     s    zGaussianKDE.silverman_factorc           	      C   s  t |}t |j\}}|| jkr6td|| jt |}|| jkrt	| jD ]R}| j
dd|t jf | }t | j|}t j|| ddd }|t |  }qTnft	|D ]\}| j
|dd|t jf  }t | j|}t j|| ddd }t jt | dd||< q|| 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
        -------
        (# 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   rL   )r   r   r'   r6   r   r    formatzerosr   ranger   r<   dotr   rW   expr   )	r}   pointsr   Znum_mra   idiffZtdiffenergyr   r   r   evaluate  s(    




zGaussianKDE.evaluate)N)
__name__
__module____qualname____doc__r   r   r   r   r   __call__r   r   r   r   ru   K  s   +
)1ru   )NN)N)N)Nr   )r   r   )
NNNNNNNNNN)NNNN)NNNNNNNN)NNNNNNNN)	NNNNNNNNN)%r   	functoolsnumbersr   numpyr   
matplotlibr   r   r   r   r   r   r   r   r   
deprecatedr3   r0   re   rj   interpdupdatededent_interpdrB   rl   Z_single_spectrum_docspartialZcomplex_spectrumr   paramsmagnitude_spectrumangle_spectrumphase_spectrumrr   rt   ru   r   r   r   r   <module>   s   4
1

"$
&   
   
	:  7  ?&   R1