
W[c           @   s  d  Z  d d l m Z d d l Z d d l Z d d l m Z d d l j	 Z
 d d l m Z d d l Z d d l Z d d l m Z d d l m Z d d	 l m Z d d
 l m Z m Z m Z m Z d d l m Z d d g Z d   Z d   Z d   Z  d   Z! d e" f d     YZ# e$ e$ e$ e$ e% e$ d e$ d d e& e$ e$ e% d d e$ e$ d  Z' d e" f d     YZ( e$ d e& d d e% e$ d  Z) d e f d     YZ* e$ d d e$ e$ e$ e$ e& e& e$ e$ e$ e$ e$ d   Z+ d S(!   s(   Functions to visualize matrices of data.i(   t   divisionN(   t   LineCollection(   t   gridspec(   t	   hierarchyi   (   t   cm(   t   Grid(   t   despinet   axis_ticklabels_overlapt   relative_luminancet   to_utf8(   t   string_typest   heatmapt
   clustermapc         C   s6   t  |  t j  r+ d j t t |  j   S|  j Sd S(   s6   Convert a pandas index or multiindex to an axis label.t   -N(   t
   isinstancet   pdt
   MultiIndext   joint   mapR	   t   namest   name(   t   index(    (    s-   lib/python2.7/site-packages/seaborn/matrix.pyt   _index_to_label   s    c         C   sI   t  |  t j  r> g  |  j D] } d j t t |   ^ q S|  j Sd S(   s5   Convert a pandas index or multiindex into ticklabels.R   N(   R   R   R   t   valuesR   R   R	   (   R   t   i(    (    s-   lib/python2.7/site-packages/seaborn/matrix.pyt   _index_to_ticklabels    s    ,c            s   t  j j j  t   t j  rA t j    f d     D  St   t j  r`   j   Sy%    d  t	 t      SWn4 t
 k
 r g    D] } t	 t  |   ^ q SXd S(   sA   Convert either a list of colors or nested lists of colors to RGB.c            s&   i  |  ] }   | j    |  q S(    (   R   (   t   .0t   col(   t   colorst   to_rgb(    s-   lib/python2.7/site-packages/seaborn/matrix.pys
   <dictcomp>.   s   	i    N(   t   mplR   t   colorConverterR   R   R   t	   DataFramet   SeriesR   t   listt
   ValueError(   R   t   l(    (   R   R   s-   lib/python2.7/site-packages/seaborn/matrix.pyt   _convert_colors(   s    c         C   s   | d k r' t j |  j t j  } n  t | t j  r | j |  j k rZ t d   n  t j	 | d |  j
 d |  j d t j } nU t | t j	  r | j
 j |  j
  r | j j |  j  r d } t |   q n  | t j |   B} | S(   s   Ensure that data and mask are compatabile and add missing values.

    Values will be plotted for cells where ``mask`` is ``False``.

    ``data`` is expected to be a DataFrame; ``mask`` can be an array or
    a DataFrame.

    s&   Mask must have the same shape as data.R   t   columnst   dtypes2   Mask must have the same index and columns as data.N(   t   Nonet   npt   zerost   shapet   boolR   t   ndarrayR#   R   R    R   R&   t   equalst   isnull(   t   datat   maskt   err(    (    s-   lib/python2.7/site-packages/seaborn/matrix.pyt   _matrix_mask<   s     			t   _HeatMapperc           B   sM   e  Z d  Z e e d d  Z d   Z d   Z d   Z d   Z	 d   Z
 RS(   s?   Draw a heatmap plot of a matrix with nice labels and colormaps.c         C   s  t  | t j  r | j } n t j |  } t j |  } t | |  } t j j t j |  |  } d } t  | t	  r | } t
 | j  } n3 | t k r t
 | j  } n | t k r g  } n  d } t  | t	  r | } t
 | j  } n3 | t k rt
 | j  } n | t k r)g  } n  | j j \ } } t |  s\g  |  _ g  |  _ nW t  | t  r| d k rd |  _ t
 | j  |  _ n |  j | |  \ |  _ |  _ t |  sg  |  _ g  |  _ nW t  | t  r| d k rd |  _ t
 | j  |  _ n |  j | |  \ |  _ |  _ t | j  } t | j  } | d k	 r[| n d |  _ | d k	 rv| n d |  _ |  j | | | | | |  | d k rt } d } nu t  | t  r| r| } q+d } nN y | j } Wn t k
 r| } n X| j | j k r%t d   n  t } | |  _  | |  _! | |  _" | |  _# | |  _$ |	 d k rji  n |	 |  _% |
 |  _& | d k ri  n | |  _' |  j' j( d t) j* j+ d   d S(   s   Initialize the plotting object.i   t   autot    sD   Data supplied to "annot" must be the same shape as the data to plot.t   ticksi   N(,   R   R   R    R   R)   t   asarrayR3   t   mat   masked_wheret   intR   R&   t   Truet   FalseR   t   TR+   t   lent   xtickst   xticklabelsR
   t   _skip_tickst   ytickst   yticklabelsR   R(   t   xlabelt   ylabelt   _determine_cmap_paramsR,   t   AttributeErrorR#   R0   t	   plot_datat   annott
   annot_datat   fmtt	   annot_kwst   cbart   cbar_kwst
   setdefaultR   t   tickert   MaxNLocator(   t   selfR0   t   vmint   vmaxt   cmapt   centert   robustRJ   RL   RM   RN   RO   RA   RD   R1   RI   t
   xtickeveryt
   ytickeveryt   nxt   nyRE   RF   RK   (    (    s-   lib/python2.7/site-packages/seaborn/matrix.pyt   __init__d   s    											
						c         C   s  | j  t j | j   } | d k rM | r> t j | d  n	 | j   } n  | d k r | rq t j | d  n	 | j   } n  | | |  _ |  _ | d k r | d k r t	 j
 |  _ q t	 j |  _ nW t | t  r t j	 j |  |  _ n0 t | t  rt j j |  |  _ n	 | |  _ | d k	 rt | | | |  } t j j | | | |  }	 |	 | | g  \ }
 } t j |
 | d  } t j j |  j |   |  _ n  d S(   s@   Use some heuristics to set good defaults for colorbar and range.i   ib   i   N(   R0   R)   t   isnanR(   t
   percentilet   mint   maxRT   RU   R   t   rocketRV   t   icefireR   R
   R   t   get_cmapR"   R   t   ListedColormapt	   Normalizet   linspace(   RS   RI   RT   RU   RV   RW   RX   t	   calc_datat   vranget   normlizet   cmint   cmaxt   cc(    (    s-   lib/python2.7/site-packages/seaborn/matrix.pyRG      s*    ''	c         C   s0  | j    |  j j \ } } t j t j |  d t j |  d  \ } } x t | j | j | j   | j	   |  j j  D] \ } } }	 }
 } |	 t j
 j k	 r t |
  } | d k r d n d } d |  j d j |  } t d | d d	 d
 d	  } | j |  j  | j | | | |  q q Wd S(   s/   Add textual labels with the value in each cell.g      ?g&1?s   .15t   ws   {:t   }t   colort   haRW   t   vaN(   t   update_scalarmappableRK   R+   R)   t   meshgridt   aranget   zipt   flatt	   get_arrayt   get_facecolorsR9   t   maskedR   RL   t   formatt   dictt   updateRM   t   text(   RS   t   axt   mesht   heightt   widtht   xpost   ypost   xt   yt   mRp   t   valt   lumt
   text_colort
   annotationt   text_kwargs(    (    s-   lib/python2.7/site-packages/seaborn/matrix.pyt   _annotate_heatmap   s    
2"c         C   s   t  |  } | d k r( g  g  } } ni | d k rQ t j |  d | } } n@ d | | } } } t j | | |  d } | | | |  } | | f S(   s3   Return ticks and labels at evenly spaced intervals.i    i   g      ?(   R?   R)   Ru   (   RS   t   labelst	   tickeveryt   nR7   t   startt   endt   step(    (    s-   lib/python2.7/site-packages/seaborn/matrix.pyRB      s    c         C   s   | j  j j   } | j   j |  } | j | j g | } | j | j g | } | j	 d g  \ } | j
 j   } t | | d  }	 |	 d k  r g  g  f St |  |	 d }
 |
 d k r d n |
 }
 |  j | |
  \ } } | | f S(   s5   Determine ticks and ticklabels that minimize overlap.i    iH   i   (   t   figuret   dpi_scale_transt   invertedt   get_window_extentt   transformedR   R   t   xaxist   yaxist	   set_tickst   labelt   get_sizeR;   R?   RB   (   RS   R   R   t   axist	   transformt   bboxt   sizet   tickt   fontsizet	   max_tickst
   tick_everyR7   (    (    s-   lib/python2.7/site-packages/seaborn/matrix.pyt   _auto_ticks  s    
c      	   C   s  t  d | d t d t  | j |  j d |  j d |  j d |  j | } | j d d |  j j	 d	 f d
 d |  j j	 d f  | j
   |  j r | j j | | | |  j  } | j j d  | j d t  r | j j t  q n  t |  j t  r*|  j d k r*|  j | |  j d  \ } } n |  j |  j } } t |  j t  r|  j d k r|  j | |  j d	  \ } }	 n |  j |  j } }	 | j d | d |  | j |  }
 | j |	 d d } t | j j d  r | j j  | j j j!    n  t" |
  r"t# j$ |
 d d n  t" |  rDt# j$ | d d n  | j d |  j% d |  j&  |  j' r||  j( | |  n  d S(   s&   Draw the heatmap on the provided Axes.R   t   leftt   bottomRT   RU   RV   t   xlimi    i   t   ylimt
   rasterizedR5   R@   RC   t   rotationt   verticalt   get_renderert
   horizontalRE   RF   N()   R   R<   t
   pcolormeshRI   RT   RU   RV   t   setR0   R+   t   invert_yaxisRN   R   t   colorbarRO   t   outlinet   set_linewidtht   getR=   t   solidst   set_rasterizedR   R@   R
   R   RA   RC   RD   t   set_xticklabelst   set_yticklabelst   hasattrt   canvast   drawR   R   t   pltt   setpRE   RF   RJ   R   (   RS   R   t   caxt   kwsR   t   cbR@   RA   RC   RD   t   xtlt   ytl(    (    s-   lib/python2.7/site-packages/seaborn/matrix.pyt   plot  s8    !6
	!!!!	N(   t   __name__t
   __module__t   __doc__R<   R(   R]   RG   R   RB   R   R   (    (    (    s-   lib/python2.7/site-packages/seaborn/matrix.pyR4   a   s   c				s   .2gi    t   whiteR5   c         K   s   t  |  | | | | | | | | | | | | |  } |	 | d <|
 | d <| d k rb t j   } n  | rx | j d  n  | j | | |  | S(   sR  Plot rectangular data as a color-encoded matrix.

    This is an Axes-level function and will draw the heatmap into the
    currently-active Axes if none is provided to the ``ax`` argument.  Part of
    this Axes space will be taken and used to plot a colormap, unless ``cbar``
    is False or a separate Axes is provided to ``cbar_ax``.

    Parameters
    ----------
    data : rectangular dataset
        2D dataset that can be coerced into an ndarray. If a Pandas DataFrame
        is provided, the index/column information will be used to label the
        columns and rows.
    vmin, vmax : floats, optional
        Values to anchor the colormap, otherwise they are inferred from the
        data and other keyword arguments.
    cmap : matplotlib colormap name or object, or list of colors, optional
        The mapping from data values to color space. If not provided, the
        default will depend on whether ``center`` is set.
    center : float, optional
        The value at which to center the colormap when plotting divergant data.
        Using this parameter will change the default ``cmap`` if none is
        specified.
    robust : bool, optional
        If True and ``vmin`` or ``vmax`` are absent, the colormap range is
        computed with robust quantiles instead of the extreme values.
    annot : bool or rectangular dataset, optional
        If True, write the data value in each cell. If an array-like with the
        same shape as ``data``, then use this to annotate the heatmap instead
        of the raw data.
    fmt : string, optional
        String formatting code to use when adding annotations.
    annot_kws : dict of key, value mappings, optional
        Keyword arguments for ``ax.text`` when ``annot`` is True.
    linewidths : float, optional
        Width of the lines that will divide each cell.
    linecolor : color, optional
        Color of the lines that will divide each cell.
    cbar : boolean, optional
        Whether to draw a colorbar.
    cbar_kws : dict of key, value mappings, optional
        Keyword arguments for `fig.colorbar`.
    cbar_ax : matplotlib Axes, optional
        Axes in which to draw the colorbar, otherwise take space from the
        main Axes.
    square : boolean, optional
        If True, set the Axes aspect to "equal" so each cell will be
        square-shaped.
    xticklabels, yticklabels : "auto", bool, list-like, or int, optional
        If True, plot the column names of the dataframe. If False, don't plot
        the column names. If list-like, plot these alternate labels as the
        xticklabels. If an integer, use the column names but plot only every
        n label. If "auto", try to densely plot non-overlapping labels.
    mask : boolean array or DataFrame, optional
        If passed, data will not be shown in cells where ``mask`` is True.
        Cells with missing values are automatically masked.
    ax : matplotlib Axes, optional
        Axes in which to draw the plot, otherwise use the currently-active
        Axes.
    kwargs : other keyword arguments
        All other keyword arguments are passed to ``ax.pcolormesh``.

    Returns
    -------
    ax : matplotlib Axes
        Axes object with the heatmap.

    See also
    --------
    clustermap : Plot a matrix using hierachical clustering to arrange the
                 rows and columns.

    Examples
    --------

    Plot a heatmap for a numpy array:

    .. plot::
        :context: close-figs

        >>> import numpy as np; np.random.seed(0)
        >>> import seaborn as sns; sns.set()
        >>> uniform_data = np.random.rand(10, 12)
        >>> ax = sns.heatmap(uniform_data)

    Change the limits of the colormap:

    .. plot::
        :context: close-figs

        >>> ax = sns.heatmap(uniform_data, vmin=0, vmax=1)

    Plot a heatmap for data centered on 0 with a diverging colormap:

    .. plot::
        :context: close-figs

        >>> normal_data = np.random.randn(10, 12)
        >>> ax = sns.heatmap(normal_data, center=0)

    Plot a dataframe with meaningful row and column labels:

    .. plot::
        :context: close-figs

        >>> flights = sns.load_dataset("flights")
        >>> flights = flights.pivot("month", "year", "passengers")
        >>> ax = sns.heatmap(flights)

    Annotate each cell with the numeric value using integer formatting:

    .. plot::
        :context: close-figs

        >>> ax = sns.heatmap(flights, annot=True, fmt="d")

    Add lines between each cell:

    .. plot::
        :context: close-figs

        >>> ax = sns.heatmap(flights, linewidths=.5)

    Use a different colormap:

    .. plot::
        :context: close-figs

        >>> ax = sns.heatmap(flights, cmap="YlGnBu")

    Center the colormap at a specific value:

    .. plot::
        :context: close-figs

        >>> ax = sns.heatmap(flights, center=flights.loc["January", 1955])

    Plot every other column label and don't plot row labels:

    .. plot::
        :context: close-figs

        >>> data = np.random.randn(50, 20)
        >>> ax = sns.heatmap(data, xticklabels=2, yticklabels=False)

    Don't draw a colorbar:

    .. plot::
        :context: close-figs

        >>> ax = sns.heatmap(flights, cbar=False)

    Use different axes for the colorbar:

    .. plot::
        :context: close-figs

        >>> grid_kws = {"height_ratios": (.9, .05), "hspace": .3}
        >>> f, (ax, cbar_ax) = plt.subplots(2, gridspec_kw=grid_kws)
        >>> ax = sns.heatmap(flights, ax=ax,
        ...                  cbar_ax=cbar_ax,
        ...                  cbar_kws={"orientation": "horizontal"})

    Use a mask to plot only part of a matrix

    .. plot::
        :context: close-figs

        >>> corr = np.corrcoef(np.random.randn(10, 200))
        >>> mask = np.zeros_like(corr)
        >>> mask[np.triu_indices_from(mask)] = True
        >>> with sns.axes_style("white"):
        ...     ax = sns.heatmap(corr, mask=mask, vmax=.3, square=True)


    t
   linewidthst	   edgecolort   equalN(   R4   R(   R   t   gcat
   set_aspectR   (   R0   RT   RU   RV   RW   RX   RJ   RL   RM   R   t	   linecolorRN   RO   t   cbar_axt   squareRA   RD   R1   R   t   kwargst   plotter(    (    s-   lib/python2.7/site-packages/seaborn/matrix.pyR   L  s    

t   _DendrogramPlotterc           B   sY   e  Z d  Z d   Z d   Z d   Z e d    Z d   Z e d    Z	 d   Z
 RS(   sA   Object for drawing tree of similarities between data rows/columnsc         C   s,  | |  _  |  j  d k r$ | j } n  t | t j  rB | j } n t j |  } t j |  } | |  _ | |  _	 |  j	 j
 |  _
 | |  _ | |  _ | |  _  | |  _ | |  _ | d k r |  j |  _ n	 | |  _ |  j   |  _ d t j |  j	 j
 d  d }	 |  j rt |  j	 j  }
 g  |  j D] } |
 | ^ q'}
 |  j rg  |  _ |	 |  _ g  |  _ |
 |  _ t |  j	 j  |  _ d |  _ q|	 |  _ g  |  _ |
 |  _ g  |  _ d |  _ t |  j	 j  |  _ n8 g  g  |  _ |  _ g  g  |  _ |  _ d	 \ |  _ |  _ |  j d |  _ |  j d |  _  d S(
   s   Plot a dendrogram of the relationships between the columns of data

        Parameters
        ----------
        data : pandas.DataFrame
            Rectangular data
        i   i
   i    i   R6   t   dcoordt   icoordN(   R6   R6   (!   R   R>   R   R   R    R   R)   R8   t   arrayR0   R+   t   metrict   methodR   t   rotateR(   t   calculated_linkaget   linkaget   calculate_dendrogramt
   dendrogramRu   R   R   t   reordered_indR@   RC   RA   RD   R   RF   RE   t   dependent_coordt   independent_coord(   RS   R0   R   R   R   R   R   R   R   R7   t
   ticklabelsR   (    (    s-   lib/python2.7/site-packages/seaborn/matrix.pyR]     sR    									!	 										c         C   sM   t  j |  j  d k r% t d  n  t j |  j d |  j d |  j } | S(   Ni'  sC   This will be slow... (gentle suggestion: "pip install fastcluster")R   R   (	   R)   t   productR+   t   UserWarningR   R   R   R   R   (   RS   R   (    (    s-   lib/python2.7/site-packages/seaborn/matrix.pyt   _calculate_linkage_scipyV  s
    c         C   s   d d  l  } d	 } |  j d k o- |  j | k } | sE |  j d k rg | j |  j d |  j d |  j S| j |  j d |  j d |  j } | Sd  S(
   Nit   centroidt   mediant   wardt	   euclideant   singleR   R   (   R   R   R   (   t   fastclusterR   R   t   linkage_vectorR   R   (   RS   R   t   euclidean_methodsR   R   (    (    s-   lib/python2.7/site-packages/seaborn/matrix.pyt   _calculate_linkage_fastcluster^  s    		
c         C   s-   y |  j    SWn t k
 r( |  j   SXd  S(   N(   R   t   ImportErrorR   (   RS   (    (    s-   lib/python2.7/site-packages/seaborn/matrix.pyR   o  s    c         C   s    t  j |  j d t d t j S(   s  Calculates a dendrogram based on the linkage matrix

        Made a separate function, not a property because don't want to
        recalculate the dendrogram every time it is accessed.

        Returns
        -------
        dendrogram : dict
            Dendrogram dictionary as returned by scipy.cluster.hierarchy
            .dendrogram. The important key-value pairing is
            "reordered_ind" which indicates the re-ordering of the matrix
        t   no_plott   color_threshold(   R   R   R   R<   R)   t   inf(   RS   (    (    s-   lib/python2.7/site-packages/seaborn/matrix.pyR   v  s    c         C   s   |  j  d S(   s2   Indices of the matrix, reordered by the dendrogramt   leaves(   R   (   RS   (    (    s-   lib/python2.7/site-packages/seaborn/matrix.pyR     s    c   
   	   C   s  t  d d d d  } |  j rv |  j d k rv t g  t |  j |  j  D]! \ } } t t | |   ^ qF |  } nF t g  t |  j |  j  D]! \ } } t t | |   ^ q |  } | j |  t	 |  j
  } t t t |  j   } |  j rH| j j d  | j d | d  | j d | d  | j   | j   n( | j d | d  | j d | d  t d	 | d
 t d t  | j d |  j d |  j d |  j d |  j  | j |  j  } | j |  j d d }	 t | j j  d  r| j j! | j j  j"    n  t	 |	  d k rIt# |	  rIt$ j% |	 d d n  t	 |  d k r}t# |  r}t$ j% | d d n  |  S(   s   Plots a dendrogram of the similarities between data on the axes

        Parameters
        ----------
        ax : matplotlib.axes.Axes
            Axes object upon which the dendrogram is plotted

        R   g      ?R   t   ki    t   righti
   g?R   R   R   R@   RC   RE   RF   R   R   R   R   (&   R|   R   R   R   Rv   R   R   R"   t   add_collectionR?   R   Ra   R   R   t   set_ticks_positiont   set_ylimt   set_xlimt   invert_xaxisR   R   R<   R   R@   RC   RE   RF   R   RA   R   RD   R   R   R   R   R   R   R   R   (
   RS   R   t   line_kwargsR   R   t   linest   number_of_leavest   max_dependent_coordR   R   (    (    s-   lib/python2.7/site-packages/seaborn/matrix.pyR     sB    		.	.		
(   R   R   R   R]   R   R   t   propertyR   R   R   R   (    (    (    s-   lib/python2.7/site-packages/seaborn/matrix.pyR     s   	?			R   t   averagec   	      C   s[   t  |  d | d | d | d | d | d | } | d k rK t j   } n  | j d |  S(	   s%  Draw a tree diagram of relationships within a matrix

    Parameters
    ----------
    data : pandas.DataFrame
        Rectangular data
    linkage : numpy.array, optional
        Linkage matrix
    axis : int, optional
        Which axis to use to calculate linkage. 0 is rows, 1 is columns.
    label : bool, optional
        If True, label the dendrogram at leaves with column or row names
    metric : str, optional
        Distance metric. Anything valid for scipy.spatial.distance.pdist
    method : str, optional
        Linkage method to use. Anything valid for
        scipy.cluster.hierarchy.linkage
    rotate : bool, optional
        When plotting the matrix, whether to rotate it 90 degrees
        counter-clockwise, so the leaves face right
    ax : matplotlib axis, optional
        Axis to plot on, otherwise uses current axis

    Returns
    -------
    dendrogramplotter : _DendrogramPlotter
        A Dendrogram plotter object.

    Notes
    -----
    Access the reordered dendrogram indices with
    dendrogramplotter.reordered_ind

    R   R   R   R   R   R   R   N(   R   R(   R   R   R   (	   R0   R   R   R   R   R   R   R   R   (    (    s-   lib/python2.7/site-packages/seaborn/matrix.pyR     s    $t   ClusterGridc           B   s   e  Z d d d d d d d d   Z d   Z d d d  Z e d d   Z e d d   Z d d  Z	 e d d	   Z
 d
   Z d   Z d   Z d   Z d   Z RS(   c	         C   s  t  | t j  r | |  _ n t j |  |  _ |  j |  j | | |  |  _ t |  j |  |  _ | d k r d \ }	 }
 |	 |
 f } n  t	 j
 d |  |  _ |  j | | d d \ |  _ |  _ |  j | | d d \ |  _ |  _ |  j |  j d | d d } |  j |  j d | d d } |  j d k r8d n d } |  j d k rSd n d } t j | | d d	 d
 d	 d | d | |  _ |  j j |  j | d d d  f  |  _ |  j j |  j d d  | d f  |  _ |  j j   |  j j   d |  _ d |  _ |  j d k	 rF|  j j |  j | d | d f  |  _ n  |  j d k	 r|  j j |  j | d | d f  |  _ n  |  j j |  j | d | d f  |  _ |  j j |  j d  |  _ d |  _ d |  _ d S(   s=   Grid object for organizing clustered heatmap input on to axesi
   t   figsizeR   i    i   i   i   t   wspaceg{Gz?t   hspacet   width_ratiost   height_ratiosi   N(   i
   i
   (   i    i    (   R   R   R    R0   t   format_datat   data2dR3   R1   R(   R   R   t   figt   _preprocess_colorst
   row_colorst   row_color_labelst
   col_colorst   col_color_labelst
   dim_ratiosR   t   GridSpect   gst   add_subplott   ax_row_dendrogramt   ax_col_dendrogramt   set_axis_offt   ax_row_colorst   ax_col_colorst
   ax_heatmapR   t   dendrogram_rowt   dendrogram_col(   RS   R0   t	   pivot_kwst   z_scoret   standard_scaleR  R  R  R1   R   R   R  R  t   nrowst   ncols(    (    s-   lib/python2.7/site-packages/seaborn/matrix.pyR]     sN    $$		,,			$	$*	c         C   s   d } | d k	 r t | t j t j f  r | d k rL | j | j } n | j | j } | j d  } t | t j  r t	 | j  } | j
 j } q | j d k r d g } n | j g } | j } n  t |  } n  | | f S(   sA   Preprocess {row/col}_colors to extract labels and convert colors.i    R   R6   N(   R(   R   R   R    R!   t   locR   R&   t   fillnaR"   R>   R   R   R%   (   RS   R0   R   R   R   (    (    s-   lib/python2.7/site-packages/seaborn/matrix.pyR
  /  s     c         C   s   | d k	 r | j |   } n | } | d k	 rK | d k	 rK t d   n  | d k	 rl |  j | |  } n  | d k	 r |  j | |  } n  | S(   s,   Extract variables from data or use directly.s:   Cannot perform both z-scoring and standard-scaling on dataN(   R(   t   pivotR#   R  R  (   RS   R0   R  R  R  R  (    (    s-   lib/python2.7/site-packages/seaborn/matrix.pyR  N  s    i   c         C   sS   | d k r |  } n	 |  j  } | | j   | j   } | d k rH | S| j  Sd S(   s  Standarize the mean and variance of the data axis

        Parameters
        ----------
        data2d : pandas.DataFrame
            Data to normalize
        axis : int
            Which axis to normalize across. If 0, normalize across rows, if 1,
            normalize across columns.

        Returns
        -------
        normalized : pandas.DataFrame
            Noramlized data with a mean of 0 and variance of 1 across the
            specified axis.
        i   N(   R>   t   meant   std(   R  R   t   z_scored(    (    s-   lib/python2.7/site-packages/seaborn/matrix.pyR  b  s    		c         C   sc   | d k r |  } n	 |  j  } | j   } | | | j   | j   } | d k rX | S| j  Sd S(   sV  Divide the data by the difference between the max and min

        Parameters
        ----------
        data2d : pandas.DataFrame
            Data to normalize
        axis : int
            Which axis to normalize across. If 0, normalize across rows, if 1,
            normalize across columns.
        vmin : int
            If 0, then subtract the minimum of the data before dividing by
            the range.

        Returns
        -------
        standardized : pandas.DataFrame
            Noramlized data with a mean of 0 and variance of 1 across the
            specified axis.

        i   N(   R>   R`   Ra   (   R  R   t   standardizedt   subtract(    (    s-   lib/python2.7/site-packages/seaborn/matrix.pyR    s    		g?c   
      C   s   | | } t  d | d  } d | } d | } | d k rL | | g }	 n | | g }	 | d k	 rt |	 | g 7}	 n  |	 d g 7}	 |	 S(   s@   Get the proportions of the figure taken up by each axes
        g       @g?g?i    N(   R`   R(   (
   RS   t   side_colorsR   R  t   side_colors_ratiot   figdimR   t   colorbar_widtht   colorbar_heightt   ratios(    (    s-   lib/python2.7/site-packages/seaborn/matrix.pyR    s    


i    c         C   s%  t  d   |  D  rJ t t j |     } t |   } t |  d  } n' t |   } d } t |   } |  g }  t d   t |  D  } t j g  |  D] } | D] } | | ^ q q  }	 | | f }
 |	 j	 |
  }	 |	 d d  | f }	 | d k r	|	 j
 }	 n  t j j |  } |	 | f S(   s  Turns a list of colors into a numpy matrix and matplotlib colormap

        These arguments can now be plotted using heatmap(matrix, cmap)
        and the provided colors will be plotted.

        Parameters
        ----------
        colors : list of matplotlib colors
            Colors to label the rows or columns of a dataframe.
        ind : list of ints
            Ordering of the rows or columns, to reorder the original colors
            by the clustered dendrogram order
        axis : int
            Which axis this is labeling

        Returns
        -------
        matrix : numpy.array
            A numpy array of integer values, where each corresponds to a color
            from the originally provided list of colors
        cmap : matplotlib.colors.ListedColormap

        c         s   s$   |  ] } t  t |  t  Vq d  S(   N(   t
   issubclasst   typeR"   (   R   R   (    (    s-   lib/python2.7/site-packages/seaborn/matrix.pys	   <genexpr>  s    i    i   c         s   s!   |  ] \ } } | | f Vq d  S(   N(    (   R   R   R   (    (    s-   lib/python2.7/site-packages/seaborn/matrix.pys	   <genexpr>  s    N(   t   anyR   t	   itertoolst   chainR?   R|   t	   enumerateR)   R   t   reshapeR>   R   R   Re   (   R   t   indR   t
   all_colorsR   R   t   color_to_valueRp   t   ct   matrixR+   RV   (    (    s-   lib/python2.7/site-packages/seaborn/matrix.pyt   color_list_to_matrix_and_cmap  s$    		*c         O   s0   d | k r d | d <n  |  j  j | |   d  S(   Nt   bbox_inchest   tight(   R	  t   savefig(   RS   t   argsR   (    (    s-   lib/python2.7/site-packages/seaborn/matrix.pyR=    s    c         C   s  | rH t  |  j d | d | d t d d d |  j d t d | |  _ n  |  j j g   |  j j g   | r t  |  j d | d | d t d d	 d |  j d | |  _	 n  |  j j g   |  j j g   t
 d |  j d
 t d t  t
 d |  j d
 t d t  d  S(   NR   R   R   R   i    R   R   R   i   R   R   (   R   R  R=   R  R<   R  t
   set_xtickst
   set_yticksR  R  R   (   RS   t   row_clustert   col_clusterR   R   t   row_linkaget   col_linkage(    (    s-   lib/python2.7/site-packages/seaborn/matrix.pyt   plot_dendrograms  s    !c         K   s,  | j    } | j d d  | j d d  | j d d  | j d d  | j d d  | j d d  | j d d  | j d d  |  j d k	 r9|  j |  j | d	 d
 \ } } |  j d k	 r |  j } n t } t | d | d t d |  j d | d t | | t k	 rRt	 j
 |  j j   d d qRn t |  j d t d t |  j d k	 r|  j |  j | d	 d \ } } |  j d k	 r|  j } n t } t | d | d t d |  j d t d | | | t k	 r(|  j j j   t	 j
 |  j j   d d
 q(n t |  j d t d t d S(   s   Plots color labels between the dendrogram and the heatmap

        Parameters
        ----------
        heatmap_kws : dict
            Keyword arguments heatmap
        RV   RW   RJ   RT   RU   RX   RA   RD   R   i    RN   R   R   iZ   R   R   i   N(   t   copyt   popR(   R  R:  R  R=   R   R  R   R   t   get_xticklabelsR   R<   R  R  R  R   t
   tick_rightt   get_yticklabels(   RS   t   xindt   yindR   R9  RV   R  R  (    (    s-   lib/python2.7/site-packages/seaborn/matrix.pyt   plot_colors  s@    	""c         K   s{  |  j  j | | f |  _  |  j j | | f |  _ | j d d  } y t j |  | } Wn t t f k
 rt n X| j d d  } y t j |  | } Wn t t f k
 r n Xt |  j  d |  j	 d |  j
 d | d |  j d | d | | |  j	 j   } | sd  n | d j   } |  j	 j j d	  |  j	 j j d	  | d  k	 rw|  j	 j   } t j | d
 | n  d  S(   NRA   R5   RD   R   R   RO   R1   i    R   R   (   R  t   ilocR1   RG  R)   R8   t	   TypeErrort
   IndexErrorR   R  R   RJ  R(   t   get_rotationR   R   t   set_label_positionR   R   (   RS   t   colorbar_kwsRK  RL  R   R   R   t   ytl_rot(    (    s-   lib/python2.7/site-packages/seaborn/matrix.pyt   plot_matrixH  s,    c      	   K   s   | d  k r i  n | } |  j | | | | d | d | y |  j j }	 Wn* t k
 rv t j |  j j d  }	 n Xy |  j	 j }
 Wn* t k
 r t j |  j j d  }
 n X|  j
 |	 |
 |  |  j | |	 |
 |  |  S(   NRC  RD  i   i    (   R(   RE  R  R   RH   R)   Ru   R  R+   R  RM  RU  (   RS   R   R   RS  RA  RB  RC  RD  R   RK  RL  (    (    s-   lib/python2.7/site-packages/seaborn/matrix.pyR   d  s    N(   R   R   R(   R]   R
  R  t   staticmethodR  R  R  R:  R=  RE  RM  RU  R   (    (    (    s-   lib/python2.7/site-packages/seaborn/matrix.pyR    s"   	<	$2			<	c         K   sm   t  |  d | d | d | d | d | d | d | } | j d | d	 | d
 | d | d |	 d |
 d | |  S(   s  Plot a matrix dataset as a hierarchically-clustered heatmap.

    Parameters
    ----------
    data: 2D array-like
        Rectangular data for clustering. Cannot contain NAs.
    pivot_kws : dict, optional
        If `data` is a tidy dataframe, can provide keyword arguments for
        pivot to create a rectangular dataframe.
    method : str, optional
        Linkage method to use for calculating clusters.
        See scipy.cluster.hierarchy.linkage documentation for more information:
        https://docs.scipy.org/doc/scipy/reference/generated/scipy.cluster.hierarchy.linkage.html
    metric : str, optional
        Distance metric to use for the data. See
        scipy.spatial.distance.pdist documentation for more options
        https://docs.scipy.org/doc/scipy/reference/generated/scipy.spatial.distance.pdist.html
        To use different metrics (or methods) for rows and columns, you may
        construct each linkage matrix yourself and provide them as
        {row,col}_linkage.
    z_score : int or None, optional
        Either 0 (rows) or 1 (columns). Whether or not to calculate z-scores
        for the rows or the columns. Z scores are: z = (x - mean)/std, so
        values in each row (column) will get the mean of the row (column)
        subtracted, then divided by the standard deviation of the row (column).
        This ensures that each row (column) has mean of 0 and variance of 1.
    standard_scale : int or None, optional
        Either 0 (rows) or 1 (columns). Whether or not to standardize that
        dimension, meaning for each row or column, subtract the minimum and
        divide each by its maximum.
    figsize: tuple of two ints, optional
        Size of the figure to create.
    cbar_kws : dict, optional
        Keyword arguments to pass to ``cbar_kws`` in ``heatmap``, e.g. to
        add a label to the colorbar.
    {row,col}_cluster : bool, optional
        If True, cluster the {rows, columns}.
    {row,col}_linkage : numpy.array, optional
        Precomputed linkage matrix for the rows or columns. See
        scipy.cluster.hierarchy.linkage for specific formats.
    {row,col}_colors : list-like or pandas DataFrame/Series, optional
        List of colors to label for either the rows or columns. Useful to
        evaluate whether samples within a group are clustered together. Can
        use nested lists or DataFrame for multiple color levels of labeling.
        If given as a DataFrame or Series, labels for the colors are extracted
        from the DataFrames column names or from the name of the Series.
        DataFrame/Series colors are also matched to the data by their
        index, ensuring colors are drawn in the correct order.
    mask : boolean array or DataFrame, optional
        If passed, data will not be shown in cells where ``mask`` is True.
        Cells with missing values are automatically masked. Only used for
        visualizing, not for calculating.
    kwargs : other keyword arguments
        All other keyword arguments are passed to ``sns.heatmap``

    Returns
    -------
    clustergrid : ClusterGrid
        A ClusterGrid instance.

    Notes
    -----
    The returned object has a ``savefig`` method that should be used if you
    want to save the figure object without clipping the dendrograms.

    To access the reordered row indices, use:
    ``clustergrid.dendrogram_row.reordered_ind``

    Column indices, use:
    ``clustergrid.dendrogram_col.reordered_ind``

    Examples
    --------

    Plot a clustered heatmap:

    .. plot::
        :context: close-figs

        >>> import seaborn as sns; sns.set(color_codes=True)
        >>> iris = sns.load_dataset("iris")
        >>> species = iris.pop("species")
        >>> g = sns.clustermap(iris)

    Use a different similarity metric:

    .. plot::
        :context: close-figs

        >>> g = sns.clustermap(iris, metric="correlation")

    Use a different clustering method:

    .. plot::
        :context: close-figs

        >>> g = sns.clustermap(iris, method="single")

    Use a different colormap and ignore outliers in colormap limits:

    .. plot::
        :context: close-figs

        >>> g = sns.clustermap(iris, cmap="mako", robust=True)

    Change the size of the figure:

    .. plot::
        :context: close-figs

        >>> g = sns.clustermap(iris, figsize=(6, 7))

    Plot one of the axes in its original organization:

    .. plot::
        :context: close-figs

        >>> g = sns.clustermap(iris, col_cluster=False)

    Add colored labels:

    .. plot::
        :context: close-figs

        >>> lut = dict(zip(species.unique(), "rbg"))
        >>> row_colors = species.map(lut)
        >>> g = sns.clustermap(iris, row_colors=row_colors)

    Standardize the data within the columns:

    .. plot::
        :context: close-figs

        >>> g = sns.clustermap(iris, standard_scale=1)

    Normalize the data within the rows:

    .. plot::
        :context: close-figs

        >>> g = sns.clustermap(iris, z_score=0)


    R  R  R  R  R  R  R1   R   R   RS  RA  RB  RC  RD  (   R  R   (   R0   R  R   R   R  R  R  RO   RA  RB  RC  RD  R  R  R1   R   R   (    (    s-   lib/python2.7/site-packages/seaborn/matrix.pyR   w  s    		(,   R   t
   __future__R    R1  t
   matplotlibR   t   matplotlib.collectionsR   t   matplotlib.pyplott   pyplotR   R   t   numpyR)   t   pandasR   t   scipy.clusterR   R6   R   t   axisgridR   t   utilsR   R   R   R	   t   external.sixR
   t   __all__R   R   R%   R3   t   objectR4   R(   R=   R<   R   R   R   R  R   (    (    (    s-   lib/python2.7/site-packages/seaborn/matrix.pyt   <module>   sF   "				%			+ 	