rL iv dZddlZddlmZddlZddlmZmZm Z dZ dZ d$dZ d%dZ d%d Zd Z d&d Z d'd Zej$j'd ddej$ d(dZej$ d(dZdZej.edZej2d)ddiej$j4e_ej.edZej2d)ddiej$j4e_ej.edZej2d)ddiej$j4e_ej.edZej2d)ddiej$j4e_ej$ d*dZej$ddee ddd dfd!ZGd"d#Z y)+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. N)Number)_api _docstringcbookcDtjt||zS)z Return *x* times the Hanning (or Hann) window of len(*x*). See Also -------- window_none : Another window algorithm. )nphanninglenxs U/mnt/ssd/data/python-lab/Trading/venv/lib/python3.12/site-packages/matplotlib/mlab.pywindow_hanningr:s ::c!f a c|S)zz No window function; simply return *x*. See Also -------- window_hanning : Another window algorithm. r s r window_nonerEs  Hrc||dvrt|t|S|dk(rt|t|S|dk(rt|t|St |rmt j |}|!|dz|jkDrtd|d||jdk(s|s|jdk(r||S ||| Std |d #t$rt j||| cYSwxYw) 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. )constantmeandefault)keyaxislinearnonezaxis(=z) out of boundsrr)rarrzUnknown value for key: zH, must be one of: 'default', 'constant', 'mean', 'linear', or a function) detrend detrend_meandetrend_linear detrend_nonecallablerasarrayndim ValueError TypeErrorapply_along_axis)r rrs r rrPs2 {c<<ql66 qn488 ql66 # JJqM  q166 1vdV?;< < LQVVq[$166Q;q6M >qt$ $%cW-: ;< < >&&s1= = >s5 C!C21C2ctj|}| |dz|jkDrtd|z||j |dz 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. rzaxis(=%s) out of boundsT)keepdims)rr#r$r%rr rs r rrsN( 1 A DFQVVO2T9:: qvvdTv* **rc|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. rr*s r r!r!s & Hrctj|}|jdkDr td|js!tjd|j Stj |jt}tj||d}|d|dz }|j||jzz }|||z|zz 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. rzy cannot have ndim > 1g)dtype)bias)rr)rr) rr#r$r%arrayr-arangesizefloatcovr)yr Cbas r r r s 1 Avvz122 66xx!''** !&&&A q!!A $$A 1QVVX:A !a=rc r |d} n||u} |d}|d}|t}|t}|d}||k\r td| | dk(rd} tjgd | | s| dk7r td t j |}| st j |}||dk(rt j|rd }nd }tjgd|t||kr&t|} t j||}d|| d| s4t||kr&t|} t j||}d|| d||}| dk7rd} n| d} |d k(r|} |dzr |dz dzdz}n|dz}d}n|d k(r|dzr |dzdz} n|dzdz} d}t j|s&|t j||j}t||k7r tdt jjj||ddd||z j }t#||d}||j%dz}t j&j'||dd ddf}t j&j)|d|z d| }| st jjj||ddd||z j }t#||d}||j%dz}t j&j'||dd| ddf}t j*||z}n| dk(rt j*||z}nd| dk(r't j,||j/z }n8| dk(s| dk(rt j0|}n| dk(r||j/z}| dk(ra|dzst3ddd}n t3ddd}||xxzcc<| r||z}||dzj/z}n||j/dzz}t j4|dz t||dz z dz||z |z }|d k(r3t j6| d}t j6|| d}n|dzs |dxxdzcc<| dk(rt j8|d}|||fS)z Private helper implementing the common parts between the psd, csd, spectrogram and complex, magnitude, angle, and phase spectrums. NTrznoverlap must be less than NFFTrpsd)rr;complex magnitudeanglephasemodez*x and y must be equal if mode is not 'psd'twosidedonesided)rrCrB)sidesFrg?@z7The window length must match the data's first dimensionr)r)nrr=r>r?r<rF)r!rr%r check_in_listrr# iscomplexobjr resizeiterableonesr-lib stride_trickssliding_window_viewTrreshapefftfftfreqconjabssumr>slicer0rollunwrap)r r4NFFTFs detrend_funcwindownoverlappad_torD scale_by_freqrA same_datarGnumFreqs freqcenterscaling_factorresultfreqsresultYslcts r _spectral_helperrjs y F  z #  ~ |4:;; |ty(D  EFF 1 A  JJqM }* ??1 EE:%H 1v} F IIa !" Q$ F IIa !" ~ u}     A: 1*q1,JJ *  A: QHqy1}H ;;v agg./ 6{d EG GVV ! ! 5 5 4a6*4(?*,,-A V\ 2F fnnW- -F VVZZ&qZ 1)8)Q, ?F FFNN61R4 (( 3E &&&&:: t!;.th.001 'r?r@NrF r r4rZr[r\r]r^r_rDr`rAr<r9r)rrHr rjr!realr$shape) rAr r[r]r_rDspecrf_s r _single_spectrum_helperrqxs  AM ~Q%TA23?/0,149+/ 1ND%  yyy yyA~$**Q-1,AqDz ;raLFs : 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.apad_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).afpad_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.)SpectralSingle_SpectrumPSDc Nt|d|||||||| \} } | j| fS)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 r4rZr[rr]r^r_rDr`)csdrm) r rZr[rr]r^r_rDr`Pxxrfs r r;r;s9dqDtG"Xf ?JC 88U?rc |d}t|||||||||| d \} } } | jdk(r1| jddkDr| jd} | | fS| dddf} | | fS) 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``. Nr:r;rlr9rrr)rjr$rnr) r r4rZr[rr]r^r_rDr`Pxyrfrps r rvrvs` |$qADR29&.6v+0 */ 1MC  xx1} 99Qz8angle of the frequency spectrum (wrapped phase spectrum)r?z:phase of the frequency spectrum (unwrapped phase spectrum)c |d}|d}t||kr%tjd|dt|dt|d|||||||||  \} } } | dk7r | j} | | | fS) 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'. Nr:z6Only one segment is calculated since parameter NFFT (=z) >= signal length (=z).rlr<)r r warn_externalrjrm) r rZr[rr]r^r_rDr`rArorfris r specgramr~}s| | 1v~ %%)F*?AxrK L&T3:6/7,14A+/ 1ND% yyy >rr:r9rc t|d|zkr tdt||||||||| \} } t||||||||| \} } t|||||||||| \} } t j | dz| | zz }|| fS)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}`. r9zvCoherence is calculated by averaging over *NFFT* length segments. Your signal is too short for your choice of *NFFT*.)r r%r;rvrrU)r r4rZr[rr]r^r_rDr`rwfPyyryCxys r coherersH 1vD MN ND"gvx FC D"gvx FC AtR&(FE FC &&+ cCi (C 6Mrc2eZdZdZddZdZdZeZdZeZ y) GaussianKDEa6 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 : {'scott', 'silverman'} or float or callable, optional The method used to calculate the estimator bandwidth. If a float, this will be used directly as `kde.factor`. If a callable, it should take a `GaussianKDE` instance as only parameter and return a float. 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) Nctj|_tjjjdkDs t dtjjj \__ntjdrj_ nrtjdrj_ nJttrd_fd_ n(t#r_fd_ n t dj_t'd shtjtj(jdd _tj,j/j*_j*j$d zz_j0j$d zz _tj6tj,j9d tj:zj2zjz_y) Nrz.`dataset` input should have multiple elements.scott silvermanz use constantcSNr) bw_methodsr z&GaussianKDE.__init__..<sYrc&jSr) _bw_methodselfsr rz&GaussianKDE.__init__..?sT__T-BrzB`bw_method` should be 'scott', 'silverman', a scalar or a callable _data_inv_covF)rowvarr.r9)r atleast_2ddatasetr/r1r%rndimnum_dpr _str_equal scotts_factorcovariance_factorsilverman_factor isinstancerrr"factorhasattrr3data_covariancelinalginv data_inv_cov covarianceinv_covsqrtdetpi norm_factor)rrrs` `r __init__zGaussianKDE.__init__-s}}W- xx %**Q.MN N " 6 < <$+      i 1%)%7%7D "   i 5%)%:%:D "  6 *,DO%6D " i 'DO%BD "45 5 ,,. t_-#%==LL $!D !# d.B.B CD ..1AA((4;;!+;; GGBIIMM!bee)doo2M$NO"kk*rcbtj|jd|jdzz S)Nrpowerrrrs r rzGaussianKDE.scotts_factorVs$xx SDHHqL%9::rctj|j|jdzzdz d|jdzz S)NrEg@rrrrs r rzGaussianKDE.silverman_factorYs=xx KK488c> *S 0#A2FH Hrctj|}tj|j\}}||jk7rt d|d|jtj |}||jk\rt|jD]}}|jdd|tjf|z }tj|j|}tj||zddz }|tj| z}nt|D]}|j|dd|tjfz }tj|j|}tj||zddz }tjtj| d||<||jz }|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. zpoints have dimension z, dataset has dimension NrrrE)rrr/rnrr%zerosrrangernewaxisdotrrVexpr) rpointsrnum_mreidifftdiffenergys r evaluatezGaussianKDE.evaluate`s*v&XXf%++ U $((?5cU;**.((56 6% DKK 4;;' 2||Aq"**$45>t||T2u 15;"&&&/1  25\ <||fQ2::-=&>>t||T2u 15;FF2666'?;q  < $*** rr) __name__ __module__ __qualname____doc__rrrrr__call__rrr rrs.%T'+R;H &/bHrr)NNr) NNNNNNNNNN)NNNN)NNNNNNNNr) NNNNNNNNN)!r functoolsnumbersrnumpyr matplotlibrrrrrrrr!r rjrqinterpdregisterr;rv_single_spectrum_docspartialcomplex_spectrumformatparamsmagnitude_spectrumangle_spectrumphase_spectrumr~rrrrr rsX/b..  .`H;?6 >"B 77t 48>B44n 7;>B<<~#L%9$$% L9299! C!!#""#:GD5.55! G!!#""#:GD5.55! I!!  9=CGOOd and)4..bOOr