
    M/PhyG                        d Z ddlZddlZddlmZ ddlmZ 	 ddlZdZ	n# e
$ r dZ	Y nw xY wddlmZ  eej        ej        ej        ej        ej        ej        ej        ej        ej        ej        ej        ej        ej        	          Zd
 Zd Z G d d          Z G d d          Z G d d          Z d Z!d Z"	 	 ddZ#dS )zh
Module containing the base object for multivariate kernel density and
regression, plus some utilities.
    N)optimize)
mquantilesTF   )kernels)	wangryzinaitchisonaitkengaussianaitchison_aitken_regwangryzin_reggauss_convolutionwangryzin_convolutionaitchisonaitken_convolutiongaussian_cdfaitchisonaitken_cdfwangryzin_cdf
d_gaussiantricubec                     t          j        | d          }t          | dd          j        d         }t          | dd          j        d         }||z
  dz  }t          j        ||          }|S )z1Compute minimum of std and IQR for each variable.r   axisg      ?g      ?g/$?)npstdr   dataminimum)r   s1q75q25s2
dispersions         f/var/www/html/test/jupyter/venv/lib/python3.11/site-packages/statsmodels/nonparametric/_kernel_base.py_compute_min_std_IQRr!   #   ss    	1			B
T4a
(
(
(
-a
0C
T4a
(
(
(
-a
0C
)u	BB##J    c           
      H   |
r.t           j                            |           |d|ddf         }n||d         |d         ddf         }| dk    r,ddlm} |	d         } ||||t          d                    }n| d	k    rHdd
lm} |	\  }}}|ddd|f         }|dd|df         } ||||||t          d                    }nw| dk    rbddlm} |	\  }}}t          |dddf         d          }t          |ddddf         |          } ||||||t          d                    }nt          d          | dk    r|ddddf         }t          |          }||d||z   z  z  z  }|d||z   z  z  ||<   |d||z   z  z  ||<   |j        |z  }|j        }||fS )z"Compute bw on subset of data.

    Called from ``GenericKDE._compute_efficient_*``.

    Notes
    -----
    Needs to be outside the class in order for joblib to be able to pickle it.
    Nr   r   KDEMultivariate)r$   F)	efficient)bwdefaultsKDEMultivariateConditional)r(   	KernelReg)r)   )endogexogreg_typevar_typer&   r'   zdclass_type not recognized, should be one of {KDEMultivariate, KDEMultivariateConditional, KernelReg}             )r   randomshufflekernel_densityr$   EstimatorSettingsr(   kernel_regressionr)   _adjust_shape
ValueErrorr!   r&   )
class_typer   r&   codon_cvarsix_ordix_unordn_sub
class_vars	randomizeboundsub_datar$   r-   	sub_modelr(   k_depdep_type
indep_typer*   r+   r)   k_varsr,   r   fctsample_scale_subbw_subs                                r    _compute_subsetrJ   -   s     .
	$	?aq)111,-&&&333333a=#OHh2!2U!C!C!CE E E			3	3	3>>>>>>&0#xFUF#566	"..udH2(9E(J(J(JL L L			{	"	"000000%/"&(hqqq!tna00Xaaae_f55IEx'/B'85'I'I'IK K K		  L M M 	M [  AAAqrrE?%h//J
usgl34
4CC7R<01CM#2./CK |c)\FV##r"   c                   N    e Zd ZdZd Zd Zd Zd Zd Zd Z	d Z
d	 Zd
 Zd ZdS )
GenericKDEzG
    Base class for density estimation and regression KDE classes.
    c                     |d}t          |t                    sd| _        t          j        |          }n4|| _        |dk    r| j        }n|dk    r| j        }n| j        } |            }|S )a  
        Computes the bandwidth of the data.

        Parameters
        ----------
        bw : {array_like, str}
            If array_like: user-specified bandwidth.
            If a string, should be one of:

                - cv_ml: cross validation maximum likelihood
                - normal_reference: normal reference rule of thumb
                - cv_ls: cross validation least squares

        Notes
        -----
        The default values for bw is 'normal_reference'.
        Nnormal_referenceuser-specifiedcv_ml)
