B
    &[_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_objsZnumpyZscipyzscipy.cluster.hierarchyzscipy.spatialbottomNc             C   s   t | dS )Ncomplete)schlinkage)x r   E/tmp/pip-install-l29rncou/plotly/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 )ac	  
    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 )Nr   )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rd| j| j< nd| j| j< |	d krtj	j
}	| |||	|
||\}}}}}|| _|| _| }| }g | _x>tt|D ].}|| dkr|| | jkr| j||  qW t| jt|d krt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_labelsr/   Z
yvals_flatZ
xvals_flatiZl_borderZr_borderZcorrect_leaves_posr   r   r   __init__s   sF    


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|}x@tt| D ],}t| | }|t|k rb|| ||< qbW ddddddddddg
}x>|D ]6\}}	y||	 ||< W q tk
r   d|t< Y qX qW |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.

        ZredZgreenZblueZcyanZmagentaZyellowZblackZ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C0rC   )ZC1rB   )ZC2rA   )ZC3rD   )ZC4rE   )ZC5rF   )ZC6rG   )ZC7rB   )ZC8rA   )ZC9rD   )	r   sorteditemsr4   r   keyslistKeyErrorn)
r;   r"   dZdefault_colorsZrgb_colorscaler?   rG   Znew_old_color_mapZncocr   r   r   get_color_dict   sN    
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   )r0   )r,   Zzv)axis_keyr;   r   r   r.     s    z/_Dendrogram.set_axis_layout.<locals>.<listcomp>ZtickvalsZticktextarrayZtickmode)r   r!   r&   r    r'   r   r3   update)r;   rU   Zaxis_defaultsZaxis_key_labelsr   )rU   r;   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   rW   rX   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 }x$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}yt| jd }W n tk
r@   d}Y nX yt| jd }W n tk
rn   d}Y nX d| |d< d| |d< || q~W ||
|||	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)rT   r   rF   modemarkerr_   Z	hoverinfor*    r   r&   rF   r'   r/   )r	   r$   r    r!   r   rV   rS   r4   r   dictnpmultiplyr0   r&   r'   r6   
ValueErrorr5   )r;   r   r"   r   r   r   r   rQ   ZPrY   rZ   r>   r[   colorsZ
trace_listr?   xsZysZ	color_keyZhovertext_labeltraceZx_indexZy_indexr   r   r   r1   <  sZ    






z!_Dendrogram.get_dendrogram_traces)__name__
__module____qualname____doc__rd   infr@   rS   rX   r:   r1   r   r   r   r   r   p   s    8M#r   )
__future__r   collectionsr   Zplotlyr   r   Zplotly.graph_objsr   Z
get_modulerd   r   r	   r   r%   objectr   r   r   r   r   <module>   s   



W