U
    Y»{j|6  ã                   @   sŒ   d dl mZ d dlmZ d dlmZmZ d dlmZ e 	d¡Z
e 	d¡Ze 	d¡Ze 	d¡Zd	d
d
d
dd„ d
d
fdd„ZG dd„ deƒZd
S )é    )Úabsolute_import)ÚOrderedDict)Ú
exceptionsÚoptional_imports)Ú
graph_objsÚnumpyZscipyzscipy.cluster.hierarchyzscipy.spatialÚbottomNc                 C   s   t  | d¡S ©NZcomplete©ÚschÚlinkage©Úx© r   ú`/var/www/html/bwave/python/venv/lib/python3.8/site-packages/plotly/figure_factory/_dendrogram.pyÚ<lambda>   ó    r   c           
   
   C   sj   t rtrtstdƒ‚| j}t|ƒdkr0t d¡ |dkr@tjj	}t
| |||||||d�}	tj|	j|	jd�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   ZPlotlyErrorÚdistanceÚpdistÚ_Dendrogramr   ZFigurer   r   )
ÚXÚorientationÚlabelsÚ
colorscaler   r   r   r   ÚsÚ
dendrogramr   r   r   Úcreate_dendrogram   s(    Dÿ
ør(   c                   @   sX   e Zd ZdZdddejejddddd„ ddfdd	„Zd
d„ Zdd„ Zdd„ Z	dd„ Z
dS )r!   z9Refer to FigureFactory.create_dendrogram() for docstring.r   NÚxaxisÚyaxisc                 C   s   t  | d¡S r	   r
   r   r   r   r   r   ~   r   z_Dendrogram.<lambda>c                 C   s¢  || _ || _|| _|| _g | _g | _| jd| jdi| _| ji | ji i| _| j dkr`d| j| j< nd| j| j< | j dkr„d| j| j< nd| j| j< |	d kr tj	j
}	|  |||	|
||¡\}}}}}|| _|| _| ¡ }| ¡ }g | _tt|ƒƒD ].}|| dkrì|| | jkrì| j || ¡ qìt| jƒt|ƒd k�r€tt| jƒƒ}tt| jƒƒ}t||d t|| t|ƒ ƒƒ}dd„ |D ƒ| _| j ¡  |  ||¡| _|| _d S )Né   )Úleftr   éÿÿÿÿ)Úrightr   g        c                 S   s   g | ]}|‘qS r   r   )Ú.0Úvr   r   r   Ú
<listcomp>²   s     z(_Dendrogram.__init__.<locals>.<listcomp>)r#   r$   r)   r*   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)   r*   r   r   r   r   Z	dd_tracesZxvalsZyvalsÚordered_labelsr2   Z
yvals_flatZ
xvals_flatÚiZl_borderZr_borderZcorrect_leaves_posr   r   r   Ú__init__s   sX    

     ÿ  ÿ
z_Dendrogram.__init__c           
   
   C   sæ   ddddddddd	œ}t t| ¡ d
d„ d�ƒ}|dkrLddddddddg}n|}tt| ¡ ƒƒD ],}t| ¡ ƒ| }|t|ƒk r`|| ||< q`ddddddddddg
}|D ]6\}}	z||	 ||< W qª tk
rÞ   d|t< Y qªX qª|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                 S   s   | d S )Nr   r   )Útr   r   r   r   Ò   r   z,_Dendrogram.get_color_dict.<locals>.<lambda>)ÚkeyNz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))ZC0rN   )ZC1rM   )ZC2rL   )ZC3rO   )ZC4rP   )ZC5rQ   )ZC6rR   )ZC7rM   )ZC8rL   )ZC9rO   )	r   ÚsortedÚitemsr7   r   ÚkeysÚlistÚKeyErrorÚn)
r>   r%   ÚdZdefault_colorsZrgb_colorscalerB   rR   Znew_old_color_mapÚncÚocr   r   r   Úget_color_dict¸   sT    öø
öz_Dendrogram.get_color_dictc              	      s¦   dddddddddœ}t ˆjƒdkrŒˆj}ˆjd	kr:ˆj}|ˆjkrNi ˆj|< ‡ ‡fd
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.

        ZlinearZoutsideZallticksZtozeroTF)ÚtypeZticksZmirrorZ	rangemodeZshowticklabelsZzerolineZshowgridZshowliner   )r,   r.   c                    s   g | ]}|ˆj ˆ   ‘qS r   )r3   )r/   Zzv©Úaxis_keyr>   r   r   r1     s    z/_Dendrogram.set_axis_layout.<locals>.<listcomp>ZtickvalsZticktextÚarrayZtickmode)r   r$   r)   r#   r*   r   r6   Úupdate)r>   rb   Zaxis_defaultsZaxis_key_labelsr   ra   r   Úset_axis_layout  s,    	ø


ÿz_Dendrogram.set_axis_layoutc                 C   s6   | j  ddd||dœ¡ |  | j¡ |  | j¡ | j S )zP
        Sets and returns default layout object for dendrogram figure.

        FZclosest)Z
showlegendZautosizeZ	hovermoder?   r@   )r   rd   re   r)   r*   )r>   r?   r@   r   r   r   r=   (  s    ûÿ
z_Dendrogram.set_figure_layoutc              
   C   s¢  ||ƒ}||ƒ}t j|| j| jd|d�}	t |	d ¡}
t |	d ¡}t |	d ¡}t |	d ¡}|  |¡}g }tt|
ƒƒD �]}| jdkr”|
| }n|| }| jdkr°|| }n|
| }|| }d}|rÐ|| }t	d	t
 | j| j |¡t
 | j| j |¡d
t	|| d�|dd�}zt| jd ƒ}W n tk
�r<   d}Y nX zt| jd ƒ}W n tk
�rj   d}Y nX d| |d< d| |d< | |¡ qz||
|||	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$   Zno_plotr   ÚicoordÚdcoordZivlÚ
color_list)Útopr   NZscatterÚlines)ÚcolorÚtext)r`   r   rQ   ÚmodeÚmarkerrl   Z	hoverinfor-   Ú r   r)   rQ   r*   r2   )r   r'   r#   r$   r   rc   r_   r7   r   ÚdictÚnpÚmultiplyr3   r)   r*   r9   Ú
ValueErrorr8   )r>   r"   r%   r   r   r   r   r\   ÚZÚPrf   rg   rA   rh   ÚcolorsZ
trace_listrB   ZxsZysZ	color_keyZhovertext_labelÚtraceZx_indexZy_indexr   r   r   r4   <  s^    û




ù


z!_Dendrogram.get_dendrogram_traces)Ú__name__Ú
__module__Ú__qualname__Ú__doc__rq   ÚinfrC   r_   re   r=   r4   r   r   r   r   r!   p   s"   ó
EM#r!   )Ú
__future__r   Úcollectionsr   Zplotlyr   r   Zplotly.graph_objsr   Z
get_modulerq   r   r   r   r(   Úobjectr!   r   r   r   r   Ú<module>   s    



ø
_