
    -i                         S r SSKrSSKJrJr  SSKJr  SSKr	SSK
Jr  SSKJr  SSKJrJrJr  SS	KJr  SS
KJr  SSKJr   " S S5      r " S S5      r  SS jrg)z
This module contains the TreeGrower class.

TreeGrower builds a regression tree fitting a Newton-Raphson step, based on
the gradients and hessians of the training data.
    N)heappopheappush)default_timer)_openmp_effective_n_threads   )!set_raw_bitset_from_binned_bitset)PREDICTOR_RECORD_DTYPEX_BITSET_INNER_DTYPEMonotonicConstraint)HistogramBuilder)TreePredictor)Splitterc                   2    \ rS rSrSrSS.S jrS rS rSrg)	TreeNode   a  Tree Node class used in TreeGrower.

This isn't used for prediction purposes, only for training (see
TreePredictor).

Parameters
----------
depth : int
    The depth of the node, i.e. its distance from the root.
sample_indices : ndarray of shape (n_samples_at_node,), dtype=np.uint32
    The indices of the samples at the node.
partition_start : int
    start position of the node's sample_indices in splitter.partition.
partition_stop : int
    stop position of the node's sample_indices in splitter.partition.
sum_gradients : float
    The sum of the gradients of the samples at the node.
sum_hessians : float
    The sum of the hessians of the samples at the node.

Attributes
----------
depth : int
    The depth of the node, i.e. its distance from the root.
sample_indices : ndarray of shape (n_samples_at_node,), dtype=np.uint32
    The indices of the samples at the node.
sum_gradients : float
    The sum of the gradients of the samples at the node.
sum_hessians : float
    The sum of the hessians of the samples at the node.
split_info : SplitInfo or None
    The result of the split evaluation.
is_leaf : bool
    True if node is a leaf
left_child : TreeNode or None
    The left child of the node. None for leaves.
right_child : TreeNode or None
    The right child of the node. None for leaves.
value : float or None
    The value of the leaf, as computed in finalize_leaf(). None for
    non-leaf nodes.
partition_start : int
    start position of the node's sample_indices in splitter.partition.
partition_stop : int
    stop position of the node's sample_indices in splitter.partition.
allowed_features : None or ndarray, dtype=int
    Indices of features allowed to split for children.
interaction_cst_indices : None or list of ints
    Indices of the interaction sets that have to be applied on splits of
    child nodes. The fewer sets the stronger the constraint as fewer sets
    contain fewer features.
