
    M/Ph'M                        d Z ddlmZmZ ddlZddlZddlm	Z	 ddlm
Z
mZmZmZmZmZ  G d d          Z G d d	          Z G d
 de          Z G d de          Z G d de          Z G d de          Z G d de          Z G d de          Z G d de          Z G d de          Z G d de          ZdS )a  
This models contains the Kernels for Kernel smoothing.

Hopefully in the future they may be reused/extended for other kernel based
method

References:
----------

Pointwise Kernel Confidence Bounds
(smoothconf)
http://fedc.wiwi.hu-berlin.de/xplore/ebooks/html/anr/anrhtmlframe62.html
    )lziplfilterN)	factorial)expmultiplysquaredividesubtractinfc                   T    e Zd ZdZddZd Zd Z eeed          Zd Z	d	 Z
d
 ZdS )NdKernela  Generic N-dimensial kernel

    Parameters
    ----------
    n : int
        The number of series for kernel estimates
    kernels : list
        kernels

    Can be constructed from either
    a) a list of n kernels which will be treated as
    indepent marginals on a gaussian copula (specified by H)
    or b) a single univariate kernel which will be applied radially to the
    mahalanobis distance defined by H.

    In the case of the Gaussian these are both equivalent, and the second constructiong
    is prefered.
    Nc                     |t                      }|| _        d | _        |&t          j        t          j        |                    }|| _        t          j                            |j	                  | _
        d S )N)Gaussian_kernelsweightsnpmatrixidentity_HlinalgcholeskyI	_Hrootinv)selfnkernelsHs       i/var/www/html/test/jupyter/venv/lib/python3.11/site-packages/statsmodels/sandbox/nonparametric/kernels.py__init__zNdKernel.__init__-   s^    ?jjG9	2;q>>**A++QS22    c                     | j         S )zGetter for kernel bandwidth, Hr   r   s    r   getHzNdKernel.getH:   	    wr    c                     || _         dS )zSetter for kernel bandwidth, HNr"   r   values     r   setHzNdKernel.setH>       r    zKernel bandwidth matrixdocc                 V   t          |          }t          |          dk    r|| j        Kt          j         | ||z
  | j        z            j        | j        z            t          | j                  z  }n(t          j         | ||z
  | j        z                      }|S t          j        S )Nr   )lenr   r   meanr   Tsumnan)r   xsxr   ws        r   densityzNdKernel.densityD   s    GG r77199 |'GDD"Q$$.!899;dlJKKCPTP\L]L]]GDD"Q$$.!8::;;H6Mr    c                     t          | j        t                    rSt          j        |          }||z                      d          }|                     t          j        |                    S dS )zAreturns the kernel weight for the independent multivariate kernelN)
isinstancer   CustomKernelr   asarrayr1   )r   r4   ds      r   _kernweightzNdKernel._kernweightU   s\    t}l44 	2
 
