
    M/PhJ                     |   d Z ddlZddlmZmZ ddlmZ ddlm	Z	 ddl
mZmZ ddlmZ dd	lmZmZmZ dd
lmZ  eej        ej        ej        ej        ej        ej        ej        ej        ej        	  	        Zd Z  G d d          Z!dddddej"         ej"        fddfdZ#dddddej"         ej"        fddfdZ$dS )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    	 | j          d S # t          $ r t          d          w xY w)Nz!Call fit to fit the density first)density	Exception
ValueErrorselfs    ]/var/www/html/test/jupyter/venv/lib/python3.11/site-packages/statsmodels/nonparametric/kde.py_checkisfitr   (   s<    > > > ><===>s    %c            	           e Zd ZdZd Zdddddddej         ej        ffd	Zed
             Z	ed             Z
ed             Zed             Zed             Zd ZdS )KDEUnivariatea  
    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                 6    t          |ddd          | _        d S )Nendogr	   T)ndim
contiguous)r   r#   )r   r#   s     r   __init__zKDEUnivariate.__init__U   s    wQ4HHH


    r   normal_referenceTNr	      c	           
      8   t          |t                    r|| _        n&d| _        t          |          st	          |d          }| j        }	|rF|dk    rd}
t          |
          |d}
t          |
          t          |	|||||||          \  }}}nt          |	|||||||          \  }}}|| _	        || _
        || _        t          |         |          | _        || j        _        |'| j        xj        |                                z  c_        i | _        | S )	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 fftNz#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,   r.   sum_cache)r   r,   r+   fftr.   r/   r-   r1   r0   r#   msgr   grids                r   fitzKDEUnivariate.fitX   s\   @ b# 	*DNN)DNB<< *D))
 	A)#...";)#... +!	! 	! 	!GT22 !)!	! 	! 	!GT2 #F+b111 &K7;;==0r'   c                 \   t          |            | j        j        t          j         t          j        }}n
j        \  }}fd| j        t          j        |f         t                    }| j        fdt          d|          D             }t          j
        |          S )z
        Returns the cumulative distribution function evaluated at the support.

        Notes
        -----
        Will not work if fit has not been called.
        Nc                 T    t          j                            ||                     S )N)npsqueezer   )xskerns     r   funczKDEUnivariate.cdf.<locals>.func   s!    :dll1a00111r'   c                 j    g | ]/}t          j        |d z
           |                   d         0S )r	   argsr   )r   quad).0ir#   rI   r:   s     r   
<listcomp>z%KDEUnivariate.cdf.<locals>.<listcomp>   sM     
 
 
 N4Q%HHHK
 
 
r'   r	   )r   r,   domainrD   infr:   r_lenr#   rangecumsum)	r   abr/   probsr#   rI   rH   r:   s	        @@@@r   cdfzKDEUnivariate.cdf   s     	D{;F7BFqAA;DAq	2 	2 	2 	2 	2 ,%7
#w<<

 
 
 
 
 
1h''
 
 
 yr'   c                 T    t          |            t          j        | j                   S )z
        Returns the hazard function evaluated at the support.

        Notes
        -----
        Will not work if fit has not been called.
        )r   rD   logsfr   s    r   	cumhazardzKDEUnivariate.cumhazard   s%     	Dtwr'   c                 4    t          |            d| j        z
  S )z
        Returns the survival function evaluated at the support.

        Notes
        -----
        Will not work if fit has not been called.
        r	   )r   rZ   r   s    r   r]   zKDEUnivariate.sf   s     	D48|r'   c                     t          |            fd}| j        j        | j        \  }}nt          j         t          j        }}| j        }t          j        ||||f          d          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                 d                         ||           }|t          j        |dz             z  S )Ng-q=)r   rD   r\   )rF   rG   pdfrH   s      r   entrz#KDEUnivariate.entropy.<locals>.entr
  s/    ,,q!$$Ce,,,,r'   NrK   r   )r   r,   rQ   rD   rR   r#   r   rM   )r   rc   rW   rX   r#   rH   s        @r   entropyzKDEUnivariate.entropy   s     	D	- 	- 	- 	- 	- {;";DAqqF7BFqA
