
    >[g^                        d dl Z d dlZd dl mZmZ d dlmZ d dlZd dlm	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mZ dd
lmZ ddlmZmZmZ ddlmZmZ ddlm Z m!Z!m"Z" ddl#m$Z$ ddl%m&Z& dgZ'd Z( G d dee$      Z)d Z*y)    N)IntegralReal)warn)issparse   )OutlierMixin_fit_context)ExtraTreeRegressor)DTYPE)check_arraycheck_random_stategen_batches)get_chunk_n_rows)Interval
RealNotInt
StrOptions)Paralleldelayed)_num_samplescheck_is_fittedvalidate_data   )BaseBagging)_partition_estimatorsIsolationForestc                     ||}n	|dd|f   }| j                  |d      }|5  |||   ||   z   dz
  z  }ddd       y# 1 sw Y   yxY w)z-Parallel computation of isolation tree depth.NF)check_input      ?)apply)	treeXfeaturestree_decision_path_lengthstree_avg_path_lengthsdepthslockX_subsetleaves_indexs	            T/var/www/html/bid-api/venv/lib/python3.12/site-packages/sklearn/ensemble/_iforest.py_parallel_compute_tree_depthsr*      sb     Q[>::hE::L	&|4#L12	
 
s	   ?Ac            
       \    e Zd ZU dZ eeddd      g edh       eeddd       eeddd      g edh       eedd	d      ge eeddd      gd
