
    ^iI'              "          d Z ddlZddlZddlmZ ddlmZmZmZ ddl	Z
ddlmZ ddlmZmZ ddlmZ eZeZedd	ddd
ddddddddddeeeef   dee   dedee   dee   dedededededee   dededed ed!ef d"       Zedddddddd#dd$	deeef   ded%ee   d&ee   d'ee   d(ee   d)ee   d*ee   d+ed,ed ed!efd-       Zeddddd#dd.deeef   ded%ee   d&ee   dee   d+ed,ed ed!efd/       Zy)0zPlotting Library.    N)BytesIO)AnyOptionalUnion   )PathLike)Booster_deprecate_positional_args)XGBModelg?zFeature importancezImportance scoreFeatures weightTz{v})axheightxlimylimtitlexlabelylabelfmapimportance_typemax_num_featuresgridshow_valuesvalues_formatboosterr   r   r   r   r   r   r   r   r   r   r   r   r   kwargsreturnc                
   	 ddl m} t        | t              r"| j                         j                  |	|      }nBt        | t              r| j                  |	|      }nt        | t              r| }nt        d      |st        d      |D cg c]	  }|||   f }}|
t        |d       |
 d }nt        |d	       }t        | \  }}||j                  d
d
      \  }}t        j                  t        |            } |j                   ||fd|d| |du rEt        ||      D ]6  \  }}|j#                  |d
z   t%        |      |j'                  |      d       8 |j)                  |       |j+                  |       |)t        |t,              rt        |      dk7  rt        d      dt/        |      dz  f}|j1                  |       |)t        |t,              rt        |      dk7  rt        d      dt        |      f}|j3                  |       ||j5                  |       ||j7                  |       ||j9                  |       |j;                  |       |S # t        $ r}t        d      |d}~ww xY wc c}w )a  Plot importance based on fitted trees.

    Parameters
    ----------
    booster :
        Booster or XGBModel instance, or dict taken by Booster.get_fscore()
    ax : matplotlib Axes
        Target axes instance. If None, new figure and axes will be created.
    grid :
        Turn the axes grids on or off.  Default is True (On).
    importance_type :
        How the importance is calculated: either "weight", "gain", or "cover"

        * "weight" is the number of times a feature appears in a tree
        * "gain" is the average gain of splits which use the feature
        * "cover" is the average coverage of splits which use the feature
          where coverage is defined as the number of samples affected by the split
    max_num_features :
        Maximum number of top features displayed on plot. If None, all features will be
        displayed.
    height :
        Bar height, passed to ax.barh()
    xlim :
        Tuple passed to axes.xlim()
    ylim :
        Tuple passed to axes.ylim()
    title :
        Axes title. To disable, pass None.
    xlabel :
        X axis title label. To disable, pass None.
    ylabel :
        Y axis title label. To disable, pass None.
    fmap :
        The name of feature map file.
    show_values :
        Show values on plot. To disable, pass False.
    values_format :
        Format string for values. "v" will be replaced by the value of the feature
        importance.  e.g. Pass "{v:.2f}" in order to limit the number of digits after
        the decimal point to two, for each value printed on the graph.
    kwargs :
        Other keywords passed to ax.barh()

    Returns
    -------
    ax : matplotlib Axes
    r   Nz.You must install matplotlib to plot importance)r   r   z/tree must be Booster, XGBModel or dict instancez_Booster.get_score() results in empty.  This maybe caused by having all trees as decision dumps.c                     | d   S Nr    _xs    Q/var/www/html/hubwallet-dev/venv/lib/python3.12/site-packages/xgboost/plotting.py<lambda>z!plot_importance.<locals>.<lambda>n   
    r!u     )keyc                     | d   S r!   r"   r#   s    r%   r&   z!plot_importance.<locals>.<lambda>p   r'   r(   r   center)alignr   T)v)va   z"xlim must be a tuple of 2 elementsg?z"ylim must be a tuple of 2 elements)matplotlib.pyplotpyplotImportError
isinstancer   get_booster	get_scorer	   dict
ValueErrorsortedzipsubplotsnparangelenbarhtextfloatformat
set_yticksset_yticklabelstuplemaxset_xlimset_ylim	set_title
set_xlabel
set_ylabelr   )r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   plte
importancektupleslabelsvalues_ylocsxys                             r%   plot_importancerW      s   DS' '8$((*44+$ 5 

 
GW	%&&T&R
	GT	"
JKKI
 	

 +55Qq*Q- 5F5#$457G6G6HI$45&\NFF	zQ"2IIc&k"EBGGE6C&CFCd& 	MDAqGGAE58]%9%9A%9%>8GL	M MM%v$&#d)q.ABB3v;$%KK$&#d)q.ABBCK KK
U
f
fGGDMI}  SJKQRRS( 6s   I# J #	I=,I88I=F)	r   	num_treesrankdir	yes_colorno_colorcondition_node_paramsleaf_node_params
with_statstree_idxrX   rY   rZ   r[   r\   r]   r^   r_   c       	            	 ddl m} t        | t              r| j                         } d}i }|
j                         D ]
  \  }}|||<    |i |
