
    -Ph76                         d dl mZ d dlmZmZ d dlmZ  ej        d          Z ej        d          Z	 ej        d          Z
 ej        d          Zdd	d	d	d
 d	d	fdZ G d de          Zd	S )    )OrderedDict)
exceptionsoptional_imports)
graph_objsnumpyscipyzscipy.cluster.hierarchyzscipy.spatialbottomNc                 8    t                               | d          S Ncompleteschlinkagexs    a/var/www/html/test/jupyter/venv/lib/python3.11/site-packages/plotly/figure_factory/_dendrogram.py<lambda>r      s    Q
33     c           
      :   t           rt          rt          st          d          | j        }t          |          dk    rt          j        d           |t          j        j	        }t          | |||||||          }	t          j        |	j        |	j                  S )a[	  
    Function that returns a dendrogram Plotly figure object. This is a thin
    wrapper around scipy.cluster.hierarchy.dendrogram.

    See also https://dash.plot.ly/dash-bio/clustergram.

    :param (ndarray) X: Matrix of observations as array of arrays
    :param (str) orientation: 'top', 'right', 'bottom', or 'left'
    :param (list) labels: List of axis category labels(observation labels)
    :param (list) colorscale: Optional colorscale for the dendrogram tree.
                              Requires 8 colors to be specified, the 7th of
                              which is ignored.  With scipy>=1.5.0, the 2nd, 3rd
                              and 6th are used twice as often as the others.
                              Given a shorter list, the missing values are
                              replaced with defaults and with a longer list the
                              extra values are ignored.
    :param (function) distfun: Function to compute the pairwise distance from
                               the observations
    :param (function) linkagefun: Function to compute the linkage matrix from
                               the pairwise distances
    :param (list[list]) hovertext: List of hovertext for constituent traces of dendrogram
                               clusters
    :param (double) color_threshold: Value at which the separation of clusters will be made

    Example 1: Simple bottom oriented dendrogram

    >>> from plotly.figure_factory import create_dendrogram

    >>> import numpy as np

    >>> X = np.random.rand(10,10)
    >>> fig = create_dendrogram(X)
    >>> fig.show()

    Example 2: Dendrogram to put on the left of the heatmap

    >>> from plotly.figure_factory import create_dendrogram

    >>> import numpy as np

    >>> X = np.random.rand(5,5)
    >>> names = ['Jack', 'Oxana', 'John', 'Chelsea', 'Mark']
    >>> dendro = create_dendrogram(X, orientation='right', labels=names)
    >>> dendro.update_layout({'width':700, 'height':500}) # doctest: +SKIP
    >>> dendro.show()

    Example 3: Dendrogram with Pandas

    >>> from plotly.figure_factory import create_dendrogram

    >>> import numpy as np
    >>> import pandas as pd

    >>> Index= ['A','B','C','D','E','F','G','H','I','J']
    >>> df = pd.DataFrame(abs(np.random.randn(10, 10)), index=Index)
    >>> fig = create_dendrogram(df, labels=Index)
    >>> fig.show()
    zmFigureFactory.create_dendrogram requires scipy,                             scipy.spatial and scipy.hierarchy   z X should be 2-dimensional array.N)distfun
linkagefun	hovertextcolor_threshold)datalayout)scpscsr   ImportErrorshapelenr   PlotlyErrordistancepdist_Dendrogramr   Figurer   r   )
Xorientationlabels
colorscaler   r   r   r   s
dendrograms
             r   create_dendrogramr-      s    H  
c 
 