gedgdgdgd
gd	Z	e
ed<   dddddddddd	 fd
Zd Zd Zd Z ed      d  fd	       Zd Zd Zd Zd Zd Zd Z fdZ xZS )!r   a  
    Isolation Forest Algorithm.

    Return the anomaly score of each sample using the IsolationForest algorithm

    The IsolationForest 'isolates' observations by randomly selecting a feature
    and then randomly selecting a split value between the maximum and minimum
    values of the selected feature.

    Since recursive partitioning can be represented by a tree structure, the
    number of splittings required to isolate a sample is equivalent to the path
    length from the root node to the terminating node.

    This path length, averaged over a forest of such random trees, is a
    measure of normality and our decision function.

    Random partitioning produces noticeably shorter paths for anomalies.
    Hence, when a forest of random trees collectively produce shorter path
    lengths for particular samples, they are highly likely to be anomalies.

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

    .. versionadded:: 0.18

    Parameters
    ----------
    n_estimators : int, default=100
        The number of base estimators in the ensemble.

    max_samples : "auto", int or float, default="auto"
        The number of samples to draw from X to train each base estimator.

        - If int, then draw `max_samples` samples.
        - If float, then draw `max_samples * X.shape[0]` samples.
        - If "auto", then `max_samples=min(256, n_samples)`.

        If max_samples is larger than the number of samples provided,
        all samples will be used for all trees (no sampling).

    contamination : 'auto' or float, default='auto'
        The amount of contamination of the data set, i.e. the proportion
        of outliers in the data set. Used when fitting to define the threshold
        on the scores of the samples.

        - If 'auto', the threshold is determined as in the
          original paper.
        - If float, the contamination should be in the range (0, 0.5].

        .. versionchanged:: 0.22
           The default value of ``contamination`` changed from 0.1
           to ``'auto'``.

    max_features : int or float, default=1.0
        The number of features to draw from X to train each base estimator.

        - If int, then draw `max_features` features.
        - If float, then draw `max(1, int(max_features * n_features_in_))` features.

        Note: using a float number less than 1.0 or integer less than number of
        features will enable feature subsampling and leads to a longer runtime.

    bootstrap : bool, default=False
        If True, individual trees are fit on random subsets of the training
        data sampled with replacement. If False, sampling without replacement
        is performed.

    n_jobs : int, default=None
        The number of jobs to run in parallel for both :meth:`fit` and
        :meth:`predict`. ``None`` means 1 unless in a
        :obj:`joblib.parallel_backend` context. ``-1`` means using all
        processors. See :term:`Glossary <n_jobs>` for more details.

    random_state : int, RandomState instance or None, default=None
        Controls the pseudo-randomness of the selection of the feature
        and split values for each branching step and each tree in the forest.

        Pass an int for reproducible results across multiple function calls.
        See :term:`Glossary <random_state>`.

    verbose : int, default=0
        Controls the verbosity of the tree building process.

    warm_start : bool, default=False
        When set to ``True``, reuse the solution of the previous call to fit
        and add more estimators to the ensemble, otherwise, just fit a whole
        new forest. See :term:`the Glossary <warm_start>`.

        .. versionadded:: 0.21

    Attributes
    ----------
    estimator_ : :class:`~sklearn.tree.ExtraTreeRegressor` instance
        The child estimator template used to create the collection of
        fitted sub-estimators.

        .. versionadded:: 1.2
           `base_estimator_` was renamed to `estimator_`.

    estimators_ : list of ExtraTreeRegressor instances
        The collection of fitted sub-estimators.

    estimators_features_ : list of ndarray
        The subset of drawn features for each base estimator.

    estimators_samples_ : list of ndarray
        The subset of drawn samples (i.e., the in-bag samples) for each base
        estimator.

    max_samples_ : int
        The actual number of samples.

    offset_ : float
        Offset used to define the decision function from the raw scores. We
        have the relation: ``decision_function = score_samples - offset_``.
        ``offset_`` is defined as follows. When the contamination parameter is
        set to "auto", the offset is equal to -0.5 as the scores of inliers are
        close to 0 and the scores of outliers are close to -1. When a
        contamination parameter different than "auto" is provided, the offset
        is defined in such a way we obtain the expected number of outliers
        (samples with decision function < 0) in training.

        .. versionadded:: 0.20

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

        .. versionadded:: 0.24

    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.

        .. versionadded:: 1.0

    See Also
    --------
    sklearn.covariance.EllipticEnvelope : An object for detecting outliers in a
        Gaussian distributed dataset.
    sklearn.svm.OneClassSVM : Unsupervised Outlier Detection.
        Estimate the support of a high-dimensional distribution.
        The implementation is based on libsvm.
    sklearn.neighbors.LocalOutlierFactor : Unsupervised Outlier Detection
        using Local Outlier Factor (LOF).

    Notes
    -----
    The implementation is based on an ensemble of ExtraTreeRegressor. The
    maximum depth of each tree is set to ``ceil(log_2(n))`` where
    :math:`n` is the number of samples used to build the tree
    (see (Liu et al., 2008) for more details).

    References
    ----------
    .. [1] Liu, Fei Tony, Ting, Kai Ming and Zhou, Zhi-Hua. "Isolation forest."
           Data Mining, 2008. ICDM'08. Eighth IEEE International Conference on.
    .. [2] Liu, Fei Tony, Ting, Kai Ming and Zhou, Zhi-Hua. "Isolation-based
           anomaly detection." ACM Transactions on Knowledge Discovery from
           Data (TKDD) 6.1 (2012): 3.

    Examples
    --------
    >>> from sklearn.ensemble import IsolationForest
    >>> X = [[-1.1], [0.3], [0.5], [100]]
    >>> clf = IsolationForest(random_state=0).fit(X)
    >>> clf.predict([[0.1], [0], [90]])
    array([ 1,  1, -1])

    For an example of using isolation forest for anomaly detection see
    :ref:`sphx_glr_auto_examples_ensemble_plot_isolation_forest.py`.
    r   Nleft)closedautor   rightg      ?booleanrandom_stateverbose)	n_estimatorsmax_samplescontaminationmax_features	bootstrapn_jobsr1   r2   
warm_start_parameter_constraintsd   r   Fc       	         F    t         
|   d |d||||	|||
       || _        y )NF)
	estimatorr7   bootstrap_featuresr3   r4   r6   r9   r8   r1   r2   )super__init__r5   )selfr3   r4   r5   r6   r7   r8   r1   r2   r9   	__class__s             r)   r@   zIsolationForest.__init__   s?     	$%#%!% 	 	
 +    c                 2    t        dd| j                        S )Nr   random)r6   splitterr1   )r
   r1   rA   s    r)   _get_estimatorzIsolationForest._get_estimator  s    !**	
 	
