U
    A¼|e:0  ã                   @   sÊ   d Z ddlZddlmZmZ ddlZddlmZ ddl	m
Z
 ddlmZ ddlmZ dd	lmZmZ dd
lmZmZ ddlmZ ddlmZmZ ddlmZ ddddddgZeedœZG dd„ de
ƒZdS )z5
Kernel Density Estimation
-------------------------
é    N)ÚIntegralÚReal)Úgammaincé   )ÚBaseEstimator©ÚVALID_METRICS)Úcheck_random_state)Ú_check_sample_weightÚcheck_is_fitted)ÚIntervalÚ
StrOptions)Ú	row_normsé   )ÚBallTreeÚDTYPE)ÚKDTreeÚgaussianÚtophatÚepanechnikovÚexponentialÚlinearÚcosine)Ú	ball_treeÚkd_treec                   @   s
  e Zd ZU dZeedddd�eddhƒgeee 	¡ ƒdhB ƒgeee
ƒƒgeeejd	d
„ e 	¡ D ƒŽ ƒƒgeedddd�geedddd�gdgeedddd�gdegdœ	Zeed< ddddddddddœ	dd„Zdd„ Zd#dd„Zdd„ Zd$dd„Zd%dd „Zd!d"„ ZdS )&ÚKernelDensitya  Kernel Density Estimation.

    Read more in the :ref:`User Guide <kernel_density>`.

    Parameters
    ----------
    bandwidth : float or {"scott", "silverman"}, default=1.0
        The bandwidth of the kernel. If bandwidth is a float, it defines the
        bandwidth of the kernel. If bandwidth is a string, one of the estimation
        methods is implemented.

    algorithm : {'kd_tree', 'ball_tree', 'auto'}, default='auto'
        The tree algorithm to use.

    kernel : {'gaussian', 'tophat', 'epanechnikov', 'exponential', 'linear',                  'cosine'}, default='gaussian'
        The kernel to use.

    metric : str, default='euclidean'
        Metric to use for distance computation. See the
        documentation of `scipy.spatial.distance
        <https://docs.scipy.org/doc/scipy/reference/spatial.distance.html>`_ and
        the metrics listed in
        :class:`~sklearn.metrics.pairwise.distance_metrics` for valid metric
        values.

        Not all metrics are valid with all algorithms: refer to the
        documentation of :class:`BallTree` and :class:`KDTree`. Note that the
        normalization of the density output is correct only for the Euclidean
        distance metric.

    atol : float, default=0
        The desired absolute tolerance of the result.  A larger tolerance will
        generally lead to faster execution.

    rtol : float, default=0
        The desired relative tolerance of the result.  A larger tolerance will
        generally lead to faster execution.

    breadth_first : bool, default=True
        If true (default), use a breadth-first approach to the problem.
        Otherwise use a depth-first approach.

    leaf_size : int, default=40
        Specify the leaf size of the underlying tree.  See :class:`BallTree`
        or :class:`KDTree` for details.

    metric_params : dict, default=None
        Additional parameters to be passed to the tree for use with the
        metric.  For more information, see the documentation of
        :class:`BallTree` or :class:`KDTree`.

    Attributes
    ----------
    n_features_in_ : int
        Number of features seen during :term:`fit`.

        .. versionadded:: 0.24

    tree_ : ``BinaryTree`` instance
        The tree algorithm for fast generalized N-point problems.

    feature_names_in_ : ndarray of shape (`n_features_in_`,)
        Names of features seen during :term:`fit`. Defined only when `X`
        has feature names that are all strings.

    bandwidth_ : float
        Value of the bandwidth, given directly by the bandwidth parameter or
        estimated using the 'scott' or 'silverman' method.

        .. versionadded:: 1.0

    See Also
    --------
    sklearn.neighbors.KDTree : K-dimensional tree for fast generalized N-point
        problems.
    sklearn.neighbors.BallTree : Ball tree for fast generalized N-point
        problems.

    Examples
    --------
    Compute a gaussian kernel density estimate with a fixed bandwidth.

    >>> from sklearn.neighbors import KernelDensity
    >>> import numpy as np
    >>> rng = np.random.RandomState(42)
    >>> X = rng.random_sample((100, 3))
    >>> kde = KernelDensity(kernel='gaussian', bandwidth=0.5).fit(X)
    >>> log_density = kde.score_samples(X[:3])
    >>> log_density
    array([-1.52955942, -1.51462041, -1.60244657])
    r   NÚneither)ÚclosedÚscottÚ	silvermanÚautoc                 C   s   g | ]}t | ‘qS © r   )Ú.0Úalgr!   r!   úS/var/www/website-v5/atlas_env/lib/python3.8/site-packages/sklearn/neighbors/_kde.pyÚ
<listcomp>‹   s     zKernelDensity.<listcomp>ÚleftÚbooleanr   )	Ú	bandwidthÚ	algorithmÚkernelÚmetricÚatolÚrtolÚbreadth_firstÚ	leaf_sizeÚmetric_paramsÚ_parameter_constraintsç      ð?r   Ú	euclideanTé(   c       	   
      C   s:   || _ || _|| _|| _|| _|| _|| _|| _|	| _d S )N)	r)   r(   r*   r+   r,   r-   r.   r/   r0   )
Úselfr(   r)   r*   r+   r,   r-   r.   r/   r0   r!   r!   r$   Ú__init__•   s    zKernelDensity.__init__c                 C   sP   |dkr&|t jkrdS |tjkrLdS n&|t| jkrHtd t| |¡ƒ‚|S d S )Nr    r   r   zinvalid metric for {0}: '{1}')r   Úvalid_metricsr   Ú	TREE_DICTÚ
ValueErrorÚformat)r5   r)   r+   r!   r!   r$   Ú_choose_algorithm¬   s    