1AQBA=="*Q--111	2 	2r    c                 ,    |                      |          S z
        This simply returns the value of the kernel function at x

        Does the same as weight if the function is normalised
        )r=   r   r4   s     r   __call__zNdKernel.__call__a   s     """r    )NN)__name__
__module____qualname____doc__r   r$   r)   propertyr   r6   r=   rA    r    r   r   r      s         $3 3 3 3     	t!:;;;A  "
2 
2 
2# # # # #r    r   c                       e Zd ZdZddZd Zd Z eeed          Zd	 Z	d
 Z
d ZddZd Zd ZddZed             Zed             Zed             Zd Zed             Zd Zd ZdS )r:   z
    Generic 1D Kernel object.
    Can be constructed by selecting a standard named Kernel,
    or providing a lambda expression and domain.
    The domain allows some algorithms to run faster for finite domain kernels.
          ?Nc                     || _         || _        d| _        t          |          r|| _        nt          d          || _        d| _        d| _        d| _	        d| _
        dS )a   
        shape should be a function taking and returning numeric type.

        For sanity it should always return positive or zero but this is not
        enforced in case you want to do weird things. Bear in mind that the
        statistical tests etc. may not be valid for non-positive kernels.

        The bandwidth of the kernel is supplied as h.

        You may specify a domain as a list of 2 values [min, max], in which case
        kernel will be treated as zero outside these values. This will speed up
        calculation.

        You may also specify the normalisation constant for the supplied Kernel.
        If you do this number will be stored and used as the normalisation
        without calculation.  It is recommended you do this if you know the
        constant, to speed up calculation.  In particular if the shape function
        provided is already normalised you should provide norm = 1.0.

        Warning: I think several calculations assume that the kernel is
        normalized. No tests for non-normalized kernel.
        Nz(shape must be a callable object/function)
_normconstdomainr   callable_shape	TypeError_h_L2Norm_kernel_var_normal_reference_constant_order)r   shapehrL   norms        r   r   zCustomKernel.__init__u   si    . E?? 	HDKKFGGG*.'r    c                     | j         S )zGetter for kernel bandwidth, hrP   r#   s    r   gethzCustomKernel.geth   r%   r    c                     || _         dS )zSetter for kernel bandwidth, hNrY   r'   s     r   sethzCustomKernel.seth   r*   r    zKernel Bandwidthr+   c                       fd} j         ||fS t          |t          ||                    }t          |          dk    rt          | \  }}||fS g g fS )zW
        Returns the filtered (xs, ys) based on the Kernel domain centred on x
        c                     | d         z
  j         z  }t          j        |j        d         k    |j        d         k    z            S )z2Used for filter to check if point is in the domainr      )rV   r   allrL   )xyur   r4   s     r   
isInDomainz*CustomKernel.in_domain.<locals>.isInDomain   sB    Aq$& A61A.1A3FGHHHr    Nr   )rL   r   r   r.   )r   r3   ysr4   rc   filtereds   `  `  r   	in_domainzCustomKernel.in_domain   s    	I 	I 	I 	I 	I 	I
 ;8Oz4B<<88H8}}q  xBBxBxr    c                 H   t          j        |          }t          |          }| j         |                     || j        |          \  }}n|                     |||          d         }t          j        |          }|j        dk    r|dddf         }t          |          dk    rr| j        }| j        4d|z  t          j         | ||z
  |z            j        |z  d          z  }n.d||z  z  t          j         | ||z
  |z            d          z  }|S t           j	        S )zUReturns the kernel density estimate for point x based on x-values
        xs
        Nr   r_   )axisrI   )
r   r;   r.   r   rf   ndimrV   r1   r0   r2   )r   r3   r4   r   r   rV   r5   s          r   r6   zCustomKernel.density   s    Z^^GG<#.."dlA??KBR,,Q/BZ^^7a<<AAAdFBr77199A|'EBF44Aq>>#3g#=AFFFF!a%L26$$1ax..q#A#A#AAH6Mr    c                 P    t          j        |          | j        z  | j        z  |z  S )a  approximate pointwise variance for kernel density

        not verified

        Parameters
        ----------
        density : array_lie
            pdf of the kernel density
        nobs : int
            number of observations used in the KDE estimation

        Returns
        -------
        kde_var : ndarray
            estimated variance of the density estimate

        Notes
        -----
        This uses the asymptotic normal approximation to the distribution of
        the density estimate.
        )r   r;   L2NormrV   )r   r6   nobss      r   density_varzCustomKernel.density_var   s'    , z'""T[0469D@@r    皙?c                    ddl m} |j                            |dz            }t	          j        |          }|t	          j        |                     ||                    z  }t	          j        ||z
  ||z   f          }|S )a+  approximate pointwise confidence interval for kernel density

        The confidence interval is centered at the estimated density and
        ignores the bias of the density estimate.

        not verified

        Parameters
        ----------
        density : array_lie
            pdf of the kernel density
        nobs : int
            number of observations used in the KDE estimation

        Returns
        -------
        conf_int : ndarray
            estimated confidence interval of the density estimate, lower bound
            in first column and upper bound in second column

        Notes
        -----
        This uses the asymptotic normal approximation to the distribution of
        the density estimate. The lower bound can be negative for density
        values close to zero.
        r   stats       @)	scipyrq   rW   isfr   r;   sqrtrm   column_stack)r   r6   rl   alpharq   crit
half_widthconf_ints           r   density_confintzCustomKernel.density_confint   s    6 	 z~~ebj))*W%%BGD$4$4Wd$C$CDDD
?Gj$8'J:N#OPPr    c                 0                          ||          \  }}t          |          dk    r\t          j          |z
   j        z                      }t          j         fdt          ||          D                       }||z  S t          j        S )zReturns the kernel smoothing estimate for point x based on x-values
        xs and y-values ys.
        Not expected to be called by the user.
        r   c                 H    g | ]\  }}| |z
  j         z            z  S rG   rV   ).0xxyyr   r4   s      r   
<listcomp>z'CustomKernel.smooth.<locals>.<listcomp>  s6    III62r44Atv...IIIr    )rf   r.   r   r1   rV   zipr2   r   r3   rd   r4   r5   vs   `  `  r   smoothzCustomKernel.smooth	  s    
 B**Br77199ttRT46M**++AIIIIISR[[IIIJJAq5L6Mr    c                                                     \  t                    dk    rt          j         fdD                       }t	          t          |                    }t          j          z
   j        z                      }t          j         fdt          |          D                       }||z  S t          j	        S )zJReturns the kernel smoothing estimate of the variance at point x.
        r   c                 >    g | ]}                     |          S rG   r   r   r   r   r3   rd   s     r   r   z*CustomKernel.smoothvar.<locals>.<listcomp>  )    "H"H"Hr4;;r2r#:#:"H"H"Hr    c                 H    g | ]\  }}| |z
  j         z            z  S rG   r~   r   r   rrr   r4   s      r   r   z*CustomKernel.smoothvar.<locals>.<listcomp>!  6    NNN62r44Atv...NNNr    )
rf   r.   r   arrayr   r
   r1   rV   r   r2   )r   r3   rd   r4   
fittedvalssqresidr5   r   s   ````    r   	smoothvarzCustomKernel.smoothvar  s     B**Br77Q;;"H"H"H"H"H"HR"H"H"HIIJhr:6688GttRT46M**++ANNNNNSW=M=MNNNOOAq5L6Mr    c                                                      \  t                    dk    r:t          j         fdD                       }t	          t          |                    }t          j          z
   j        z                      }t          j         fdt          |          D                       }||z  }	t          j	        |	          }
 j
        }                               }ddlm} |j                            |dz            }||
z  t          j	        |          z  t          j	        | j        z   j        z            z  }||z
  |||z   fS t          j        t          j        t          j        fS )LReturns the kernel smoothing estimate with confidence 1sigma bounds
        r   c                 >    g | ]}                     |          S rG   r   r   s     r   r   z+CustomKernel.smoothconf.<locals>.<listcomp>,  r   r    c                 H    g | ]\  }}| |z
  j         z            z  S rG   r~   r   s      r   r   z+CustomKernel.smoothconf.<locals>.<listcomp>3  r   r    rp      )rf   r.   r   r   r   r
   r1   rV   r   ru   rk   r   rs   rq   rW   rt   
norm_constr2   )r   r3   rd   r4   rw   r   r   r5   r   varsdKyhatrq   rx   errs   ````            r   
smoothconfzCustomKernel.smoothconf&  s    B**Br77Q;;"H"H"H"H"H"HR"H"H"HIIJZ(( G ttRT46M**++ANNNNNSW=M=MNNNOOAa%CBA;;r2q))D######:>>%!),,D)bgajj(271tv:3O+P+PPC3JdSj11FBFBF++r    c                 ,     j          fd} j        8t          j                            |t
           t
                    d          _         nBt          j                            | j        d          j        d                   d          _          j         S )zAReturns the integral of the square of the kernal from -inf to infNc                 D    j                             |           z  dz  S Nr   r   rN   r4   r   s    r   <lambda>z%CustomKernel.L2Norm.<locals>.<lambda>C  s    A >B r    r   r_   )rQ   rL   rs   	integratequadr   )r   L2Funcs   ` r   rk   zCustomKernel.L2Norm?  s     <BBBBF{"$33FSD#FFqI$33FDKN/3{1~ ?  ??@ B|r    c                 (   | j         | j        2t          j                            | j        t           t                    }n<t          j                            | j        | j        d         | j        d                   }d|d         z  | _         | j         S )zM
        Normalising constant for kernel (integral from -inf to inf)
        Nr   r_   rI   )rK   rL   rs   r   r   rN   r   )r   quadress     r   r   zCustomKernel.norm_constK  sw    
 ?"{"/..t{SD#FF/..t{DKN/3{1~? ?!71:.DOr    c                 ,     j          fd} j        8t          j                            |t
           t
                    d          _         nBt          j                            | j        d          j        d                   d          _          j         S )z'Returns the second moment of the kernelNc                 J    | dz  j         z                      |           z  S r   r   r   s    r   r   z)CustomKernel.kernel_var.<locals>.<lambda>]  s!    QTDO3dkk!nnD r    r   r_   )rR   rL   rs   r   r   r   )r   funcs   ` r   
kernel_varzCustomKernel.kernel_varY  s     #DDDDD{"#(?#7#7sdC#H#H#K  #(?#7#7dk!n/3{1~$? $??@$B r    c                 ^    |dk    rd}t          |          |dk    rdS |dk    r| j        S d S )Nr   z2Only first and second moment currently implementedr_   r   )NotImplementedErrorr   )r   r   msgs      r   momentszCustomKernel.momentse  sD    q55FC%c***66166?" 6r    c                 F   | j         }|dk    sd}t          |          | j        vt          j        dz  t          |          dz  z  | j        z  }|d|z  t          d|z            z  |                     |          dz  z  z  }d|dd|z  dz   z  z  z  }|| _        | j        S )a^  
        Constant used for silverman normal reference asymtotic bandwidth
        calculation.

        C  = 2((pi^(1/2)*(nu!)^3 R(k))/(2nu(2nu)!kap_nu(k)^2))^(1/(2nu+1))
        nu = kernel order
        kap_nu = nu'th moment of kernel
        R = kernel roughness (square of L^2 norm)

        Note: L2Norm property returns square of norm.
        r   z)Only implemented for second order kernelsN      ?   rI   r_   )rT   r   rS   r   pir   rk   r   )r   nur   Cs       r   normal_reference_constantz&CustomKernel.normal_reference_constantq  s     [Qww=C%c****2immQ..<A!b&9QV,,,t||B/?/?/BBCA!c1R46l##A./D+..r    c                 <    | j         |                     |          z  S )z0This returns the normalised weight at distance xr   r@   s     r   weightzCustomKernel.weight  s    t{{1~~--r    c                 ,    |                      |          S r?   )rN   r@   s     r   rA   zCustomKernel.__call__  s     {{1~~r    )rI   NN)rn   )rB   rC   rD   rE   r   rZ   r\   rF   rV   rf   r6   rm   r{   r   r   r   rk   r   r   r   r   r   rA   rG   r    r   r:   r:   j   sz        " " " "H     	t!3444A     ,  0A A A0       D    , , , ,2 	 	 X	   X 	  	  X	 
# 
# 
# / / X/6. . .    r    r:   c                       e Zd ZddZdS )UniformrI   c                 t    t                               | d |ddgd           d| _        d| _        d| _        d S )Nc                 :    dt          j        | j                  z  S )Nr   )r   onesrU   r4   s    r   r   z"Uniform.__init__.<locals>.<lambda>  s    C"'!':J:J4J r          rI   rU   rV   rL   rW   r   gUUUUUU?r   r:   r   rQ   rR   rT   r   rV   s     r   r   zUniform.__init__  sL    d*J*Ja&*C[ 	 	> 	> 	>!r    NrI   rB   rC   rD   r   rG   r    r   r   r     (             r    r   c                       e Zd ZddZdS )
TriangularrI   c                 t    t                               | d |ddgd           d| _        d| _        d| _        d S )Nc                 &    dt          |           z
  S )Nr_   absr   s    r   r   z%Triangular.__init__.<locals>.<lambda>  s    AAJ r    r   rI   r   gUUUUUU?gUUUUUU?r   r   r   s     r   r   zTriangular.__init__  sL    d*>*>!&*C[ 	 	> 	> 	>!r    Nr   r   rG   r    r   r   r     r   r    r   c                       e Zd ZddZdS )EpanechnikovrI   c                 t    t                               | d |ddgd           d| _        d| _        d| _        d S )Nc                     dd| | z  z
  z  S )Ng      ?r_   rG   r   s    r   r   z'Epanechnikov.__init__.<locals>.<lambda>  s    D!ac'N r    r   rI   r   g333333?g?r   r   r   s     r   r   zEpanechnikov.__init__  sL    d*B*Ba&*C[ 	 	> 	> 	>r    Nr   r   rG   r    r   r   r     r   r    r   c                   (    e Zd ZddZd Zd Zd ZdS )BiweightrI   c                 t    t                               | d |ddgd           d| _        d| _        d| _        d S )Nc                     dd| | z  z
  dz  z  S )N      ?r_   r   rG   r   s    r   r   z#Biweight.__init__.<locals>.<lambda>  s    FA!Ga<4G r    r   rI   r   gm۶m?g$I$I?r   r   r   s     r   r   zBiweight.__init__  sL    d*G*G1&*C[ 	 	> 	> 	>!r    c                    |                      |||          \  }}t          |          dk    rt          j        t	          t          dt	          t          t          ||          | j                                                          }t          j        t          |t	          t          dt	          t          t          ||          | j                                                                    }||z  S t          j	        S )zReturns the kernel smoothing estimate for point x based on x-values
        xs and y-values ys.
        Not expected to be called by the user.

        Special implementation optimized for Biweight.
        r   r_   )
rf   r.   r   r1   r   r
   r	   rV   r   r2   r   s         r   r   zBiweight.smooth  s    B**Br77Q;;vhq&Q8<2@ 2@ +A +A B B C C D DAxF8Avf08Q?I ?I 8J 8J ,K ,K %L %L M M N NAq5L6Mr    c                                           |          \  t                    dk    rt          j         fdD                       }t	          t          |                    }t          j        t	          t          dt	          t          t          |           j                                                          }t          j        t          |t	          t          dt	          t          t          |           j                                                                    }||z  S t          j
        S )zS
        Returns the kernel smoothing estimate of the variance at point x.
        r   c                 >    g | ]}                     |          S rG   r   r   s     r   r   z&Biweight.smoothvar.<locals>.<listcomp>  r   r    rI   r_   )rf   r.   r   r   r   r
   r1   r	   rV   r   r2   )r   r3   rd   r4   r   rsr5   r   s   ```     r   r   zBiweight.smoothvar  sH    B**Br77Q;;"H"H"H"H"H"HR"H"H"HIIJZ0011BvhsF6(2q//8<4@ 4@ -A -A B B C C D DAxF8Avf08Q?I ?I 8J 8J ,K ,K %L %L M M N NAq5L6Mr    c                                           |          \  t                    dk    rnt          j         fdD                       }t	          t          |                    }t          j        t	          t          dt	          t          t          |           j                                                          }t          j        t          |t	          t          dt	          t          t          |           j                                                                    }||z  }t          j
        |          }	 j        }
                     |          }|	|
z  t          j
        d|z   j        z            z  }||z
  |||z   fS t          j        t          j        t          j        fS )r   r   c                 >    g | ]}                     |          S rG   r   r   s     r   r   z(Biweight.smoothconf_.<locals>.<listcomp>  r   r    rI   r_   r   )rf   r.   r   r   r   r
   r1   r	   rV   r   ru   rk   r   r2   )r   r3   rd   r4   r   r   r5   r   r   r   r   r   r   s   ```          r   smoothconf_zBiweight.smoothconf_  s    B**Br77Q;;"H"H"H"H"H"HR"H"H"HIIJZ0011BvhsF6(2q//8<4@ 4@ -A -A B B C C D DAxF8Avf08Q?I ?I 8J 8J ,K ,K %L %L M M N NAa%CBA;;r2q))Dq&276A:#6777C3JdSj11FBFBF++r    Nr   )rB   rC   rD   r   r   r   r   rG   r    r   r   r     sU             $  ", , , , ,r    r   c                       e Zd ZddZdS )	TriweightrI   c                 t    t                               | d |ddgd           d| _        d| _        d| _        d S )Nc                     dd| | z  z
  dz  z  S )Ng     ?r_   r   rG   r   s    r   r   z$Triweight.__init__.<locals>.<lambda>  s    GQ1WqL4H r    r   rI   r   gCЏ+s?gqq?r   r   r   s     r   r   zTriweight.__init__  sL    d*H*HA&*C[ 	 	> 	> 	>"!r    Nr   r   rG   r    r   r   r     r   r    r   c                        e Zd ZdZddZd ZdS )r   zN
    Gaussian (Normal) Kernel

    K(u) = 1 / (sqrt(2*pi)) exp(-0.5 u**2)
    rI   c                     t                               | d |d d           ddt          j        t          j                  z  z  | _        d| _        d| _        d S )Nc                 >    dt          j        | dz   dz            z  S )NgQ63E?r   rr   )r   r   r   s    r   r   z#Gaussian.__init__.<locals>.<lambda>  s#    6H1uSy))7* r    rI   r   rr   r   )r:   r   r   ru   r   rQ   rR   rT   r   s     r   r   zGaussian.__init__  sc    d -* -*/04 	 	M 	M 	MC./r    c                    t          j        t          t          t	          t          t          ||          | j                            d                              }t          j        t          |t          t          t	          t          t          ||          | j                            d                                        }||z  S )zReturns the kernel smoothing estimate for point x based on x-values
        xs and y-values ys.
        Not expected to be called by the user.

        Special implementation optimized for Gaussian.
              )r   r1   r   r   r   r	   r
   rV   r   s         r   r   zGaussian.smooth  s     F3xvhr1oo.2f(6 (6 !7 !77;= = > > ? ?F8BHVF8B??:>&5B 5B .C .CDH%J %J !K !K L L M Ms
r    Nr   )rB   rC   rD   rE   r   r   rG   r    r   r   r     sA         
       r    r   c                       e Zd ZdZddZdS )CosinezO
    Cosine Kernel

    K(u) = pi/4 cos(0.5 * pi * u) between -1.0 and 1.0
    rI   c                     t                               | d |ddgd           t          j        dz  dz  | _        d| _        d| _        d S )Nc                 P    dt          j        t           j        dz  | z            z  S )Ng-DT!?rr   r   cosr   r   s    r   r   z!Cosine.__init__.<locals>.<lambda>  s#    4GruSy1}%%5& r    r   rI   r   r   g      0@gtwB??)r:   r   r   r   rQ   rR   rT   r   s     r   r   zCosine.__init__  s]    d +& +&)*D#;s 	 	L 	L 	Luax}-r    Nr   rB   rC   rD   rE   r   rG   r    r   r   r     2         
     r    r   c                       e Zd ZdZddZdS )Cosine2z
    Cosine2 Kernel

    K(u) = 1 + cos(2 * pi * u) between -0.5 and 0.5

    Note: this  is the same Cosine kernel that Stata uses
    rI   c                 t    t                               | d |ddgd           d| _        d| _        d| _        d S )	Nc                 P    dt          j        dt           j        z  | z            z   S )Nr_   rr   r   r   s    r   r   z"Cosine2.__init__.<locals>.<lambda>/  s    AsRU{Q8O8O4O r    r   r   rI   r   g      ?gH{?r   r   r   s     r   r   zCosine2.__init__.  sL    d*O*OtSk# 	 	7 	7 	7.r    Nr   r   rG   r    r   r   r   &  s2              r    r   c                       e Zd ZdZddZdS )Tricubez]
    Tricube Kernel

    K(u) = 0.864197530864 * (1 - abs(x)**3)**3 between -1.0 and 1.0
    rI   c                 t    t                               | d |ddgd           d| _        d| _        d| _        d S )Nc                 8    ddt          |           dz  z
  dz  z  S )Ng?r_   r   r   r   s    r   r   z"Tricube.__init__.<locals>.<lambda><  s     >QQQR]UVDV3V r    r   rI   r   gjo?g4\o?r   r   r   s     r   r   zTricube.__init__;  sO    d)V)V !4+c 	 	C 	C 	C"%r    Nr   r   rG   r    r   r   r   5  r   r    r   )rE   statsmodels.compat.pythonr   r   numpyr   scipy.integraters   scipy.specialr   r   r   r   r	   r
   r   r   r:   r   r   r   r   r   r   r   r   r   rG   r    r   <module>r      sj   $ 4 3 3 3 3 3 3 3         # # # # # # > > > > > > > > > > > > > > > >M# M# M# M# M# M# M# M#`m m m m m m m m`	    l              <   >, >, >, >, >,| >, >, >,@           |   4    \       l       l     r    