children_lower_bound : float
children_upper_bound : float
N)valuec                *   Xl         X l        UR                  S   U l        XPl        X`l        Xpl        SU l        S U l        S U l	        U R                  [        S5      [        S5      5        S U l        S U l        S U l        S U l        X0l        X@l        g )Nr   Fz-infz+inf)depthsample_indicesshape	n_samplessum_gradientssum_hessiansr   is_leafallowed_featuresinteraction_cst_indicesset_children_boundsfloat
split_info
left_childright_child
histogramspartition_startpartition_stop)selfr   r   r#   r$   r   r   r   s           b/var/www/html/venv/lib/python3.13/site-packages/sklearn/ensemble/_hist_gradient_boosting/grower.py__init__TreeNode.__init__V   s     
,'--a0*(
 $'+$  vf>  /,    c                     Xl         X l        g)z<Set children values bounds to respect monotonic constraints.N)children_lower_boundchildren_upper_bound)r%   loweruppers      r&   r   TreeNode.set_children_boundsz   s     %*!$)!r)   c                 \    U R                   R                  UR                   R                  :  $ )a#  Comparison for priority queue.

Nodes with high gain are higher priority than nodes with low gain.

heapq.heappush only need the '<' operator.
heapq.heappop take the smallest item first (smaller is higher
priority).

Parameters
----------
other_node : TreeNode
    The node to compare with.
)r   gain)r%   
other_nodes     r&   __lt__TreeNode.__lt__   s%     ##j&;&;&@&@@@r)   )r   r+   r,   r   r"   r   r   r    r   r#   r$   r!   r   r   r   r   r   )	__name__
__module____qualname____firstlineno____doc__r'   r   r3   __static_attributes__ r)   r&   r   r      s    5@ "-H*Ar)   r   c                       \ rS rSrSrSSSSSSSSSSSSS	\R                  R                  5       S	S4S
 jrS r	S r
S rS rS rS rS rS rS rS rSrg)
TreeGrower   a;  Tree grower class used to build a tree.

The tree is fitted to predict the values of a Newton-Raphson step. The
splits are considered in a best-first fashion, and the quality of a
split is defined in splitting._split_gain.

Parameters
----------
X_binned : ndarray of shape (n_samples, n_features), dtype=np.uint8
    The binned input samples. Must be Fortran-aligned.
gradients : ndarray of shape (n_samples,)
    The gradients of each training sample. Those are the gradients of the
    loss w.r.t the predictions, evaluated at iteration ``i - 1``.
hessians : ndarray of shape (n_samples,)
    The hessians of each training sample. Those are the hessians of the
    loss w.r.t the predictions, evaluated at iteration ``i - 1``.
max_leaf_nodes : int, default=None
    The maximum number of leaves for each tree. If None, there is no
    maximum limit.
max_depth : int, default=None
    The maximum depth of each tree. The depth of a tree is the number of
    edges to go from the root to the deepest leaf.
    Depth isn't constrained by default.
min_samples_leaf : int, default=20
    The minimum number of samples per leaf.
min_gain_to_split : float, default=0.
    The minimum gain needed to split a node. Splits with lower gain will
    be ignored.
min_hessian_to_split : float, default=1e-3
    The minimum sum of hessians needed in each node. Splits that result in
    at least one child having a sum of hessians less than
    ``min_hessian_to_split`` are discarded.
n_bins : int, default=256
    The total number of bins, including the bin for missing values. Used
    to define the shape of the histograms.
n_bins_non_missing : ndarray, dtype=np.uint32, default=None
    For each feature, gives the number of bins actually used for
    non-missing values. For features with a lot of unique values, this
    is equal to ``n_bins - 1``. If it's an int, all features are
    considered to have the same number of bins. If None, all features
    are considered to have ``n_bins - 1`` bins.
has_missing_values : bool or ndarray, dtype=bool, default=False
    Whether each feature contains missing values (in the training data).
    If it's a bool, the same value is used for all features.
is_categorical : ndarray of bool of shape (n_features,), default=None
    Indicates categorical features.
monotonic_cst : array-like of int of shape (n_features,), dtype=int, default=None
    Indicates the monotonic constraint to enforce on each feature.
      - 1: monotonic increase
      - 0: no constraint
      - -1: monotonic decrease

    Read more in the :ref:`User Guide <monotonic_cst_gbdt>`.
interaction_cst : list of sets of integers, default=None
    List of interaction constraints.
l2_regularization : float, default=0.
    The L2 regularization parameter penalizing leaves with small hessians.
    Use ``0`` for no regularization (default).
feature_fraction_per_split : float, default=1
    Proportion of randomly chosen features in each and every node split.
    This is a form of regularization, smaller values make the trees weaker
    learners and might prevent overfitting.
rng : Generator
    Numpy random Generator used for feature subsampling.
shrinkage : float, default=1.
    The shrinkage parameter to apply to the leaves values, also known as
    learning rate.
n_threads : int, default=None
    Number of OpenMP threads to use. `_openmp_effective_n_threads` is called
    to determine the effective number of threads use, which takes cgroups CPU
    quotes into account. See the docstring of `_openmp_effective_n_threads`
    for details.

Attributes
----------
histogram_builder : HistogramBuilder
splitter : Splitter
root : TreeNode
finalized_leaves : list of TreeNode
splittable_nodes : list of TreeNode
missing_values_bin_idx : int
    Equals n_bins - 1
n_categorical_splits : int
n_features : int
n_nodes : int
total_find_split_time : float
    Time spent finding the best splits
total_compute_hist_time : float
    Time spent computing histograms
total_apply_split_time : float
    Time spent splitting nodes
with_monotonic_cst : bool
    Whether there are monotonic constraints that apply. False iff monotonic_cst is
    None.
N           gMbP?   Fg      ?c                 &   U R                  UUU5        [        U5      nU
c  U	S-
  n
[        U
[        R                  5      (       a5  [
        R                  " U
/UR                  S   -  [
        R                  S9n
O#[
        R                  " U
[
        R                  S9n
[        U[        5      (       a  U/UR                  S   -  n[
        R                  " U[
        R                  S9nUc@  [
        R                  " UR                  S   [        R                  [
        R                  S9nO#[
        R                  " U[
        R                  S9n[
        R                   " U[        R                  :g  5      U l        Uc1  [
        R$                  " UR                  S   [
        R                  S9nO#[
        R                  " U[
        R                  S9n[
        R                   " [
        R&                  " US:H  U[        R                  :g  5      5      (       a  [)        S5      eUR                  S   S:H  n[+        XX#UU5      U l        U	S-
  n[/        UU
UUUUUUUUUUUUS9U l        Xl        X@l        XPl        X`l        Xpl        Xl        UU l        Xl         Xl!        Xl"        Xl#        Xl$        UU l%        UR                  S   U l&        UU l'        / U l(        / U l)        SU l*        SU l+        SU l,        SU l-        U R]                  5         SU l/        g )	Nr   dtype)r   
fill_valuerD   )r   rD   z7Categorical features cannot have monotonic constraints.r   )X_binnedn_bins_non_missingmissing_values_bin_idxhas_missing_valuesis_categoricalmonotonic_cstl2_regularizationmin_hessian_to_splitmin_samples_leafmin_gain_to_splithessians_are_constantfeature_fraction_per_splitrng	n_threadsr@   )0_validate_parametersr   
isinstancenumbersIntegralnparrayr   uint32asarraybooluint8fullr   NO_CSTint8anywith_monotonic_cstzeroslogical_and
ValueErrorr   histogram_builderr   splitterrF   max_leaf_nodes	max_depthrN   rO   rG   rH   rI   rJ   rK   interaction_cstrL   	shrinkage
n_featuresrS   splittable_nodesfinalized_leavestotal_find_split_timetotal_compute_hist_timetotal_apply_split_timen_categorical_splits_initialize_rootn_nodes)r%   rF   	gradientshessiansrh   ri   rN   rO   rM   n_binsrG   rI   rJ   rK   rj   rL   rQ   rR   rk   rS   rP   rH   s                         r&   r'   TreeGrower.__init__   s   , 	!! 	

 0	:	%!'!('*:*:;;!##$x~~a'88		" "$,>bii!P($//"4!5q8I!IZZ(:"((K
  GGnnQ'.55ggM JJ}BGGDM"$&&:M:T:T)T"U!XXHNN1,=RXXNNZZbhhGN66NN!#]6I6P6P%P
 

 VWW (q 1Q 6!1i3H)"
 "(! 1#91)'/!5-/"7'A
  !," 0!2"4&<#"4,*.!2""..+" " "%("'*$&)#$%!r)   c                 "   UR                   [        R                  :w  a  [        S5      eUR                  R
                  (       d  [        S5      eUS:  a  [        SR                  U5      5      eUS:  a  [        SR                  U5      5      eg)zVValidate parameters passed to __init__.

Also validate parameters passed to splitter.
zX_binned must be of type uint8.zMX_binned should be passed as Fortran contiguous array for maximum efficiency.r   z&min_gain_to_split={} must be positive.z)min_hessian_to_split={} must be positive.N)rD   rX   r]   NotImplementedErrorflagsf_contiguousre   format)r%   rF   rO   rM   s       r&   rT   TreeGrower._validate_parametersf  s     >>RXX%%&GHH~~**0  q 8??@QR   !#;BBCWX  $r)   c                     U R                   (       a#  U R                  5         U R                   (       a  M#  U R                  5         g)z#Grow the tree, from root to leaves.N)rm   
split_next_apply_shrinkage)r%   s    r&   growTreeGrower.grow  s1    ##OO ### 	r)   c                 h    U R                    H"  nU=R                  U R                  -  sl        M$     g)av  Multiply leaves values by shrinkage parameter.