isinstancestr
_bw_methodr   asarray_normal_reference_cv_ml_cv_ls)selfr&   resbwfuncs       r    _compute_bwzGenericKDE._compute_bwg   s~    $ :#B"c"" 	.DO*R..CC !DO'''/w&((C
r"   c                      t          |          S )a  
        Computes the measure of dispersion.

        The minimum of the standard deviation and interquartile range / 1.349

        Notes
        -----
        Reimplemented in `KernelReg`, because the first column of `data` has to
        be removed.

        References
        ----------
        See the user guide for the np package in R.
        In the notes on bwscaling option in npreg, npudens, npcdens there is
        a discussion on the measure of dispersion
        )r!   )rX   r   s     r    _compute_dispersionzGenericKDE._compute_dispersion   s    " $D)))r"   c                     dS )zpHelper method to be able to pass needed vars to _compute_subset.

        Needs to be implemented by subclasses.N rX   s    r    _get_class_vars_typezGenericKDE._get_class_vars_type   s	     	r"   c                     d _         t          t                    r _         n	d _         S  j        } j        t          j         j                   j        	                    d          ddt           j                  \  } j        rdg j        z  nDfdt          |z            D             |z  dk    r                    ||z  z
  |f            j        r j        nt                    }t!          j        | j        f          }t!          j        | j        f          }                                 \  t(          rH t+          j         j                   fd	t          |          D                       }nLg }t          |          D ]:}|                    t1           j        |                              ;t          |          D ],}||         d         ||ddf<   ||         d
         ||ddf<   -                               }	 j        rt           j        nt           j        }
 |
|d          }||	z  |dz   z  z  z  |         |dz   z  z  z  <   |         |dz   z  z  z  <    j        rt!          j        |d          S )a\  
        Computes the bandwidth by estimating the scaling factor (c)
        in n_res resamples of size ``n_sub`` (in `randomize` case), or by
        dividing ``nobs`` into as many ``n_sub`` blocks as needed (if
        `randomize` is False).

        References
        ----------
        See p.9 in socserv.mcmaster.ca/racine/np_faq.pdf
        NrN   rO   c   c                 *    g | ]}|z  |d z   z  fS )r   r_   ).0ir=   s     r    