ÿzKernelDensity._choose_algorithmc                 C   sò   |   ¡  |  | j| j¡}t| jtƒrŠ| jdkrN|jd d|jd d   | _q’| jdkr’|jd |jd d  d d|jd d   | _n| j| _| j	|dt
d	�}|d
k	rºt||t
dd�}| j}|d
krÌi }t| |f| j| j|dœ|—Ž| _| S )a”  Fit the Kernel Density model on the data.

        Parameters
        ----------
        X : array-like of shape (n_samples, n_features)
            List of n_features-dimensional data points.  Each row
            corresponds to a single data point.

        y : None
            Ignored. This parameter exists only for compatibility with
            :class:`~sklearn.pipeline.Pipeline`.

        sample_weight : array-like of shape (n_samples,), default=None
            List of sample weights attached to the data X.

            .. versionadded:: 0.20

        Returns
        -------
        self : object
            Returns the instance itself.
        r   r   éÿÿÿÿr   é   r   r   ÚC)ÚorderÚdtypeNT)Úonly_non_negative)r+   r/   Úsample_weight)Ú_validate_paramsr;   r)   r+   Ú
isinstancer(   ÚstrÚshapeÚ
bandwidth_Ú_validate_datar   r
   r0   r8   r/   Útree_)r5   ÚXÚyrB   r)   Úkwargsr!   r!   r$   Úfit¼   s>    
 
ÿ   ÿÿüûzKernelDensity.fitc              	   C   s|   t | ƒ | j|dtdd�}| jjdkr6| jjjd }n| jj}| j| }| jj	|| j
| j|| j| jdd�}|t |¡8 }|S )a  Compute the log-likelihood of each sample under the model.

        Parameters
        ----------
        X : array-like of shape (n_samples, n_features)
            An array of points to query.  Last dimension should match dimension
            of training data (n_features).

        Returns
        -------
        density : ndarray of shape (n_samples,)
            Log-likelihood of each sample in `X`. These are normalized to be
            probability densities, so values will be low for high-dimensional
            data.
        r>   F)r?   r@   ÚresetNr   T)Úhr*   r,   r-   r.   Ú
return_log)r   rH   r   rI   rB   ÚdatarF   Ú
sum_weightr,   Úkernel_densityrG   r*   r-   r.   ÚnpÚlog)r5   rJ   ÚNZatol_NZlog_densityr!   r!   r$   Úscore_samplesô   s"    
ù	zKernelDensity.score_samplesc                 C   s   t  |  |¡¡S )a}  Compute the total log-likelihood under the model.

        Parameters
        ----------
        X : array-like of shape (n_samples, n_features)
            List of n_features-dimensional data points.  Each row
            corresponds to a single data point.

        y : None
            Ignored. This parameter exists only for compatibility with
            :class:`~sklearn.pipeline.Pipeline`.

        Returns
        -------
        logprob : float
            Total log-likelihood of the data in X. This is normalized to be a
            probability density, so the value will be low for high-dimensional
            data.
        )rT   ÚsumrW   )r5   rJ   rK   r!   r!   r$   Úscore  s    zKernelDensity.scorec                 C   s.  t | ƒ | jdkrtƒ ‚t | jj¡}t|ƒ}|jdd|d�}| jj	dkrb||j
d   tj¡}n,t t | jj	¡¡}|d }t ||| ¡}| jdkr°t | || | j¡¡S | jdk�r*|j
d }	|j||	fd�}
t|
d	d
�}td|	 d| ƒd|	  | j t |¡ }|| |
|dd…tjf   S dS )a�  Generate random samples from the model.

        Currently, this is implemented only for gaussian and tophat kernels.

        Parameters
        ----------
        n_samples : int, default=1
            Number of samples to generate.

        random_state : int, RandomState instance or None, default=None
            Determines random number generation used to generate
            random samples. Pass an int for reproducible results
            across multiple function calls.
            See :term:`Glossary <random_state>`.

        Returns
        -------
        X : array-like of shape (n_samples, n_features)
            List of samples.
        )r   r   r   r   )ÚsizeNr<   r   r   T)Úsquaredg      à?r2   )r   r*   ÚNotImplementedErrorrT   ÚasarrayrI   rQ   r	   ÚuniformrB   rF   ÚastypeÚint64ÚcumsumÚsearchsortedÚ
atleast_2dÚnormalrG   r   r   ÚsqrtÚnewaxis)r5   Ú	n_samplesÚrandom_staterQ   ÚrngÚuÚiZcumsum_weightrR   ÚdimrJ   Ús_sqÚ
correctionr!   r!   r$   Úsample0  s0    


ÿþÿzKernelDensity.samplec                 C   s   dddiiS )NÚ_xfail_checksZcheck_sample_weights_invariancez'sample_weight must have positive valuesr!   )r5   r!   r!   r$   Ú
_more_tagse  s
    þÿzKernelDensity._more_tags)NN)N)r   N)Ú__name__Ú
__module__Ú__qualname__Ú__doc__r   r   r   Úsetr8   ÚkeysÚVALID_KERNELSÚ	itertoolsÚchainr   Údictr1   Ú__annotations__r6   r;   rM   rW   rY   ro   rq   r!   r!   r!   r$   r   $   s@   
_
þÿÿðõ
8&

5r   )ru   ry   Únumbersr   r   ÚnumpyrT   Úscipy.specialr   Úbaser   Zneighbors._baser   Úutilsr	   Úutils.validationr
   r   Zutils._param_validationr   r   Zutils.extmathr   Ú
_ball_treer   r   Ú_kd_treer   rx   r8   r   r!   r!   r!   r$   Ú<module>   s*   ú	