This must be done at the very end of the growing process. If this were
done during the growing process e.g. in finalize_leaf(), then a leaf
would be shrunk but its sibling would potentially not be (if it's a
non-leaf), which would lead to a wrong computation of the 'middle'
value needed to enforce the monotonic constraints.
N)rn   r   rk   )r%   leafs     r&   r   TreeGrower._apply_shrinkage  s&     ))DJJ$..(J *r)   c           
      "   [        5       nU R                  bT  [        5       R                  " U R                  6 n[        R
                  " U[        R                  [        U5      S9nUS   nOSnSnU R                  R                  U R                  R                  U5      nU =R                  [        5       U-
  -  sl        [        5       nU R                  R                  S   nSn[        R                  " XC   5      nUS   R!                  5       nU R                  R"                  (       a  U R                  R$                  S   U-  n	OUS   R!                  5       n	['        UU R                  R                  SUUU	SS9U l        U R(                  R*                  SU R,                  -  :  a  U R/                  U R(                  5        gXR                  R0                  :  a  U R/                  U R(                  5        gU R                  b=  [3        [        U R                  5      5      U R(                  l        X R(                  l        X@R(                  l        U R;                  U R(                  5        U =R<                  [        5       U-
  -  sl        g)z/Initialize root node and finalize it if needed.NrD   countr   r   r   r   r   r#   r$   r   r   r      )timerj   setunionrX   fromiterrZ   lenrf   compute_histograms_bruterg   	partitionrp   rF   r   r[   sumrP   rv   r   rootr   rN   _finalize_leafrM   ranger   r   r"   _compute_best_split_and_pushro   )
r%   ticr   arbitrary_featurer"   r   r   histogram_arrayr   r   s
             r&   rs   TreeGrower._initialize_root  s   f+"u{{D,@,@A!{{ 		=M9N  !1 3# ! ++DDMM##

 	$$4$fMM''*	**Z%BC'8<<>!!7711::1=	IL*>:>>@L==22$'%
	 99T%:%:!::		*--<<<		*+05c$:N:N6O0PDII-)9II&)		))$))4""dfsl2"r)   c                 r   U R                   R                  UR                  UR                  UR                  UR
                  UR                  UR                  UR                  UR                  S9Ul
        UR                  R                  S::  a  U R                  U5        g[        U R                  U5        g)a5  Compute the best possible split (SplitInfo) of a given node.