<listcomp>z1GenericKDE._compute_efficient.<locals>.<listcomp>   s*    OOOQq5y1Q3%-0OOOr"   r   )n_jobsc              3      K   | ]<} t          j        t                    	
j        |                   V  =d S N)joblibdelayedrJ   r?   )rf   rg   boundsr&   r7   r>   r8   r   r9   r;   r<   r:   r=   rX   s     r    	<genexpr>z0GenericKDE._compute_efficient.<locals>.<genexpr>   sq       6* 6*  0//b"b'68:t~vayB B6* 6* 6* 6* 6* 6*r"   r   r   r.   r/   )rS   rQ   rR   nobsr=   copydeepcopyr   	data_typecount_get_type_posr?   n_resrangeappendlenr   emptyrF   ra   
has_joblibrl   Parallelri   rJ   r]   return_medianmedianmeanreturn_only_bw)rX   r&   rp   _n_blockssample_scaleonly_bwrY   rg   s
order_funcm_scalern   r7   r>   r8   r   r9   r;   r<   r:   r=   s   ``          @@@@@@@@@@r    _compute_efficientzGenericKDE._compute_efficient   s]    :0DOb# 	 DOO.DOIy
}TY''.&&s+++DN;;68 > 	;Vdj(FFOOOO%:N:NOOOFe|atdUl2D9:::!%@4::S[[x4; 788(Hdk233!%!:!:!<!<
J 	75&/555 6* 6* 6* 6* 6* 6* 6* 6* 6* 6* 6* 6* 6* 6* 6* x	6* 6* 6* * *CC C8__ 7 7

?:tRR+2FHe+5t~+1!96 6 7 7 7 7
 x 	& 	&A!$QLAAAF1IGAqqqDMM$$T**"&"4ARYY"'
*\222q[4#2"677V_tcGbL.A'BB6
x(4#"2E+FF8 	,7+++B	r"   c                     |j         | _         |j        | _        |j        | _        |j        | _        |j        | _        |j        | _        |j        | _        dS )z4Sets the default values for the efficient estimationN)rv   r=   r?   r}   r%   r   ri   )rX   r'   s     r    _set_defaultszGenericKDE._set_defaults   sK    ^
^
!+%3!+&5or"   c                     t          j        | j        d          }d|z  | j        dd| j        j        d         z   z  z  z  S )a\  
        Returns Scott's normal reference rule of thumb bandwidth parameter.

        Notes
        -----
        See p.13 in [2] for an example and discussion.  The formula for the
        bandwidth is

        .. math:: h = 1.06n^{-1/(4+q)}

        where ``n`` is the number of observations and ``q`` is the number of
        variables.
        r   r   g(\?r.   rd   r   )r   r   r   rp   shaperX   Xs     r    rU   zGenericKDE._normal_reference   sC     F491%%%ax$)DIOA4F0F(GHHHr"   c                     d||dk     <   t          | j                  \  }}}t          j        ||         d          ||<   t          j        ||         d          ||<   |S )z{
        Sets bandwidth lower bound to effectively zero )1e-10), and for
        discrete values upper bound to 1.
        g|=r   g      ?)ru   rs   r   r   )rX   r&   r   r;   r<   s        r    _set_bw_boundszGenericKDE._set_bw_bounds  s^    
 26
+DN;;68Z6
B//6
z"X,338	r"   c           	          |                                  }t          j        | j        |t          j        fdddd          }|                     |          }|S )a  
        Returns the cross validation maximum likelihood bandwidth parameter.

        Notes
        -----
        For more details see p.16, 18, 27 in Ref. [1] (see module docstring).

        Returns the bandwidth estimate that maximizes the leave-out-out
        likelihood.  The leave-one-out log likelihood function is:

        .. math:: \ln L=\sum_{i=1}^{n}\ln f_{-i}(X_{i})

        The leave-one-out kernel estimator of :math:`f_{-i}` is:

        .. math:: f_{-i}(X_{i})=\frac{1}{(n-1)h}
                        \sum_{j=1,j\neq i}K_{h}(X_{i},X_{j})

        where :math:`K_{h}` represents the Generalized product kernel
        estimator:

        .. math:: K_{h}(X_{i},X_{j})=\prod_{s=1}^
                        {q}h_{s}^{-1}k\left(\frac{X_{is}-X_{js}}{h_{s}}\right)
             @@r   MbP?)x0argsmaxitermaxfundispxtol)rU   r   fminloo_likelihoodr   logr   rX   h0r&   s      r    rV   zGenericKDE._cv_ml  s\    2 ##%%]4.2RVJ#&sG G G  $$	r"   c                     |                                  }t          j        | j        |dddd          }|                     |          }|S )a  
        Returns the cross-validation least squares bandwidth parameter(s).

        Notes
        -----
        For more details see pp. 16, 27 in Ref. [1] (see module docstring).

        Returns the value of the bandwidth that maximizes the integrated mean
        square error between the estimated and actual distribution.  The
        integrated mean square error (IMSE) is given by:

        .. math:: \int\left[\hat{f}(x)-f(x)\right]^{2}dx

        This is the general formula for the IMSE.  The IMSE differs for
        conditional (``KDEMultivariateConditional``) and unconditional
        (``KDEMultivariate``) kernel density estimation.
        r   r   r   )r   r   r   r   r   )rU   r   r   imser   r   s      r    rW   zGenericKDE._cv_ls6  sR    $ ##%%]49S1 $& & &  $$	r"   c                     t           rk   )NotImplementedErrorr`   s    r    r   zGenericKDE.loo_likelihoodN  s    !!r"   N)__name__
