
    >h9M                        S r SSKrSSKJrJr  SSKJr  SSKJ	r	  SSK
JrJr  SSKJr  SS	KJrJrJr  SS
KJr  \" \R,                  \R.                  \R0                  \R2                  \R4                  \R6                  \R8                  \R:                  \R<                  S9	rS r  " S S5      r!SSSSS\RD                  * \RD                  4SS4S jr#SSSSS\RD                  * \RD                  4SS4S jr$g)aa  
Univariate Kernel Density Estimators

References
----------
Racine, Jeff. (2008) "Nonparametric Econometrics: A Primer," Foundation and
    Trends in Econometrics: Vol 3: No 1, pp1-88.
    http://dx.doi.org/10.1561/0800000009

https://en.wikipedia.org/wiki/Kernel_%28statistics%29

Silverman, B.W.  Density Estimation for Statistics and Data Analysis.
    N)	integratestats)kernels)cache_readonly)
array_like
float_like   )
bandwidths)forrtrevrtsilverman_transform)fast_linbin)	gauepaunitribiwtriwcoscos2tricc                 P     U R                     g ! [         a    [        S5      ef = f)Nz!Call fit to fit the density first)density	Exception
ValueErrorselfs    pC:\Users\julio\OneDrive\Documentos\Trabajo\Ideas Frescas\venv\Lib\site-packages\statsmodels/nonparametric/kde.py_checkisfitr   (   s)    > ><==>s    %c            	           \ rS rSrSrS rSSSSSSS	\R                  * \R                  44S
 jr\	S 5       r
\	S 5       r\	S 5       r\	S 5       r\	S 5       rS rSrg)KDEUnivariate0   aa  
Univariate Kernel Density Estimator.

Parameters
----------
endog : array_like
    The variable for which the density estimate is desired.

Notes
-----
If cdf, sf, cumhazard, or entropy are computed, they are computed based on
the definition of the kernel rather than the FFT approximation, even if
the density is fit with FFT = True.

`KDEUnivariate` is much faster than `KDEMultivariate`, due to its FFT-based
implementation.  It should be preferred for univariate, continuous data.
`KDEMultivariate` also supports mixed data.

See Also
--------
KDEMultivariate
kdensity, kdensityfft

Examples
--------
>>> import statsmodels.api as sm
>>> import matplotlib.pyplot as plt