Also push it in the heap of splittable nodes if gain isn't zero.
The gain of a node is 0 if either all the leaves are pure
(best gain = 0), or if no split would satisfy the constraints,
(min_hessians_to_split, min_gain_to_split, min_samples_leaf)
)r   r"   r   r   r   lower_boundupper_boundr   r   N)rg   find_node_splitr   r"   r   r   r   r+   r,   r   r   r1   r   r   rm   r%   nodes     r&   r   'TreeGrower._compute_best_split_and_push  s     --77nn,,****1111!22 8 	
 ??1$%T**D1r)   c           
         [        U R                  5      n[        5       nU R                  R	                  UR
                  UR                  5      u  nnnU =R                  [        5       U-
  -  sl        UR                  S-   n[        U R                  5      [        U R                  5      -   nUS-  n[        UUUR                  UR                  U-   UR
                  R                  UR
                  R                  UR
                  R                  S9n[        UUUR                   UR                   UR
                  R"                  UR
                  R$                  UR
                  R&                  S9n	Xl        Xl        U R,                  b@  U R/                  U5      u  Ul        Ul        UR2                  U	l        UR0                  U	l        U R4                  UR
                  R6                     (       d(  UR8                  U	R8                  :  UR
                  l        U =R<                  S-  sl        U =R>                  UR
                  R@                  -  sl        U RB                  bD  XpRB                  :X  a5  U RE                  U5        U RE                  U	5        U RG                  5         X4$ U RH                  b4  X`RH                  :X  a%  U RE                  U5        U RE                  U	5        X4$ UR8                  U RJ                  S-  :  a  U RE                  U5        U	R8                  U RJ                  S-  :  a  U RE                  U	5        U RL                  (       a  U RN                  UR
                  R6                     [P        RR                  :X  a  URT                  =pURV                  =pOURX                  U	RX                  -   S-  nU RN                  UR
                  R6                     [P        RZ                  :X  a  URT                  UpXRV                  pOXRV                  pURT                  UpUR]                  X5        U	R]                  X5        UR^                  (       + nU	R^                  (       + nU(       d  U(       Ga`  UR                  R`                  S   nU	R                  R`                  S   nUU:  a  UnU	nOU	nUn[        5       nU Rb                  Re                  UR                  UR0                  5      Ul3        U Rb                  Ri                  URf                  URf                  UR0                  5      Ul3        SUl3        U =Rj                  [        5       U-
  -  sl5        [        5       nU(       a  U Rm                  U5        U(       a  U Rm                  U	5        U =Rn                  [        5       U-
  -  sl7        X4 H  nUR^                  (       d  M  U?3M     U?3X4$ )zSplit the node with highest potential gain.

Returns
-------
left : TreeNode
    The resulting left child.
right : TreeNode
    The resulting right child.
r   r   r   Nr   )8r   rm   r   rg   split_indicesr   r   rq   r   r   rn   r   r#   sum_gradient_leftsum_hessian_left
value_leftr$   sum_gradient_rightsum_hessian_rightvalue_rightr!   r    rj   _compute_interactionsr   r   rI   feature_idxr   missing_go_to_leftrt   rr   rJ   rh   r   _finalize_splittable_nodesri   rN   rb   rK   r   r_   r+   r,   r   POSr   r   r   rf   r   r"   compute_histograms_subtractionrp   r   ro   )r%   r   r   sample_indices_leftsample_indices_rightright_child_posr   n_leaf_nodesleft_child_noderight_child_node
lower_leftlower_right
upper_leftupper_rightmidshould_split_leftshould_split_rightn_samples_leftn_samples_rightsmallest_childlargest_childchilds                         r&   r   TreeGrower.split_next  s    t,,-f
 MM''9L9LM		
 ##tv|3#

Q4001C8M8M4NN". 00///A//;;99//,,
 $/+::..//<<:://--
 ,) + **4007  77 4 1@0P0P-&&t'B'BC
  )),<,F,FF OO. 	!!T__%C%CC!*|?R?R/R0 01++-"44>>%%>>*A0 01"44$$t'<'<q'@@0%%(=(=(AA 01"" ""4??#>#>?&--. ,0+D+DD
+/+D+DD
[&,,/?/E/EEJ&&t'B'BC*../ .2-F-F
/24M4M-02K2K
/3/H/H#//
G00J !0 7 77!1!9!99 2 -;;AA!DN.==CCAFO/!0 0!1 / &C(,(>(>(W(W--~/N/N)N% &&EEOO"--"33 $ #DO((DFSL8(&C 11/B!112BC&&$&3,6& *<===( = O00r)   c                 N   [        5       n/ nUR                   H[  nUR                  R                  U R                  U   ;   d  M,  UR                  U5        UR                  U R                  U   5        M]     [        R                  " U[        R                  [        U5      S9U4$ )a  Compute features allowed by interactions to be inherited by child nodes.

Example: Assume constraints [{0, 1}, {1, 2}].
   1      <- Both constraint groups could be applied from now on
  / \
 1   2    <- Left split still fulfills both constraint groups.
/ \ / \      Right split at feature 2 has only group {1, 2} from now on.

LightGBM uses the same logic for overlapping groups. See
https://github.com/microsoft/LightGBM/issues/4481 for details.

Parameters:
----------
node : TreeNode
    A node that might have children. Based on its feature_idx, the interaction
    constraints for possible child nodes are computed.

Returns
-------
allowed_features : ndarray, dtype=uint32
    Indices of features allowed to split for children.
interaction_cst_indices : list of ints
    Indices of the interaction sets that have to be applied on splits of
    child nodes. The fewer sets the stronger the constraint as fewer sets
    contain fewer features.
r   )r   r   r   r   rj   appendupdaterX   r   rZ   r   )r%   r   r   r   is        r&   r    TreeGrower._compute_interactions  s    > 5"$--A**d.B.B1.EE'..q1 ''(<(<Q(?@ .
 KK(		EUAVW#
 	
r)   c                 H    SUl         U R                  R                  U5        g)z)Make node a leaf of the tree being grown.TN)r   rn   r   r   s     r&   r   TreeGrower._finalize_leaf  s     $$T*r)   c                     [        U R                  5      S:  aG  U R                  R                  5       nU R                  U5        [        U R                  5      S:  a  MF  gg)z}Transform all splittable nodes into leaves.

Used when some constraint is met e.g. maximum number of leaves or
maximum depth.r   N)r   rm   popr   r   s     r&   r   %TreeGrower._finalize_splittable_nodes  sN    
 $''(1,((,,.D% $''(1,r)   c                 <   [         R                  " U R                  [        S9n[         R                  " U R                  S4[
        S9n[         R                  " U R                  S4[
        S9n[        UUUU R                  UU R                  5        [        X#U5      $ )at  Make a TreePredictor object out of the current tree.

Parameters
----------
binning_thresholds : array-like of floats
    Corresponds to the bin_thresholds_ attribute of the BinMapper.
    For each feature, this stores:

    - the bin frontiers for continuous features
    - the unique raw category values for categorical features

Returns
-------
A TreePredictor object.
rC      )
rX   rc   rt   r	   rr   r
   _fill_predictor_arraysr   rG   r   )r%   binning_thresholdspredictor_nodesbinned_left_cat_bitsetsraw_left_cat_bitsetss        r&   make_predictorTreeGrower.make_predictor  s      ((4<<7MN"$((&&*2F#
  "xx&&*2F 
 	# II##	
 6J
 	
r)   )rF   rn   rI   rf   rj   rJ   rL   ri   rh   rO   rN   rH   rK   rG   rr   rl   rt   rS   r   rk   rm   rg   rq   rp   ro   rb   )r5   r6   r7   r8   r9   rX   randomdefault_rngr'   rT   r   r   rs   r   r   r   r   r   r   r:   r;   r)   r&   r=   r=      s    ^J ! #&II!!#)ob4 
)93v22d1L(
T+&!
r)   r=   c                     X   nUR                   US'   UR                  US'   UR                  b  UR                  R                  US'   OSUS'   UR                  US'   UR
                  (       a  SUS'   US-   U4$ UR                  n	U	R                  U	R                  pXS	'   XS
'   U	R                  US'   U	R                  US'   U	R                  XZ   S-
  :X  a  [        R                  US'   OPU	R                  (       a5  XJ   nXxS'   U	R                  X'   [        X'   U	R                  U5        US-  nO
XJ   U   US'   US-  nXhS'   [        U UUUR                  UUUUS9u  pgXhS'   [        U UUUR                   UUUUS9$ )z>Helper used in make_predictor to set the TreePredictor fields.r   r   r1   r   Tr   r   r   bin_thresholdr   rJ   num_threshold
bitset_idxleft)r   rG   next_free_node_idxnext_free_bitset_idxright)r   r   r   r1   r   r   r   bin_idxr   rJ   rX   infleft_cat_bitsetr   r   r    r!   )r   r   r   grower_noder   rG   r   r   r   r   r   r   
categoriess                r&   r   r     s    .D))DM%%DM)"--22VV%%DMY!A%';;;''J%11:3E3E%#!+!>!>D	'66D	/<q@@ !#_		"	"'4
1\8B8R8R5) 6&&	

 	! 2 ? H_!%L/E---1	0, 'M!---1	 	r)   )r   r   )r9   rV   heapqr   r   timeitr   r   numpyrX   sklearn.utils._openmp_helpersr   _bitsetr   commonr	   r
   r   	histogramr   	predictorr   	splittingr   r   r=   r   r;   r)   r&   <module>r      s]     # (  E 6 
 ( $ sA sAlS	
 S	
z Kr)   