__module____qualname____doc__r[   r]   ra   r   r   rU   r   rV   rW   r   r_   r"   r    rL   rL   c   s         $ $ $L* * *&  H H HT& & &I I I"
 
 
  >  0" " " " "r"   rL   c                       e Zd ZdZ	 	 d	dZdS )
r3   a  
    Object to specify settings for density estimation or regression.

    `EstimatorSettings` has several properties related to how bandwidth
    estimation for the `KDEMultivariate`, `KDEMultivariateConditional`,
    `KernelReg` and `CensoredKernelReg` classes behaves.

    Parameters
    ----------
    efficient : bool, optional
        If True, the bandwidth estimation is to be performed
        efficiently -- by taking smaller sub-samples and estimating
        the scaling factor of each subsample.  This is useful for large
        samples (nobs >> 300) and/or multiple variables (k_vars > 3).
        If False (default), all data is used at the same time.
    randomize : bool, optional
        If True, the bandwidth estimation is to be performed by
        taking `n_res` random resamples (with replacement) of size `n_sub` from
        the full sample.  If set to False (default), the estimation is
        performed by slicing the full sample in sub-samples of size `n_sub` so
        that all samples are used once.
    n_sub : int, optional
        Size of the sub-samples.  Default is 50.
    n_res : int, optional
        The number of random re-samples used to estimate the bandwidth.
        Only has an effect if ``randomize == True``.  Default value is 25.
    return_median : bool, optional
        If True (default), the estimator uses the median of all scaling factors
        for each sub-sample to estimate the bandwidth of the full sample.
        If False, the estimator uses the mean.
    return_only_bw : bool, optional
        If True, the estimator is to use the bandwidth and not the
        scaling factor.  This is *not* theoretically justified.
        Should be used only for experimenting.
    n_jobs : int, optional
        The number of jobs to use for parallel estimation with
        ``joblib.Parallel``.  Default is -1, meaning ``n_cores - 1``, with
        ``n_cores`` the number of available CPU cores.
        See the `joblib documentation
        <https://joblib.readthedocs.io/en/latest/generated/joblib.Parallel.html>`_ for more details.

    Examples
    --------
    >>> settings = EstimatorSettings(randomize=True, n_jobs=3)
    >>> k_dens = KDEMultivariate(data, var_type, defaults=settings)
    F   2   Tc                 h    || _         || _        || _        || _        || _        || _        || _        d S rk   )r%   r?   rv   r=   r}   r   ri   )rX   r%   r?   rv   r=   r}   r   ri   s           r    __init__zEstimatorSettings.__init__  s9    ""

*,r"   N)FFr   r   TFr   )r   r   r   r   r   r_   r"   r    r3   r3   R  s=        - -\ JLBD     r"   r3   c                       e Zd ZdZd Zd ZdS )LeaveOneOuta  
    Generator to give leave-one-out views on X.

    Parameters
    ----------
    X : array_like
        2-D array.

    Examples
    --------
    >>> X = np.random.normal(0, 1, [10,2])
    >>> loo = LeaveOneOut(X)
    >>> for x in loo:
    ...    print x

    Notes
    -----
    A little lighter weight than sklearn LOO. We do not need test index.
    Also passes views on X, not the index.
    c                 8    t          j        |          | _        d S rk   )r   rT   r   r   s     r    r   zLeaveOneOut.__init__  s    Ar"   c              #      K   | j         }t          j        |          \  }}t          |          D ]0}t          j        |t
                    }d||<   ||d d f         V  1d S )N)dtypeF)r   r   r   rw   onesbool)rX   r   rp   rF   rg   indexs         r    __iter__zLeaveOneOut.__iter__  su      Fx{{ft 	 	AGD---EE!HE111H+	 	r"   N)r   r   r   r   r   r   r_   r"   r    r   r     s<         (      r"   r   c                     t          j        d | D                       }t          j        d | D                       }t          j        d | D                       }|||fS )Nc                     g | ]}|d k    	S rc   r_   rf   rc   s     r    rh   z!_get_type_pos.<locals>.<listcomp>  s    333QS333r"   c                     g | ]}|d k    	S )or_   r   s     r    rh   z!_get_type_pos.<locals>.<listcomp>  s    222AqCx222r"   c                     g | ]}|d k    	S )ur_   r   s     r    rh   z!_get_type_pos.<locals>.<listcomp>  s    444ac444r"   )r   array)r-   ix_contr;   r<   s       r    ru   ru     si    h33(33344GX2222233Fx44844455HFH$$r"   c                    t          j        |           } | j        dk    rt          j        |           } | j        dk    r	|dk    rd}n~| j        dk    r|dk    rt	          |           }n]t          j        |           d         |k    r%t          j        |           d         |k    r| j        } t          j        |           d         }t          j        | ||f          } | S )z> Returns an array of shape (nobs, k_vars) for use with `gpke`.   r   r   )r   rT   ndimsqueezery   r   Treshape)datrF   rp   s      r    r5   r5     s    
*S//C
x!||joo
x1}}!	Q6Q;;3xx8C==v%%"(3--*:f*D*D%Cx}}Q
*S4.
)
)CJr"   r	   r   r   c                    t          |||          }t          j        |j                  }	t	          |          D ]B\  }
}t
          ||                  } || |
         |dd|