tQ999!<<<r'   c                     t          |            t          | j                  }t          j                            | j        t          j        dd|                    S )z
        Inverse Cumulative Distribution (Quantile) Function

        Notes
        -----
        Will not work if fit has not been called. Uses
        `scipy.stats.mstats.mquantiles`.
        r   r	   )	r   rT   r   r   mstats
mquantilesr#   rD   linspace)r   r/   s     r   icdfzKDEUnivariate.icdf  sI     	Dt|$$|&&tz2;q!X3N3NOOOr'   c                 `    t          |            | j                            | j        |          S )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   evaluatezKDEUnivariate.evaluate&  s,     	D{""4:u555r'   )__name__
__module____qualname____doc__r&   rD   rR   rA   r   rZ   r^   r]   rd   ri   rl    r'   r   r!   r!   0   s       " "HI I I
 vgrvo o o ob     ^ 8 	  	  ^	  	 	 ^	 = = ^=2 P P ^P
6 
6 
6 
6 
6r'   r!   r   r(   r)   Tc	                    t          j        |           } | j        dk    r| dddf         } t          j        | |d         k    | |d         k               }	| |	         } t	          |           }
|t          |
d          }|t          j        |
          }|
}nst          j        |          }t	          |          t	          |	          k    rd}t          |          ||	                                         }|	                                }t          |                     }t          |          rt           || |                    }n<t          |t                    rt          j        | ||          }nt#          |d          }||z  }t          j        | d          ||z  z
  }t          j        | d          ||z  z   }t          j        |||          }| j        |dddf         z
  |z  }|                    |           |j        (|j        \  }}||k     ||k    z  } ||          }d||<   n ||          }d||dk     <   t          j        ||          ||z  z  }|r|||fS ||fS )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)rD   asarrayr$   logical_andrT   maxonesr   rE   r<   r;   r6   floatr3   r4   r
   select_bandwidthr   minrh   TsethrQ   dot)rF   r,   r+   r.   r/   r-   r0   r1   retgridclip_xnobsqr?   rH   rW   rX   r@   kz_loz_highdomain_maskdenss                         r   r9   r9   4  sv   T 	
1Av{{aaagJ^AQKT!W55F	&	Aq66DtR== '$-- *W%%w<<3v;;&&NCS//!&..**+KKMM  ""D|| "22a;;	B		 "(B55 D!!&LB
qqC"H$A
qqC"H$A;q!X&&D 	
d111d7m
	A
 	IIbMMM 	{f4xAJ/DGG+DGGAa!eH6!WR(D T2~Rxr'   c	                    t          j        |           } | t          j        | |d         k    | |d         k                        } t          |                     }	t	          |          rt           || |	                    }n<t          |t                    rt          j	        | ||	          }nt          |d          }||z  }t          |           }
|t          j        |
df          }dt          j        t          j        |                    z  }t          j        |           ||z  z
  }t          j        |           ||z  z   }t          j        ||t#          |          d          \  }}||z
  }t%          | |||          ||
z  z  }t'          |          }t)          |||          |z  }t+          |          }|r|||fS ||fS )	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+   Ng      @   T)retstep)rD   ru   rv   r;   r6   ry   r3   r4   r
   rz   r   rT   rw   ceillog2r{   rh   intr   r   r   r   )rF   r,   r+   r.   r/   r-   r0   r1   r   rH   r   rW   rX   r@   deltaRANGEbinnedyzstarfs                       r   r8   r8     s   z 	
1A	".T!Wa$q'k
2
23A  ""D|| "22a;;	B		 "(B55 D!!&LBq66D 64-((BGBGH--...H
q		C"HA
q		C"HA+aCMM4@@@KD%EE$ Aq(++ut|<F 	fA  He44q8E 	eA ${"ur'   )%rp   numpyrD   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!   rR   r9   r8   rq   r'   r   <module>r      s        " " " " " " " " 5 5 5 5 5 5 7 7 7 7 7 7 ? ? ? ? ? ? ? ?       7 7 7 7 7 7 7 7 7 7       				
 
 
> > >@6 @6 @6 @6 @6 @6 @6 @6L 6'26		N N N Nf 6'26		] ] ] ] ] ]r'   