>>> nobs = 300
>>> np.random.seed(1234)  # Seed random generator
>>> dens = sm.nonparametric.KDEUnivariate(np.random.normal(size=nobs))
>>> dens.fit()
>>> plt.plot(dens.cdf)
>>> plt.show()
c                 &    [        USSSS9U l        g )Nendogr	   T)ndim
contiguous)r   r$   )r   r$   s     r   __init__KDEUnivariate.__init__U   s    wQ4H
    r   normal_referenceTNr	      c	                    [        U[        5      (       a  X l        O#SU l        [        U5      (       d  [	        US5      nU R
                  n	U(       a7  US:w  a  Sn
[        U
5      eUb  Sn
[        U
5      e[        U	UUUUUUUS9u  pnO[        U	UUUUUUUS9u  pnXl	        Xl
        X l        [        U   " US9U l        X@R                  l        Ub-  U R                  =R                  UR                  5       -  sl        0 U l        U $ )a  
Attach the density estimate to the KDEUnivariate class.

Parameters
----------
kernel : str
    The Kernel to be used. Choices are:

    - "biw" for biweight
    - "cos" for cosine
    - "epa" for Epanechnikov
    - "gau" for Gaussian.
    - "tri" for triangular
    - "triw" for triweight
    - "uni" for uniform

bw : str, float, callable
    The bandwidth to use. Choices are:

    - "scott" - 1.059 * A * nobs ** (-1/5.), where A is
      `min(std(x),IQR/1.34)`
    - "silverman" - .9 * A * nobs ** (-1/5.), where A is
      `min(std(x),IQR/1.34)`
    - "normal_reference" - C * A * nobs ** (-1/5.), where C is
      calculated from the kernel. Equivalent (up to 2 dp) to the
      "scott" bandwidth for gaussian kernels. See bandwidths.py
    - If a float is given, its value is used as the bandwidth.
    - If a callable is given, it's return value is used.
      The callable should take exactly two parameters, i.e.,
      fn(x, kern), and return a float, where:

      * x - the clipped input data
      * kern - the kernel instance used

fft : bool
    Whether or not to use FFT. FFT implementation is more
    computationally efficient. However, only the Gaussian kernel
    is implemented. If FFT is False, then a 'nobs' x 'gridsize'
    intermediate array is created.
gridsize : int
    If gridsize is None, max(len(x), 50) is used.
cut : float
    Defines the length of the grid past the lowest and highest values
    of x so that the kernel goes to zero. The end points are
    ``min(x) - cut * adjust * bw`` and ``max(x) + cut * adjust * bw``.
adjust : float
    An adjustment factor for the bw. Bandwidth becomes bw * adjust.

Returns
-------
KDEUnivariate
    The instance fit,
z
user-givenbwr   z)Only gaussian kernel is available for fftz#Weights are not implemented for fft)kernelr-   adjustweightsgridsizeclipcut)h)
isinstancestr	bw_methodcallabler   r$   NotImplementedErrorkdensityfftkdensityr   supportr-   kernel_switchr.   r0   sum_cache)r   r.   r-   fftr0   r1   r/   r3   r2   r$   msgr   grids                r   fitKDEUnivariate.fitX   s   @ b#N)DNB<<D)

A)#..";)#.. +!	!G2 !)!	!G2 #F+b1 &KK7;;=0r)   c           
        ^	 [        U 5        U R                  m	T	R                  c!  [        R                  * [        R                  p!OT	R                  u  pU	4S jnU R
                  n[        R                  X4   n[        U5      nU R                  n[        SU5       Vs/ s H$  n[        R                  " X4US-
     XG   US9S   PM&     nn[        R                  " U5      $ s  snf )z
Returns the cumulative distribution function evaluated at the support.

Notes
-----
Will not work if fit has not been called.
c                 N   > [         R                  " TR                  X5      5      $ )N)npsqueezer   )xskerns     r   funcKDEUnivariate.cdf.<locals>.func   s    ::dll1011r)   r	   argsr   )r   r.   domainrG   infr<   r_lenr$   ranger   quadcumsum)
r   abrL   r<   r1   r$   iprobsrK   s
            @r   cdfKDEUnivariate.cdf   s     	D{{;;FF7BFFq;;DA	2 ,,%%
#w<

 1h'
' NN4Q%HK' 	 
 yy	
s    +C#c                 Z    [        U 5        [        R                  " U R                  5      * $ )zn
Returns the hazard function evaluated at the support.

Notes
-----
Will not work if fit has not been called.
)r   rG   logsfr   s    r   	cumhazardKDEUnivariate.cumhazard   s!     	Dtwwr)   c                 6    [        U 5        SU R                  -
  $ )zp
Returns the survival function evaluated at the support.

Notes
-----
Will not work if fit has not been called.
r	   )r   r[   r   s    r   r_   KDEUnivariate.sf   s     	D488|r)   c                   ^ [        U 5        U4S jnU R                  mTR                  b  U R                  u  p#O [        R                  * [        R                  p2U R
                  n[        R                  " XX44S9S   * $ )z
Returns the differential entropy evaluated at the support

Notes
-----
Will not work if fit has not been called. 1e-12 is added to each
probability to ensure that log(0) is not called.
c                 ^   > TR                  X5      nU[        R                  " US-   5      -  $ )Ng-q=)r   rG   r^   )rI   rJ   pdfrK   s      r   entr#KDEUnivariate.entropy.<locals>.entr
  s)    ,,q$Ce,,,r)   rN   r   )r   r.   rP   rG   rQ   r$   r   rU   )r   rg   rW   rX   r$   rK   s        @r   entropyKDEUnivariate.entropy   si     	D	- {{;;";;DAqFF7BFFq

t9!<<<r)   c                     [        U 5        [        U R                  5      n[        R                  R                  U R                  [        R                  " SSU5      5      $ )z
Inverse Cumulative Distribution (Quantile) Function

Notes
-----
Will not work if fit has not been called. Uses
`scipy.stats.mstats.mquantiles`.
r   r	   )	r   rS   r   r   mstats
mquantilesr$   rG   linspace)r   r1   s     r   icdfKDEUnivariate.icdf  sB     	Dt||$||&&tzz2;;q!X3NOOr)   c                 d    [        U 5        U R                  R                  U R                  U5      $ )z
Evaluate density at a point or points.

Parameters
----------
point : {float, ndarray}
    Point(s) at which to evaluate the density.
)r   r.   r   r$   )r   points     r   evaluateKDEUnivariate.evaluate&  s'     	D{{""4::u55r)   )r?   r-   r7   r   r$   r.   r<   )__name__
__module____qualname____firstlineno____doc__r'   rG   rQ   rC   r   r[   r`   r_   ri   ro   rs   __static_attributes__ r)   r   r!   r!   0   s    "HI
 vvgrvvob    8 	  	  	 	 = =2 P P
6r)   r!   r   r*   r+   Tc	                 v   [         R                  " U 5      n U R                  S:X  a	  U SS2S4   n [         R                  " XS   :  XS   :  5      n	X	   n [	        U 5      n
Uc  [        U
S5      nUc  [         R                  " U
5      nU
nO][         R                  " U5      n[	        U5      [	        U	5      :w  a  Sn[        U5      eX9R                  5          nUR                  5       n[        U   " 5       n[        U5      (       a  [        U" X5      5      nO9[        U[        5      (       a  [        R                   " XU5      nO[#        US5      nX%-  n[         R$                  " U SS9Xr-  -
  n[         R
                  " U SS9Xr-  -   n[         R&                  " XU5      nU R(                  USS2S4   -
  U-  nUR+                  U5        UR,                  b(  UR,                  u  nnUU:  UU:  -  nU" U5      nSUU'   OU" U5      nSUUS:  '   [         R.                  " UU5      X-  -  nU(       a  UUU4$ UU4$ )a  
Rosenblatt-Parzen univariate kernel density estimator.

Parameters
----------
x : array_like
    The variable for which the density estimate is desired.
kernel : str
    The Kernel to be used. Choices are
    - "biw" for biweight
    - "cos" for cosine
    - "epa" for Epanechnikov
    - "gau" for Gaussian.
    - "tri" for triangular
    - "triw" for triweight
    - "uni" for uniform
bw : str, float, callable
    The bandwidth to use. Choices are:

    - "scott" - 1.059 * A * nobs ** (-1/5.), where A is
      `min(std(x),IQR/1.34)`
    - "silverman" - .9 * A * nobs ** (-1/5.), where A is
      `min(std(x),IQR/1.34)`
    - "normal_reference" - C * A * nobs ** (-1/5.), where C is
      calculated from the kernel. Equivalent (up to 2 dp) to the
      "scott" bandwidth for gaussian kernels. See bandwidths.py
    - If a float is given, its value is used as the bandwidth.
    - If a callable is given, it's return value is used.
      The callable should take exactly two parameters, i.e.,
      fn(x, kern), and return a float, where:

      * x - the clipped input data
      * kern - the kernel instance used

weights : array or None
    Optional  weights. If the x value is clipped, then this weight is
    also dropped.
gridsize : int
    If gridsize is None, max(len(x), 50) is used.
adjust : float
    An adjustment factor for the bw. Bandwidth becomes bw * adjust.
clip : tuple
    Observations in x that are outside of the range given by clip are
    dropped. The number of observations in x is then shortened.
cut : float
    Defines the length of the grid past the lowest and highest values of x
    so that the kernel goes to zero. The end points are
    -/+ cut*bw*{min(x) or max(x)}
retgrid : bool
    Whether or not to return the grid over which the density is estimated.

Returns
-------
density : ndarray
    The densities estimated at the grid points.
grid : ndarray, optional
    The grid points at which the density is estimated.

Notes
-----
Creates an intermediate (`gridsize` x `nobs`) array. Use FFT for a more
computationally efficient version.
r	   Nr   2   z:The length of the weights must be the same as the given x.r-   )axis)rG   asarrayr%   logical_andrS   maxonesr   rH   r>   r=   r8   floatr5   r6   r
   select_bandwidthr   minrn   TsethrP   dot)rI   r.   r-   r0   r1   r/   r2   r3   retgridclip_xnobsqrA   rK   rW   rX   rB   kz_loz_highdomain_maskdenss                         r   r;   r;   4  s   T 	

1Avv{agJ^^AQK!W5F		Aq6DtR= ''$- **W%w<3v;&NCS/!..*+KKM  "D||2a;	B		((5 D!LB
qqCH$A
qqCH$A;;qX&D 	
d1d7m
	A
 	IIbM 	{{f4xAJ/G+GAa!eH66!W(DT2~Rxr)   c	                 6   [         R                  " U 5      n U [         R                  " XS   :  XS   :  5         n [        U   " 5       n	[	        U5      (       a  [        U" X	5      5      nO9[        U[        5      (       a  [        R                  " XU	5      nO[        US5      nX%-  n[        U 5      n
Uc  [         R                  " U
S45      nS[         R                  " [         R                  " U5      5      -  n[         R                  " U 5      Xr-  -
  n[         R                  " U 5      Xr-  -   n[         R                   " X[#        U5      SS9u  pX-
  n[%        XX5      X-  -  n['        U5      n[)        X$U5      U-  n[+        U5      nU(       a  UX4$ UU4$ )a  
Rosenblatt-Parzen univariate kernel density estimator

Parameters
----------
x : array_like
    The variable for which the density estimate is desired.
kernel : str
    ONLY GAUSSIAN IS CURRENTLY IMPLEMENTED.
    "bi" for biweight
    "cos" for cosine
    "epa" for Epanechnikov, default
    "epa2" for alternative Epanechnikov
    "gau" for Gaussian.
    "par" for Parzen
    "rect" for rectangular
    "tri" for triangular
bw : str, float, callable
    The bandwidth to use. Choices are:

    - "scott" - 1.059 * A * nobs ** (-1/5.), where A is
      `min(std(x),IQR/1.34)`
    - "silverman" - .9 * A * nobs ** (-1/5.), where A is
      `min(std(x),IQR/1.34)`
    - "normal_reference" - C * A * nobs ** (-1/5.), where C is
      calculated from the kernel. Equivalent (up to 2 dp) to the
      "scott" bandwidth for gaussian kernels. See bandwidths.py
    - If a float is given, its value is used as the bandwidth.
    - If a callable is given, it's return value is used.
      The callable should take exactly two parameters, i.e.,
      fn(x, kern), and return a float, where:

      * x - the clipped input data
      * kern - the kernel instance used

weights : array or None
    WEIGHTS ARE NOT CURRENTLY IMPLEMENTED.
    Optional  weights. If the x value is clipped, then this weight is
    also dropped.
gridsize : int
    If gridsize is None, min(len(x), 512) is used. Note that the provided
    number is rounded up to the next highest power of 2.
adjust : float
    An adjustment factor for the bw. Bandwidth becomes bw * adjust.
    clip : tuple
    Observations in x that are outside of the range given by clip are
    dropped. The number of observations in x is then shortened.
cut : float
    Defines the length of the grid past the lowest and highest values of x
    so that the kernel goes to zero. The end points are
    -/+ cut*bw*{x.min() or x.max()}
retgrid : bool
    Whether or not to return the grid over which the density is estimated.

Returns
-------
density : ndarray
    The densities estimated at the grid points.
grid : ndarray, optional
    The grid points at which the density is estimated.

Notes
-----
Only the default kernel is implemented. Weights are not implemented yet.
This follows Silverman (1982) with changes suggested by Jones and Lotwick
(1984). However, the discretization step is replaced by linear binning
of Fan and Marron (1994). This should be extended to accept the parts
that are dependent only on the data to speed things up for
cross-validation.

References
----------
Fan, J. and J.S. Marron. (1994) `Fast implementations of nonparametric
    curve estimators`. Journal of Computational and Graphical Statistics.
    3.1, 35-56.
Jones, M.C. and H.W. Lotwick. (1984) `Remark AS R50: A Remark on Algorithm
    AS 176. Kernal Density Estimation Using the Fast Fourier Transform`.
    Journal of the Royal Statistical Society. Series C. 33.1, 120-2.
Silverman, B.W. (1982) `Algorithm AS 176. Kernel density estimation using
    the Fast Fourier Transform. Journal of the Royal Statistical Society.
    Series C. 31.2, 93-9.
r   r	   r-   g      @   T)retstep)rG   r   r   r=   r8   r   r5   r6   r
   r   r   rS   r   ceillog2r   rn   intr   r   r   r   )rI   r.   r-   r0   r1   r/   r2   r3   r   rK   r   rW   rX   rB   deltaRANGEbinnedyzstarfs                       r   r:   r:     sg   z 	

1A	"..!Waq'k
23A  "D||2a;	B		((5 D!LBq6D 664-(BGGBGGH-..H
q	CHA
q	CHA++aCM4@KDEE$ q+u|<F 	fA  e4q8E 	eA${"ur)   )%ry   numpyrG   scipyr   r   !statsmodels.sandbox.nonparametricr   statsmodels.tools.decoratorsr   statsmodels.tools.validationr   r    r
   kdetoolsr   r   r   linbinr   dictGaussianEpanechnikovUniform
TriangularBiweight	TriweightCosineCosine2Tricuber=   r   r!   rQ   r;   r:   r{   r)   r   <module>r      s     " 5 7 ?  7 7  					
>@6 @6L 66'266		Nf 66'266		]r)   