rC   c                     t        d      )Nz"OOB score not supported by iforest)NotImplementedError)rA   r!   ys      r)   _set_oob_scorezIsolationForest._set_oob_score  s    !"FGGrC   c                 
    ddiS )Npreferthreads rG   s    r)   _parallel_argszIsolationForest._parallel_args!  s    
 )$$rC   T)prefer_skip_nested_validationc           
         t        | |dgt        d      }t        |      r|j                          t	        | j
                        }|j                  |j                  d         }|j                  d   }t        | j                  t              r| j                  dk(  rt        d|      }nt        | j                  t        j                        r;| j                  |kD  rt        d| j                  d	|d
       |}n2| j                  }n%t        | j                  |j                  d   z        }|| _        t        t#        j$                  t#        j&                  t)        |d                        }t*        	| Y  |||||d       t/        | j0                  D cg c];  }t3        |j4                  j6                        |j4                  j9                         f= c} \  | _        | _        | j>                  dk(  r	d| _         | S t        |      r|jC                         }t#        jD                  | jG                  |      d| j>                  z        | _         | S c c}w )a  
        Fit estimator.

        Parameters
        ----------
        X : {array-like, sparse matrix} of shape (n_samples, n_features)
            The input samples. Use ``dtype=np.float32`` for maximum
            efficiency. Sparse matrices are also supported, use sparse
            ``csc_matrix`` for maximum efficiency.

        y : Ignored
            Not used, present for API consistency by convention.

        sample_weight : array-like of shape (n_samples,), default=None
            Sample weights. If None, then samples are equally weighted.

        Returns
        -------
        self : object
            Fitted estimator.
        cscF)accept_sparsedtypeensure_all_finiter   )sizer.      zmax_samples (z/) is greater than the total number of samples (z7). max_samples will be set to n_samples for estimation.r   )	max_depthsample_weightr   g      g      Y@)$r   