?
 
 	

 	
A
1vv{{ABBB,$	'	 	 	J */*:KLLLLr   c                   ^    e Zd ZdZdddej        ej        dddd ddfdZd Zd	 Zd
 Z	d Z
dS )r%   z9Refer to FigureFactory.create_dendrogram() for docstring.r	   Nxaxisyaxisc                 8    t                               | d          S r   r   r   s    r   r   z_Dendrogram.<lambda>z   s    S[[J77 r   c           
         || _         || _        || _        || _        g | _        g | _        | j        d| j        di| _        | j        i | j        i i| _        | j         dv rd| j        | j        <   nd| j        | j        <   | j         dv rd| j        | j        <   nd| j        | j        <   |	t          j	        j
        }	|                     |||	|
||          \  }}}}}|| _        || _        |                                }|                                }g | _        t          t          |                    D ]=}||         dk    r/||         | j        vr | j                            ||                    >t          | j                  t          |          dz   k    rt#          t%          | j                            }t#          t'          | j                            }t          ||dz   t#          ||z
  t          |          z                      }d |D             | _        | j                                         |                     ||          | _        || _        d S )N   )leftr	   )rightr	   g        c                     g | ]}|S  r8   ).0vs     r   
<listcomp>z(_Dendrogram.__init__.<locals>.<listcomp>   s    <<<Aa<<<r   )r(   r)   r/   r0   r   leavessignr   r   r#   r$   get_dendrogram_tracesflatten	zero_valsranger!   appendintminmaxsortset_figure_layout)selfr'   r(   r)   r*   widthheightr/   r0   r   r   r   r   	dd_tracesxvalsyvalsordered_labelsr<   
yvals_flat
xvals_flatil_borderr_bordercorrect_leaves_poss                           r   __init__z_Dendrogram.__init__o   sG    '

	ZDJ2	z2tz26111$%DIdj!!$&DIdj!222$%DIdj!!$&DIdj!?l(G<@<V<Vz7J	?=
 =
9E5.& %]]__
]]__
s:'' 	5 	5A!}##
1T^(K(K%%jm444t~Ua//
 3t~..//H3t~..//H!&(Q,X-@CJJ,N(O(O" " =<);<<<DN,,UF;;			r   c           	         ddddddddd	}t          t          |                                d
                     }|g d}n|}t          t	          |                                                    D ]G}t          |                                          |         }|t	          |          k     r||         ||<   Hg d}|D ]+\  }}		 ||	         ||<   # t          $ r d|t          <   Y (w xY w|S )z
        Returns colorscale used for dendrogram tree clusters.

        :param (list) colorscale: Colors to use for the plot in rgb format.
        :rtype (dict): A dict of default colors mapped to the user colorscale.

        redgreenbluecyanmagentayellowblackwhite)rgbcmykwc                     | d         S )Nr   r8   )ts    r   r   z,_Dendrogram.get_color_dict.<locals>.<lambda>   s
    QqT r   )keyN)rgb(0,116,217)zrgb(35,205,205)zrgb(61,153,112)zrgb(40,35,35)zrgb(133,20,75)zrgb(255,65,54)zrgb(255,255,255)zrgb(255,220,0))
)C0ra   )C1r`   )C2r_   )C3rb   )C4rc   )C5rd   )C6re   )C7r`   )C8r_   )C9rb   rj   )	r   sorteditemsrA   r!   keyslistKeyErrorn)
rH   r*   ddefault_colorsrgb_colorscalerQ   re   new_old_color_mapncocs
             r   get_color_dictz_Dendrogram.get_color_dict   sO     
 
 %VAGGII>>%J%J%JKK	 	 	NN (Ns>..001122 	6 	6A^((**++A.A3~&&&&$21$5q!
 
 
 ( 	5 	5FB5%3B%7r"" 5 5 5 %5q!!!	5 s   CC+*C+c           	          ddddddddd}t           j                  dk    rq j        } j        d	v r j        }| j        vr
i  j        |<    fd
 j        D              j        |         d<    j         j        |         d<   d j        |         d<    j                                     |            j                 S )z
        Sets and returns default axis object for dendrogram figure.

        :param (str) axis_key: E.g., 'xaxis', 'xaxis1', 'yaxis', yaxis1', etc.
        :rtype (dict): An axis_key dictionary with set parameters.

        linearoutsidealltickstozeroTF)typeticksmirror	rangemodeshowticklabelszerolineshowgridshowliner   )r4   r6   c                 0    g | ]}|j                  z  S r8   )r=   )r9   zvaxis_keyrH   s     r   r;   z/_Dendrogram.set_axis_layout.<locals>.<listcomp>  s2     8 8 8-/TYx((8 8 8r   tickvalsticktextarraytickmode)r!   r)   r/   r(   r0   r   r@   update)rH   r   axis_defaultsaxis_key_labelss   ``  r   set_axis_layoutz_Dendrogram.set_axis_layout  s      !"	
 	
 t{q  "jO#444"&*dk11/1O,8 8 8 8 837>8 8 8DK(4 8<{DK(47>DK(4H$$]333{8$$r   c                     | j                             ddd||d           |                     | j                   |                     | j                   | j         S )zP
        Sets and returns default layout object for dendrogram figure.

        Fclosest)
showlegendautosize	hovermoderI   rJ   )r   r   r   r/   r0   )rH   rI   rJ   s      r   rG   z_Dendrogram.set_figure_layout$  sm    
 	#!&  	
 	
 	
 	TZ(((TZ((({r   c                     ||          } ||          }t                               || j        | j        d|          }	t                              |	d                   }
t                              |	d                   }t                              |	d                   }t                              |	d                   }|                     |          }g }t          t          |
                    D ]H}| j        dv r	|