d<   ||
d   d<   |j                         D ](  \  }}|
j                  dd      	||
d   |<   ni |
d<   |
|= * ||i |
d<   |||
d   d	<   |||
d   d
<   |||
d<   |||
d<   |
r|dz  }|t        j                  |
      z  }|-t        j                  dt               |	d|fvrt        d      |}	| j                  |||      |	   } ||      }|S # t        $ r}t        d      |d}~ww xY w)a  Convert specified tree to graphviz instance. IPython can automatically plot
    the returned graphviz instance. Otherwise, you should call .render() method
    of the returned graphviz instance.

    Parameters
    ----------
    booster :
        Booster or XGBModel instance
    fmap :
       The name of feature map file
    num_trees :

        .. deprecated:: 3.0

        Specify the ordinal number of target tree

    rankdir :
        Passed to graphviz via graph_attr
    yes_color :
        Edge color when meets the node condition.
    no_color :
        Edge color when doesn't meet the node condition.
    condition_node_params :
        Condition node configuration for for graphviz.  Example:

        .. code-block:: python

            {'shape': 'box',
             'style': 'filled,rounded',
             'fillcolor': '#78bceb'}

    leaf_node_params :
        Leaf node configuration for graphviz. Example:

        .. code-block:: python

            {'shape': 'box',
             'style': 'filled',
             'fillcolor': '#e48038'}

    with_stats :

        .. versionadded:: 3.0

        Controls whether the split statistics should be included.

    tree_idx :

        .. versionadded:: 3.0

        Specify the ordinal index of target tree.

    kwargs :
        Other keywords passed to graphviz graph_attr, e.g. ``graph [ {key} = {value} ]``

    Returns
    -------
    graph: graphviz.Source

    r   )Sourcez&You must install graphviz to plot treeNdotgraph_attrsrY   edgerZ   r[   r\   r]   :zAThe `num_trees` parameter is deprecated, use `tree_idx` insetad. zDBoth `num_trees` and `tree_idx` are used, prefer `tree_idx` instead.)r   dump_formatr^   )graphvizra   r3   r4   r   r5   itemsgetjsondumpswarningswarnFutureWarningr8   get_dump)r   r   rX   rY   rZ   r[   r\   r]   r^   r_   r   ra   rM   
parametersextrar)   valuetreegs                      r%   to_graphvizru      s   VK# '8$%%' JElln 
Uc
  "}+2}i(kkm 
U::mT*6).F=!#&$&F=!3K  4v&/v{#%-vz"(*?&'#%5!"c
djj((
O	
 Ay>)V  :*UD 	tAHi  KBCJKs   D- -	E6EE)r   rX   rY   r   r^   r_   c          	         	 ddl m} ddl m}	 ||	j	                  dd      \  }}t        | f|||||d|}t               }|j                  |j                  d	             |j                  d       |j                  |      }|j                  |       |j                  d
       |S # t        $ r}
t        d      |
d}
~
ww xY w)a  Plot specified tree.

    Parameters
    ----------
    booster :
        Booster or XGBModel instance
    fmap: str (optional)
       The name of feature map file
    num_trees :

        .. deprecated:: 3.0

    rankdir : str, default "TB"
        Passed to graphviz via graph_attr
    ax : matplotlib Axes, default None
        Target axes instance. If None, new figure and axes will be created.

    with_stats :

        .. versionadded:: 3.0

        See :py:func:`to_graphviz`.

    tree_idx :

        .. versionadded:: 3.0

        See :py:func:`to_graphviz`.

    kwargs :
        Other keywords passed to :py:func:`to_graphviz`

    Returns
    -------
    ax : matplotlib Axes

    r   )image)r2   z(You must install matplotlib to plot treeNr   )r   rX   rY   r^   r_   png)rB   off)
matplotlibrw   r2   r3   r;   ru   r   writepipeseekimreadimshowaxis)r   r   rX   rY   r   r^   r_   r   rw   rL   rM   rS   rt   simgs                  r%   	plot_treer     s    bM$, 
zQ"2		 	A 		AGGAFF%F !FF1I
,,q/CIIcNGGENI/  MDE1LMs   B( (	C1B==C)__doc__rj   rl   ior   typingr   r   r   numpyr<   _typingr   corer	   r
   sklearnr   AxesGraphvizSourcer7   rA   rE   strintboolrW   ru   r   r"   r(   r%   <module>r      s       ' '   5 
    %$#&*A8Wd*+A 	A 	A
 5/A 5/A A A A A A smA A A A  !A" 
#A AH  #!#",0'+@7H$%@ @ }	@
 c]@ }@ sm@ $D>@ tn@ @ @ @ @ @F  #!J7H$%J J }	J
 c]J 	J J J J 
J Jr(   