tree_dtyper   sort_indicesr   r1   uniformshape
isinstancer4   strminnumbersr   r   intmax_samples_npceillog2maxr?   _fitzipestimators__average_path_lengthtree_n_node_samplescompute_node_depths_average_path_length_per_tree_decision_path_lengthsr5   offset_tocsr
percentile_score_samples)
rA   r!   rK   r[   rnd	n_samplesr4   rZ   r    rB   s
            r)   fitzIsolationForest.fit(  s   . !E7*PU
 A; NN !2!23KKQWWQZK( GGAJ	d&&,1A1AV1Kc9-K(('*:*:;)+ ''4 ("..d..;<K'K(; <=>	' 	 	
 KN !,,
 -D ))B)BCJJ224 -K
G*D,G '  DLK A;	A}}T%8%8%;UTEWEW=WX/s   A Ic                     t        |        | j                  |      }t        j                  |t              }d||dk  <   |S )a3  
        Predict if a particular sample is an outlier or not.

        Parameters
        ----------
        X : {array-like, sparse matrix} of shape (n_samples, n_features)
            The input samples. Internally, it will be converted to
            ``dtype=np.float32`` and if a sparse matrix is provided
            to a sparse ``csr_matrix``.

        Returns
        -------
        is_inlier : ndarray of shape (n_samples,)
            For each observation, tells whether or not (+1 or -1) it should
            be considered as an inlier according to the fitted model.

        Notes
        -----
        The predict method can be parallelized by setting a joblib context. This
        inherently does NOT use the ``n_jobs`` parameter initialized in the class,
        which is used during ``fit``. This is because, predict may actually be faster
        without parallelization for a small number of samples,
        such as for 1000 samples or less. The user can set the
        number of jobs in the joblib context to control the number of parallel jobs.

        .. code-block:: python

            from joblib import parallel_backend

            # Note, we use threading here as the predict method is not CPU bound.
            with parallel_backend("threading", n_jobs=4):
                model.predict(X)
        )rV   r   )r   decision_functionrf   	ones_likerd   )rA   r!   decision_func	is_inliers       r)   predictzIsolationForest.predict  sB    D 	..q1LLc:	')	-!#$rC   c                 >    | j                  |      | j                  z
  S )ah  
        Average anomaly score of X of the base classifiers.

        The anomaly score of an input sample is computed as
        the mean anomaly score of the trees in the forest.

        The measure of normality of an observation given a tree is the depth
        of the leaf containing this observation, which is equivalent to
        the number of splittings required to isolate this point. In case of
        several observations n_left in the leaf, the average path length of
        a n_left samples isolation tree is added.

        Parameters
        ----------
        X : {array-like, sparse matrix} of shape (n_samples, n_features)
            The input samples. Internally, it will be converted to
            ``dtype=np.float32`` and if a sparse matrix is provided
            to a sparse ``csr_matrix``.

        Returns
        -------
        scores : ndarray of shape (n_samples,)
            The anomaly score of the input samples.
            The lower, the more abnormal. Negative scores represent outliers,
            positive scores represent inliers.

        Notes
        -----
        The decision_function method can be parallelized by setting a joblib context.
        This inherently does NOT use the ``n_jobs`` parameter initialized in the class,
        which is used during ``fit``. This is because, calculating the score may
        actually be faster without parallelization for a small number of samples,
        such as for 1000 samples or less.
        The user can set the number of jobs in the joblib context to control the
        number of parallel jobs.

        .. code-block:: python

            from joblib import parallel_backend

            # Note, we use threading here as the decision_function method is
            # not CPU bound.
            with parallel_backend("threading", n_jobs=4):
                model.decision_function(X)
        )score_samplesrs   rA   r!   s     r)   r|   z!IsolationForest.decision_function  s    b !!!$t||33rC   c                 N    t        | |dt        dd      }| j                  |      S )am  
        Opposite of the anomaly score defined in the original paper.

        The anomaly score of an input sample is computed as
        the mean anomaly score of the trees in the forest.

        The measure of normality of an observation given a tree is the depth
        of the leaf containing this observation, which is equivalent to
        the number of splittings required to isolate this point. In case of
        several observations n_left in the leaf, the average path length of
        a n_left samples isolation tree is added.

        Parameters
        ----------
        X : {array-like, sparse matrix} of shape (n_samples, n_features)
            The input samples.

        Returns
        -------
        scores : ndarray of shape (n_samples,)
            The anomaly score of the input samples.
            The lower, the more abnormal.

        Notes
        -----
        The score function method can be parallelized by setting a joblib context. This
        inherently does NOT use the ``n_jobs`` parameter initialized in the class,
        which is used during ``fit``. This is because, calculating the score may
        actually be faster without parallelization for a small number of samples,
        such as for 1000 samples or less.
        The user can set the number of jobs in the joblib context to control the
        number of parallel jobs.

        .. code-block:: python

            from joblib import parallel_backend

            # Note, we use threading here as the score_samples method is not CPU bound.
            with parallel_backend("threading", n_jobs=4):
                model.score(X)
        csrF)rU   rV   resetrW   )r   r\   rv   r   s     r)   r   zIsolationForest.score_samples  s4    V #
 ""1%%rC   c                 <    t        |        | j                  |       S )zPrivate version of score_samples without input validation.

        Input validation would remove feature names, so we disable it.
        )r   _compute_chunked_score_samplesr   s     r)   rv   zIsolationForest._score_samples  s"     	 33A666rC   c                    t        |      }| j                  |j                  d   k(  rd}nd}t        d| j                  z  |      }t	        ||      }t        j                  |d      }|D ]  }| j                  ||   |      ||<    |S )Nr   FT   )	row_bytes