|         }n||         }| j        dv r	||         }n|
|         }||         }d}|r||         }t          d	t          
                    | j        | j                 |          t          
                    | j        | j                 |          d
t          ||                   |d          }	 t          | j        d                   }n# t          $ r d}Y nw xY w	 t          | j        d                   }n# t          $ r d}Y nw xY wd| |d<   d| |d<   |                    |           J||
|||	d         fS )ao  
        Calculates all the elements needed for plotting a dendrogram.

        :param (ndarray) X: Matrix of observations as array of arrays
        :param (list) colorscale: Color scale for dendrogram tree clusters
        :param (function) distfun: Function to compute the pairwise distance
                                   from the observations
        :param (function) linkagefun: Function to compute the linkage matrix
                                      from the pairwise distances
        :param (list) hovertext: List of hovertext for constituent traces of dendrogram
        :rtype (tuple): Contains all the traces in the following order:
            (a) trace_list: List of Plotly trace objects for dendrogram tree
            (b) icoord: All X points of the dendrogram tree as array of arrays
                with length 4
            (c) dcoord: All Y points of the dendrogram tree as array of arrays
                with length 4
            (d) ordered_labels: leaf labels in the order they are going to
                appear on the plot
            (e) P['leaves']: left-to-right traversal of the leaves

        T)r(   r)   no_plotr   icoorddcoordivl
color_list)topr	   Nscatterlines)colortext)r   r   rd   modemarkerr   	hoverinfor5    r   r/   rd   r0   r<   )r   r,   r(   r)   npr   r   rA   r!   dictmultiplyr=   r/   r0   rC   
ValueErrorrB   )rH   r'   r*   r   r   r   r   r{   ZPr   r   rN   r   colors
trace_listrQ   xsys	color_keyhovertext_labeltracex_indexy_indexs                           r   r>   z!_Dendrogram.get_dendrogram_traces8  sk   0 GAJJJqMMNN(;+  
 
 !H+&&!H+&&!E(++XXao..
$$Z00
s6{{## '	% '	%A #444AYAY#444AYAY"1I"O /"+A,++di
3R88++di
3R88&"3444$   Edjn--   djn--    +]]E'N*]]E'Ne$$$$66>1X;FFs$   ;GG%$G%)HHH)__name__
__module____qualname____doc__r   infrU   r   r   rG   r>   r8   r   r   r%   r%   l   s        CC
 fv77C C C CJK K KZ!% !% !%F  (SG SG SG SG SGr   r%   )collectionsr   plotlyr   r   plotly.graph_objsr   
get_moduler   r   r   r   r-   objectr%   r8   r   r   <module>r      s   # # # # # # / / / / / / / / ( ( ( ( ( ( ! ))!!'**!!";<<!!/22
 33\M \M \M \M~_G _G _G _G _G& _G _G _G _G _Gr   