
    6Dh76                         S SK Jr  S SKJrJr  S SKJr  \R                  " S5      r\R                  " S5      r	\R                  " S5      r
\R                  " S5      rSS	S	S	S
 S	S	4S jr " S S\5      rg	)    )OrderedDict)
exceptionsoptional_imports)
graph_objsnumpyscipyzscipy.cluster.hierarchyzscipy.spatialbottomNc                 .    [         R                  U S5      $ Ncompleteschlinkagexs    S/var/www/html/env/lib/python3.13/site-packages/plotly/figure_factory/_dendrogram.py<lambda>r      s    Q
3    c                 h   [         (       a  [        (       a  [        (       d  [        S5      eU R                  n[        U5      S:w  a  [        R                  " S5        Uc  [        R                  R                  n[        U UUUUUUUS9n	[        R                  " U	R                  U	R                  S9$ )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.)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 3cc?
 	

 	
A
1v{AB,,$$	'	J *//*:K:KLLr   c                   z    \ rS rSrSrSSS\R                  \R                  SSSS SS4S jrS	 rS
 r	S r
S rSrg)r%   l   z9Refer to FigureFactory.create_dendrogram() for docstring.r	   Nxaxisyaxisc                 .    [         R                  U S5      $ r   r   r   s    r   r   _Dendrogram.<lambda>z   s    S[[J7r   c           
         X l         X0l        Xpl        Xl        / U l        / U l        U R                  SU R                  S0U l        U R                  0 U R                  0 0U l        U R                   S;   a  SU R                  U R                  '   OSU R                  U R                  '   U R                   S;   a  SU R                  U R                  '   OSU R                  U R                  '   U	c  [        R                  R                  n	U R                  XXX5      u  pnnnUU l        UU l        UR                  5       nUR                  5       n/ U l        [        [        U5      5       HA  nUU   S:X  d  M  UU   U R                  ;  d  M#  U R                  R!                  UU   5        MC     [        U R                  5      [        U5      S-   :  a|  [#        [%        U R                  5      5      n[#        ['        U R                  5      5      n[        UUS-   [#        UU-
  [        U5      -  5      5      nU Vs/ s H  nUPM     snU l        U R                  R)                  5         U R+                  XV5      U l        Xl        g s  snf )N   )leftr	   )rightr	   g        )r(   r)   r0   r1   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heightr0   r1   r   r   r   r   	dd_tracesxvalsyvalsordered_labelsr9   
yvals_flat
xvals_flatil_borderr_bordercorrect_leaves_posvs                            r   __init___Dendrogram.__init__o   s    '

	ZZDJJ2	zz2tzz2611$%DIIdjj!$&DIIdjj!22$%DIIdjj!$&DIIdjj!?ll((G<@<V<V7	=
95.& %]]_
]]_
s:'A!}#
1T^^(K%%jm4 ( t~~Ua/
 3t~~./H3t~~./H!&(Q,X-@CJ,N(O" *<<);Aa);<DN,,U;		 =s   ;Jc           	         SSSSSSSSS	.n[        [        UR                  5       S
 S95      nUc  / SQnOUn[        [	        UR                  5       5      5       H6  n[        UR                  5       5      U   nU[	        U5      :  d  M0  XE   X6'   M8     / SQnU H  u  p X9   X8'   M     U$ ! [         a    SU[        '    M(  f = f)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                     U S   $ )Nr    )ts    r   r   ,_Dendrogram.get_color_dict.<locals>.<lambda>   s    QqTr   )key)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))
)C0r`   )C1r_   )C2r^   )C3ra   )C4rb   )C5rc   )C6rd   )C7r_   )C8r^   )C9ra   rk   )	r   sorteditemsr>   r!   keyslistKeyErrorn)
rE   r*   ddefault_colorsrgb_colorscalerN   rd   new_old_color_mapncocs
             r   get_color_dict_Dendrogram.get_color_dict   s      
 %VAGGI>%JK	N (Ns>..012A^((*+A.A3~&&$2$5! 3
 (FB5%3%7" (   5 %5q!	5s    B,,CCc           	         SSSSSSSSS.n[        U R                  5      S:w  a  U R                  nU R                  S	;   a  U R                  nX0R
                  ;  a  0 U R
                  U'   U R                   Vs/ s H  oDU R                  U   -  PM     snU R
                  U   S
'   U R                  U R
                  U   S'   SU R
                  U   S'   U R
                  U   R                  U5        U R
                  U   $ s  snf )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   )r6   r8   tickvalsticktextarraytickmode)	r!   r)   r0   r(   r1   r   r=   r:   update)rE   axis_keyaxis_defaultsaxis_key_labelszvs        r   set_axis_layout_Dendrogram.set_axis_layout  s      !"	
 t{{q "jjO#44"&**kk1/1O,37>>83ARTYYx((>8DKK(4 8<{{DKK(47>DKK(4H$$]3{{8$$8s   9Dc                     U R                   R                  SSSUUS.5        U R                  U R                  5        U R                  U R                  5        U R                   $ )z@
Sets and returns default layout object for dendrogram figure.

Fclosest)
showlegendautosize	hovermoderF   rG   )r   r   r   r0   r1   )rE   rF   rG   s      r   rD   _Dendrogram.set_figure_layout$  sZ    
 	#!& 	
 	TZZ(TZZ({{r   c                    U" U5      nU" U5      n[         R                  UU R                  U R                  SUS9n	[        R                  U	S   5      n
[        R                  U	S   5      n[        R                  U	S   5      n[        R                  U	S   5      nU R                  U5      n/ n[        [        U
5      5       GH  nU R                  S;   a  U
U   nOUU   nU R                  S;   a  UU   nOU
U   nUU   nSnU(       a  UU   n[        S	[        R                  U R                  U R                     U5      [        R                  U R                  U R                     U5      S
[        UU   S9USS9n [        U R                  S   5      n [        U R                  S   5      nSU 3US'   SU 3US'   UR!                  U5        GM     XXU	S   4$ ! [         a    Sn NUf = f! [         a    Sn NNf = f)a  
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   rc   modemarkerr   	hoverinfor7    r   r0   rc   r1   r9   )r   r,   r(   r)   npr   r   r>   r!   dictmultiplyr:   r0   r1   r@   
ValueErrorr?   )rE   r'   r*   r   r   r   r   r|   ZPr   r   rK   r   colors
trace_listrN   xsys	color_keyhovertext_labeltracex_indexy_indexs                           r   r;   !_Dendrogram.get_dendrogram_traces8  s   0 AJqMNN((;;+  
 !H+&!H+&!E(+XXao.
$$Z0
s6{#A #44AYAY#44AYAY"1I"O"+A,++dii

3R8++dii

3R8&"34$ Edjjn-djjn-  !	]E'N 	]E'Ne$O $R 61X;FF  
  s$    GG1G.-G.1H ?H )	r   r)   r   r9   r(   r:   r0   r1   r=   )__name__
__module____qualname____firstlineno____doc__r   infrS   r   r   rD   r;   __static_attributes__rg   r   r   r%   r%   l   sP    C
 ffvv7CJKZ!%F(SGr   r%   )collectionsr   plotlyr   r   plotly.graph_objsr   
get_moduler   r   r   r   r-   objectr%   rg   r   r   <module>r      s    # / (   )!!'*!!";<!!/2
 3\M~_G& _Gr   