max_n_rowsforder)r   _max_featuresr_   r   r   rf   zeros_compute_score_samples)rA   r!   rx   subsample_featureschunk_n_rowsslicesscoressls           r)   r   z.IsolationForest._compute_chunked_score_samples   s     O	+!&!% (4---)
 Y5)3/B44QrU<NOF2J  rC   c           	         	
 j                   d   }t        j                  |d      	t         j                  g      }t         j                  d      \  }}}t        j                         
 t        | j                  d      	
 fdt        t         j                   j                              D               t         j                        |z  }dt        j                   	|t        j"                  	      |dk7  	       z  }|S )
a  
        Compute the score of each samples in X going through the extra trees.

        Parameters
        ----------
        X : array-like or sparse matrix
            Data matrix.

        subsample_features : bool
            Whether features should be subsampled.

        Returns
        -------
        scores : ndarray of shape (n_samples,)
            The score of each sample in X.
        r   r   r   N	sharedmem)r8   r2   requirec           
   3      K   | ]C  \  }\  }} t        t              |r|nd j                  |   j                  |          E y w)N)r   r*   rr   rq   )	.0tree_idxr    r"   r!   r%   r&   rA   r   s	       r)   	<genexpr>z9IsolationForest._compute_score_samples.<locals>.<genexpr>a  sc      

/**4 3G12.D++H5228</s   A	Ar   )outwhere)r_   rf   r   rm   _max_samplesr   r3   	threadingLockr   r2   	enumeraterk   rl   estimators_features_lendivider}   )rA   r!   r   rx   average_path_length_max_samplesr8   _denominatorr   r%   r&   s   ```      @@r)   r   z&IsolationForest._compute_score_samples@  s    " GGAJ	)3/*>@Q@Q?R*S' -T->->E1~~	
LL	


 /8D$$d&?&?@/

		
& $**+.MM YYf)=[TUEU 
 rC   c                 F    t         |          }d|j                  _        |S )NT)r?   __sklearn_tags__
input_tags	allow_nan)rA   tagsrB   s     r)   r   z IsolationForest.__sklearn_tags__z  s!    w')$(!rC   )NN)__name__
__module____qualname____doc__r   r   r   r   r   r:   dict__annotations__r@   rH   rL   rQ   r	   ry   r   r|   r   rv   r   r   r   __classcell__)rB   s   @r)   r   r   7   s(   iX "(AtFCDx Xq$v6ZAg6
 x T1c'2

 T1a0
  [T"'(; k'$D 2 +:
H% 5X 6Xt&P14f4&l
7@8t rC   c                    t        | d      } | j                  }| j                  d      } t        j                  | j                        }| dk  }| dk(  }t        j
                  ||       }d||<   d||<   dt        j                  | |   dz
        t        j                  z   z  d| |   dz
  z  | |   z  z
  ||<   |j                  |      S )	a  
    The average path length in a n_samples iTree, which is equal to
    the average path length of an unsuccessful BST search since the
    latter has the same structure as an isolation tree.
    Parameters
    ----------
    n_samples_leaf : array-like of shape (n_samples,)
        The number of training samples in each test sample leaf, for
        each estimators.

    Returns
    -------
    average_path_length : ndarray of shape (n_samples,)
    F)	ensure_2d)r   r{   r   r   g        r   g       @)r   r_   reshaperf   r   
logical_orlogeuler_gamma)n_samples_leafn_samples_leaf_shapeaverage_path_lengthmask_1mask_2not_masks         r)   rm   rm     s      !5AN)//#++G4N((>#7#78q Fq Fff--H"%"%rvvnX.45FG
)C/
0>(3K
K	L !
 &&';<<rC   )+rc   r   r   r   warningsr   numpyrf   scipy.sparser   baser   r	   r    r
   
tree._treer   r\   utilsr   r   r   utils._chunkingr   utils._param_validationr   r   r   utils.parallelr   r   utils.validationr   r   r   _baggingr   _baser   __all__r*   r   rm   rP   rC   r)   <module>r      si      "   ! - % , 
 / F F . K K ! (

2F	lK F	R!=rC   