
    :[g"              !          d 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 ddlmZ eZeZ	 	 	 	 	 	 	 	 	 	 	 	 	 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	 	 	 	 	 	 	 d#d	eeef   dededee   dee   dee   dee   dee   dedefd Z	 	 	 	 d$d	edededee   d
ee   dedefd!Zy)%zPlotting Library.    N)BytesIO)AnyOptionalUnion   )PathLike)Booster)XGBModelboosteraxheightxlimylimtitlexlabelylabelfmapimportance_typemax_num_featuresgridshow_valuesvalues_format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 r<t        ||      D ]-  \  }}|j#                  |d
z   ||j%                  |      d       / |j'                  |       |j)                  |       |)t        |t*              rt        |      dk7  rt        d      dt-        |      dz  f}|j/                  |       |)t        |t*              rt        |      dk7  rt        d      dt        |      f}|j1                  |       ||j3                  |       ||j5                  |       ||j7                  |       |j9                  |       |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    K/var/www/html/bid-api/venv/lib/python3.12/site-packages/xgboost/plotting.py<lambda>z!plot_importance.<locals>.<lambda>k       r!u    )keyc                     | d   S r   r   r   s    r!   r"   z!plot_importance.<locals>.<lambda>m   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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_importancerR      s~   @S' '8$((*44+$ 5 

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

 +55*Qq*Q- *F5#$457G6G6HI$45&\NFF	zQ"2IIc&k"EBGGE6C&CFCd&DAqGGAE1m22Q27HGE ' 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 I7	I4#I//I4	num_treesrankdir	yes_colorno_colorcondition_node_paramsleaf_node_paramsc                 4   	 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  }| 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 :
        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'}

    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_attrsrT   edgerU   rV   rW   rX   :)r   dump_format)graphvizrZ   r/   r0   r
   r1   itemsgetjsondumpsget_dump)r   r   rS   rT   rU   rV   rW   rX   r   rZ   rH   
parametersextrar%   valuetreegs                    r!   to_graphvizrk      s   nK# '8$%%' JElln
Uc
 %  "}+2}i(kkm
U::mT*6).F=!#&$&F=!3K $  4v&/v{#%-vz"(*?&'#%5!"c
djj((
:>yIDtAHM  KBCJKs   C= =	DDD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)a5  Plot specified tree.

    Parameters
    ----------
    booster : Booster, XGBModel
        Booster or XGBModel instance
    fmap: str (optional)
       The name of feature map file
    num_trees : int, default 0
        Specify the ordinal number of target tree
    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.
    kwargs :
        Other keywords passed to to_graphviz

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

    r   )image)r.   z(You must install matplotlib to plot treeNr   )r   rS   rT   png)r=   off)
matplotlibrm   r.   r/   r7   rk   r   writepipeseekimreadimshowaxis)r   r   rS   rT   r   r   rm   rG   rH   rN   rj   simgs                r!   	plot_treery      s    <M$, 
zQ"2GW$)WWPVWA	AGGAFF%F !FF1I
,,q/CIIcNGGENI  MDE1LMs   B& &	C /B;;C )Ng?NNzFeature importancezF scoreFeatures weightNTTz{v})r{   r   NNNNN)r{   r   NN)__doc__rc   ior   typingr   r   r   numpyr8   _typingr   corer	   sklearnr
   AxesGraphvizSourcer3   floatr@   strintboolrR   rk   ry   r   r$   r!   <module>r      s'      ' '    

   %#&*@8Wd*+@@ @ 5/	@
 5/@ @ @ @ @ @ sm@ @ @ @ @  
!@J !#",0'+_7H$%_
_ _ c]	_
 }_ sm_ $D>_ tn_ _ _H !00
0 0 c]	0
 	0 0 
0r$   