f         ||
                   |	dd|
f<   Ct          j        d |D                       }|	                    d          t          j        | |                   z  }|r|                    d          S |S )a[  
    Returns the non-normalized Generalized Product Kernel Estimator

    Parameters
    ----------
    bw : 1-D ndarray
        The user-specified bandwidth parameters.
    data : 1D or 2-D ndarray
        The training data.
    data_predict : 1-D ndarray
        The evaluation points at which the kernel estimation is performed.
    var_type : str, optional
        The variable type (continuous, ordered, unordered).
    ckertype : str, optional
        The kernel used for the continuous variables.
    okertype : str, optional
        The kernel used for the ordered discrete variables.
    ukertype : str, optional
        The kernel used for the unordered discrete variables.
    tosum : bool, optional
        Whether or not to sum the calculated array of densities.  Default is
        True.

    Returns
    -------
    dens : array_like
        The generalized product kernel density estimator.

    Notes
    -----
    The formula for the multivariate kernel estimator for the pdf is:

    .. math:: f(x)=\frac{1}{nh_{1}...h_{q}}\sum_{i=1}^
                        {n}K\left(\frac{X_{i}-x}{h}\right)

    where

    .. math:: K\left(\frac{X_{i}-x}{h}\right) =
                k\left( \frac{X_{i1}-x_{1}}{h_{1}}\right)\times
                k\left( \frac{X_{i2}-x_{2}}{h_{2}}\right)\times...\times
                k\left(\frac{X_{iq}-x_{q}}{h_{q}}\right)
    )rc   r   r   Nc                     g | ]}|d k    	S r   r_   r   s     r    rh   zgpke.<locals>.<listcomp>  s    888!Q#X888r"   r   r   r   )	dictr   rz   r   	enumeratekernel_funcr   prodsum)r&   r   data_predictr-   ckertypeokertypeukertypetosumkertypesKvaliivtypefunciscontinuousdenss                  r    gpker     s    X h(h777H 8DJDx(( B B	E8E?+d2b642;R0@AAQQQU888x88899L99!9rwr,'7888D xxQxr"   )r	   r   r   T)$r   rq   numpyr   scipyr   scipy.stats.mstatsr   rl   r{   ImportError r   r   
wang_ryzinaitchison_aitkenr	   r
   wang_ryzin_reggaussian_convolutionwang_ryzin_convolutionaitchison_aitken_convolutionr   aitchison_aitken_cdfwang_ryzin_cdfr   r   r   r!   rJ   rL   r3   r   ru   r5   r   r_   r"   r    <module>r      s               ) ) ) ) ) )MMMJJ   JJJ       dW/#*#;#,*1*F#*#9%,%A)0)G/6/S ' 4'.'C!(!7%0"?, , ,  3$ 3$ 3$ll" l" l" l" l" l" l" l"^7 7 7 7 7 7 7 7t       D% % %  & 5?AE> > > > > >s    ))