ó
Ê½÷Xc           @` sŸ  d  Z  d d l m Z m Z m Z d d l Z d d l Z d d l m Z d d l	 Z
 d d l m Z d d l j j Z d d l m Z d d l m Z i d d	 6d d
 6d d 6d d 6d d 6d d 6d d 6Z d d d f Z d d d d
 d d d d d d d d d d d  d! d" d# d$ d% d& d' d d( d) d	 d* d+ d d d, g Z d- e f d. „  ƒ  YZ d/ „  Z d0 „  Z d1 „  Z d2 „  Z d3 „  Z d4 „  Z d5 „  Z d6 „  Z d7 „  Z  d8 „  Z! d9 „  Z" d	 d: d; „ Z# d f  d< „  ƒ  YZ$ e$ d ƒ Z% e& e$ ƒ Z' d= „  Z( e) e) d> „ Z* e+ d? „ Z, d@ „  Z- dA „  Z. e) dB „ Z/ d dC „ Z0 dD „  Z1 dE „  Z2 dF „  Z3 e+ e+ e) dG „ Z4 e+ e+ e) dH „ Z5 dI „  Z6 dJ „  Z7 dK „  Z8 dL „  Z9 dM „  Z: d d e) e) dN „ Z; d d: d d	 e) dO „ Z< dP „  Z= i dQ dR 6dS dT 6dU dV 6d dW 6d e
 j> 6Z? i d dR 6dX dY 6dZ e
 j> 6Z@ eA e? jB ƒ  ƒ ZC eC jD ƒ  eA e@ jB ƒ  ƒ ZE eE jD ƒ  d[ „  ZF d\ „  ZG d] „  ZH e) e) e) e) d^ d_ „ ZI d` da db dc dd de g ZJ df „  ZK dT e) e) eL dg e) e+ e+ eL e+ e+ e) e) e) e+ e) e) d^ dh „ ZM di „  ZN dj „  ZO dk „  ZP dl „  ZQ e
 j> eL dg e) e+ e+ e+ dm dn g  d g  g  e) e+ g  g  g  e) d e) e) d^ do „ ZR dp „  ZS dq „  ZT dr „  ZU ds „  ZV dt „  ZW d S(u   sÍ  
========================================================
Hierarchical clustering (:mod:`scipy.cluster.hierarchy`)
========================================================

.. currentmodule:: scipy.cluster.hierarchy

These functions cut hierarchical clusterings into flat clusterings
or find the roots of the forest formed by a cut by providing the flat
cluster ids of each observation.

.. autosummary::
   :toctree: generated/

   fcluster
   fclusterdata
   leaders

These are routines for agglomerative clustering.

.. autosummary::
   :toctree: generated/

   linkage
   single
   complete
   average
   weighted
   centroid
   median
   ward

These routines compute statistics on hierarchies.

.. autosummary::
   :toctree: generated/

   cophenet
   from_mlab_linkage
   inconsistent
   maxinconsts
   maxdists
   maxRstat
   to_mlab_linkage

Routines for visualizing flat clusters.

.. autosummary::
   :toctree: generated/

   dendrogram

These are data structures and routines for representing hierarchies as
tree objects.

.. autosummary::
   :toctree: generated/

   ClusterNode
   leaves_list
   to_tree
   cut_tree

These are predicates for checking the validity of linkage and
inconsistency matrices as well as for checking isomorphism of two
flat cluster assignments.

.. autosummary::
   :toctree: generated/

   is_valid_im
   is_valid_linkage
   is_isomorphic
   is_monotonic
   correspond
   num_obs_linkage

Utility routines for plotting:

.. autosummary::
   :toctree: generated/

   set_link_color_palette

References
----------

.. [1] "Statistics toolbox." API Reference Documentation. The MathWorks.
   http://www.mathworks.com/access/helpdesk/help/toolbox/stats/.
   Accessed October 1, 2007.

.. [2] "Hierarchical clustering." API Reference Documentation.
   The Wolfram Research, Inc.
   http://reference.wolfram.com/mathematica/HierarchicalClustering/tutorial/
   HierarchicalClustering.html.
   Accessed October 1, 2007.

.. [3] Gower, JC and Ross, GJS. "Minimum Spanning Trees and Single Linkage
   Cluster Analysis." Applied Statistics. 18(1): pp. 54--64. 1969.

.. [4] Ward Jr, JH. "Hierarchical grouping to optimize an objective
   function." Journal of the American Statistical Association. 58(301):
   pp. 236--44. 1963.

.. [5] Johnson, SC. "Hierarchical clustering schemes." Psychometrika.
   32(2): pp. 241--54. 1966.

.. [6] Sneath, PH and Sokal, RR. "Numerical taxonomy." Nature. 193: pp.
   855--60. 1962.

.. [7] Batagelj, V. "Comparing resemblance measures." Journal of
   Classification. 12: pp. 73--90. 1995.

.. [8] Sokal, RR and Michener, CD. "A statistical method for evaluating
   systematic relationships." Scientific Bulletins. 38(22):
   pp. 1409--38. 1958.

.. [9] Edelbrock, C. "Mixture model tests of hierarchical clustering
   algorithms: the problem of classifying everybody." Multivariate
   Behavioral Research. 14: pp. 367--84. 1979.

.. [10] Jain, A., and Dubes, R., "Algorithms for Clustering Data."
   Prentice-Hall. Englewood Cliffs, NJ. 1988.

.. [11] Fisher, RA "The use of multiple measurements in taxonomic
   problems." Annals of Eugenics, 7(2): 179-188. 1936


* MATLAB and MathWorks are registered trademarks of The MathWorks, Inc.

* Mathematica is a registered trademark of The Wolfram Research, Inc.

i    (   t   divisiont   print_functiont   absolute_importN(   t   dequei   (   t
   _hierarchy(   t   string_types(   t   xranget   singlet   completei   t   averagei   t   centroidi   t   mediani   t   wardi   t   weightedt   ClusterNodet   cophenett
   correspondt   cut_treet
   dendrogramt   fclustert   fclusterdatat   from_mlab_linkaget   inconsistentt   is_isomorphict   is_monotonict   is_valid_imt   is_valid_linkaget   leaderst   leaves_listt   linkaget   maxRstatt   maxdistst   maxinconstst   num_obs_linkaget   set_link_color_palettet   to_mlab_linkaget   to_treet   distancet   ClusterWarningc           B` s   e  Z RS(    (   t   __name__t
   __module__(    (    (    s6   /tmp/pip-build-7oUkmx/scipy/scipy/cluster/hierarchy.pyR&   Å   s   c         C` s   t  j d |  t d d ƒd  S(   Ns   scipy.cluster: %st
   stackleveli   (   t   warningst   warnR&   (   t   s(    (    s6   /tmp/pip-build-7oUkmx/scipy/scipy/cluster/hierarchy.pyt   _warningÉ   s    c         C` sL   |  j  d k	 r |  j ƒ  St j |  t j ƒ rD t j |  d t j ƒS|  Sd S(   s@   
    Copies the array if its base points to a parent array.
    t   dtypeN(   t   baset   Nonet   copyt   npt   issubsctypet   float32t   arrayt   double(   t   a(    (    s6   /tmp/pip-build-7oUkmx/scipy/scipy/cluster/hierarchy.pyt   _copy_array_if_base_presentÍ   s
    
c         C` s#   g  |  D] } t  | ƒ ^ q } | S(   sþ   
    Accepts a tuple of arrays T. Copies the array T[i] if its base array
    points to an actual array. Otherwise, the reference is just copied.
    This is useful if the arrays are being passed to a C function that
    does not do proper striding.
    (   R8   (   t   TR7   t   l(    (    s6   /tmp/pip-build-7oUkmx/scipy/scipy/cluster/hierarchy.pyt   _copy_arrays_if_base_presentÙ   s    c         C` s=   |  d k r- t  j j |  |  d d ƒ } n t d ƒ ‚ | S(   s|    Generates a random distance matrix stored in condensed form. A
        pnts * (pnts - 1) / 2 sized vector is returned.
    i   i   s?   The number of points in the distance matrix must be at least 2.(   R2   t   randomt   randt
   ValueError(   t   pntst   D(    (    s6   /tmp/pip-build-7oUkmx/scipy/scipy/cluster/hierarchy.pyt   _randdmä   s    !c         C` s   t  |  d d d d ƒS(   sÐ  
    Performs single/min/nearest linkage on the condensed distance matrix ``y``

    Parameters
    ----------
    y : ndarray
        The upper triangular of the distance matrix. The result of
        ``pdist`` is returned in this form.

    Returns
    -------
    Z : ndarray
        The linkage matrix.

    See Also
    --------
    linkage: for advanced creation of hierarchical clusterings.
    scipy.spatial.distance.pdist : pairwise distance metrics

    t   methodR   t   metrict	   euclidean(   R   (   t   y(    (    s6   /tmp/pip-build-7oUkmx/scipy/scipy/cluster/hierarchy.pyR   ð   s    c         C` s   t  |  d d d d ƒS(   sV  
    Performs complete/max/farthest point linkage on a condensed distance matrix

    Parameters
    ----------
    y : ndarray
        The upper triangular of the distance matrix. The result of
        ``pdist`` is returned in this form.

    Returns
    -------
    Z : ndarray
        A linkage matrix containing the hierarchical clustering. See
        the `linkage` function documentation for more information
        on its structure.

    See Also
    --------
    linkage: for advanced creation of hierarchical clusterings.
    scipy.spatial.distance.pdist : pairwise distance metrics

    RB   R   RC   RD   (   R   (   RE   (    (    s6   /tmp/pip-build-7oUkmx/scipy/scipy/cluster/hierarchy.pyR     s    c         C` s   t  |  d d d d ƒS(   s%  
    Performs average/UPGMA linkage on a condensed distance matrix

    Parameters
    ----------
    y : ndarray
        The upper triangular of the distance matrix. The result of
        ``pdist`` is returned in this form.

    Returns
    -------
    Z : ndarray
        A linkage matrix containing the hierarchical clustering. See
        `linkage` for more information on its structure.

    See Also
    --------
    linkage: for advanced creation of hierarchical clusterings.
    scipy.spatial.distance.pdist : pairwise distance metrics

    RB   R	   RC   RD   (   R   (   RE   (    (    s6   /tmp/pip-build-7oUkmx/scipy/scipy/cluster/hierarchy.pyR	   "  s    c         C` s   t  |  d d d d ƒS(   s}  
    Performs weighted/WPGMA linkage on the condensed distance matrix.

    See `linkage` for more information on the return
    structure and algorithm.

    Parameters
    ----------
    y : ndarray
        The upper triangular of the distance matrix. The result of
        ``pdist`` is returned in this form.

    Returns
    -------
    Z : ndarray
        A linkage matrix containing the hierarchical clustering. See
        `linkage` for more information on its structure.

    See Also
    --------
    linkage : for advanced creation of hierarchical clusterings.
    scipy.spatial.distance.pdist : pairwise distance metrics

    RB   R   RC   RD   (   R   (   RE   (    (    s6   /tmp/pip-build-7oUkmx/scipy/scipy/cluster/hierarchy.pyR   ;  s    c         C` s   t  |  d d d d ƒS(   sc  
    Performs centroid/UPGMC linkage.

    See `linkage` for more information on the input matrix,
    return structure, and algorithm.

    The following are common calling conventions:

    1. ``Z = centroid(y)``

       Performs centroid/UPGMC linkage on the condensed distance
       matrix ``y``.

    2. ``Z = centroid(X)``

       Performs centroid/UPGMC linkage on the observation matrix ``X``
       using Euclidean distance as the distance metric.

    Parameters
    ----------
    y : ndarray
        A condensed distance matrix. A condensed
        distance matrix is a flat array containing the upper
        triangular of the distance matrix. This is the form that
        ``pdist`` returns. Alternatively, a collection of
        m observation vectors in n dimensions may be passed as
        a m by n array.

    Returns
    -------
    Z : ndarray
        A linkage matrix containing the hierarchical clustering. See
        the `linkage` function documentation for more information
        on its structure.

    See Also
    --------
    linkage: for advanced creation of hierarchical clusterings.

    RB   R
   RC   RD   (   R   (   RE   (    (    s6   /tmp/pip-build-7oUkmx/scipy/scipy/cluster/hierarchy.pyR
   W  s    )c         C` s   t  |  d d d d ƒS(   sÖ  
    Performs median/WPGMC linkage.

    See `linkage` for more information on the return structure
    and algorithm.

     The following are common calling conventions:

     1. ``Z = median(y)``

        Performs median/WPGMC linkage on the condensed distance matrix
        ``y``.  See ``linkage`` for more information on the return
        structure and algorithm.

     2. ``Z = median(X)``

        Performs median/WPGMC linkage on the observation matrix ``X``
        using Euclidean distance as the distance metric. See `linkage`
        for more information on the return structure and algorithm.

    Parameters
    ----------
    y : ndarray
        A condensed distance matrix. A condensed
        distance matrix is a flat array containing the upper
        triangular of the distance matrix. This is the form that
        ``pdist`` returns.  Alternatively, a collection of
        m observation vectors in n dimensions may be passed as
        a m by n array.

    Returns
    -------
    Z : ndarray
        The hierarchical clustering encoded as a linkage matrix.

    See Also
    --------
    linkage: for advanced creation of hierarchical clusterings.
    scipy.spatial.distance.pdist : pairwise distance metrics

    RB   R   RC   RD   (   R   (   RE   (    (    s6   /tmp/pip-build-7oUkmx/scipy/scipy/cluster/hierarchy.pyR   ƒ  s    *c         C` s   t  |  d d d d ƒS(   s‚  
    Performs Ward's linkage on a condensed distance matrix.

    See `linkage` for more information on the return structure
    and algorithm.

    The following are common calling conventions:

    1. ``Z = ward(y)``
       Performs Ward's linkage on the condensed distance matrix ``y``.

    2. ``Z = ward(X)``
       Performs Ward's linkage on the observation matrix ``X`` using
       Euclidean distance as the distance metric.

    Parameters
    ----------
    y : ndarray
        A condensed distance matrix. A condensed
        distance matrix is a flat array containing the upper
        triangular of the distance matrix. This is the form that
        ``pdist`` returns.  Alternatively, a collection of
        m observation vectors in n dimensions may be passed as
        a m by n array.

    Returns
    -------
    Z : ndarray
        The hierarchical clustering encoded as a linkage matrix. See
        `linkage` for more information on the return structure and
        algorithm.

    See Also
    --------
    linkage: for advanced creation of hierarchical clusterings.
    scipy.spatial.distance.pdist : pairwise distance metrics

    RB   R   RC   RD   (   R   (   RE   (    (    s6   /tmp/pip-build-7oUkmx/scipy/scipy/cluster/hierarchy.pyR   °  s    'RD   c         C` sã  | t  k r$ t d j | ƒ ƒ ‚ n  t t j |  d d ƒƒ }  |  j d k r| t j |  d t	 d d ƒt
 |  g ƒ \ }  nÏ |  j d k r?| t k r» | d	 k r» t d
 j | ƒ ƒ ‚ n  |  j d |  j d k r*t j t j |  ƒ d ƒ r*t j |  d k ƒ r*t j |  |  j ƒ r*t d ƒ q*n  t j |  | ƒ }  n t d ƒ ‚ t j t j |  ƒ ƒ srt d ƒ ‚ n  t t j |  ƒ ƒ } t  | } | d k r­t j |  | ƒ S| d k rÌt j |  | | ƒ St j |  | | ƒ Sd S(   s  
    Performs hierarchical/agglomerative clustering.

    The input y may be either a 1d compressed distance matrix
    or a 2d array of observation vectors.

    If y is a 1d compressed distance matrix,
    then y must be a :math:`{n \choose 2}` sized
    vector where n is the number of original observations paired
    in the distance matrix. The behavior of this function is very
    similar to the MATLAB linkage function.

    A :math:`(n-1)` by 4 matrix ``Z`` is returned. At the
    :math:`i`-th iteration, clusters with indices ``Z[i, 0]`` and
    ``Z[i, 1]`` are combined to form cluster :math:`n + i`. A
    cluster with an index less than :math:`n` corresponds to one of
    the :math:`n` original observations. The distance between
    clusters ``Z[i, 0]`` and ``Z[i, 1]`` is given by ``Z[i, 2]``. The
    fourth value ``Z[i, 3]`` represents the number of original
    observations in the newly formed cluster.

    The following linkage methods are used to compute the distance
    :math:`d(s, t)` between two clusters :math:`s` and
    :math:`t`. The algorithm begins with a forest of clusters that
    have yet to be used in the hierarchy being formed. When two
    clusters :math:`s` and :math:`t` from this forest are combined
    into a single cluster :math:`u`, :math:`s` and :math:`t` are
    removed from the forest, and :math:`u` is added to the
    forest. When only one cluster remains in the forest, the algorithm
    stops, and this cluster becomes the root.

    A distance matrix is maintained at each iteration. The ``d[i,j]``
    entry corresponds to the distance between cluster :math:`i` and
    :math:`j` in the original forest.

    At each iteration, the algorithm must update the distance matrix
    to reflect the distance of the newly formed cluster u with the
    remaining clusters in the forest.

    Suppose there are :math:`|u|` original observations
    :math:`u[0], \ldots, u[|u|-1]` in cluster :math:`u` and
    :math:`|v|` original objects :math:`v[0], \ldots, v[|v|-1]` in
    cluster :math:`v`. Recall :math:`s` and :math:`t` are
    combined to form cluster :math:`u`. Let :math:`v` be any
    remaining cluster in the forest that is not :math:`u`.

    The following are methods for calculating the distance between the
    newly formed cluster :math:`u` and each :math:`v`.

      * method='single' assigns

        .. math::
           d(u,v) = \min(dist(u[i],v[j]))

        for all points :math:`i` in cluster :math:`u` and
        :math:`j` in cluster :math:`v`. This is also known as the
        Nearest Point Algorithm.

      * method='complete' assigns

        .. math::
           d(u, v) = \max(dist(u[i],v[j]))

        for all points :math:`i` in cluster u and :math:`j` in
        cluster :math:`v`. This is also known by the Farthest Point
        Algorithm or Voor Hees Algorithm.

      * method='average' assigns

        .. math::
           d(u,v) = \sum_{ij} \frac{d(u[i], v[j])}
                                   {(|u|*|v|)}

        for all points :math:`i` and :math:`j` where :math:`|u|`
        and :math:`|v|` are the cardinalities of clusters :math:`u`
        and :math:`v`, respectively. This is also called the UPGMA
        algorithm.

      * method='weighted' assigns

        .. math::
           d(u,v) = (dist(s,v) + dist(t,v))/2

        where cluster u was formed with cluster s and t and v
        is a remaining cluster in the forest. (also called WPGMA)

      * method='centroid' assigns

        .. math::
           dist(s,t) = ||c_s-c_t||_2

        where :math:`c_s` and :math:`c_t` are the centroids of
        clusters :math:`s` and :math:`t`, respectively. When two
        clusters :math:`s` and :math:`t` are combined into a new
        cluster :math:`u`, the new centroid is computed over all the
        original objects in clusters :math:`s` and :math:`t`. The
        distance then becomes the Euclidean distance between the
        centroid of :math:`u` and the centroid of a remaining cluster
        :math:`v` in the forest. This is also known as the UPGMC
        algorithm.

      * method='median' assigns :math:`d(s,t)` like the ``centroid``
        method. When two clusters :math:`s` and :math:`t` are combined
        into a new cluster :math:`u`, the average of centroids s and t
        give the new centroid :math:`u`. This is also known as the
        WPGMC algorithm.

      * method='ward' uses the Ward variance minimization algorithm.
        The new entry :math:`d(u,v)` is computed as follows,

        .. math::

           d(u,v) = \sqrt{\frac{|v|+|s|}
                               {T}d(v,s)^2
                        + \frac{|v|+|t|}
                               {T}d(v,t)^2
                        - \frac{|v|}
                               {T}d(s,t)^2}

        where :math:`u` is the newly joined cluster consisting of
        clusters :math:`s` and :math:`t`, :math:`v` is an unused
        cluster in the forest, :math:`T=|v|+|s|+|t|`, and
        :math:`|*|` is the cardinality of its argument. This is also
        known as the incremental algorithm.

    Warning: When the minimum distance pair in the forest is chosen, there
    may be two or more pairs with the same minimum distance. This
    implementation may chose a different minimum than the MATLAB
    version.

    Parameters
    ----------
    y : ndarray
        A condensed distance matrix. A condensed distance matrix
        is a flat array containing the upper triangular of the distance matrix.
        This is the form that ``pdist`` returns. Alternatively, a collection of
        :math:`m` observation vectors in :math:`n` dimensions may be passed as an
        :math:`m` by :math:`n` array. All elements of the condensed distance matrix
        must be finite, i.e. no NaNs or infs.
    method : str, optional
        The linkage algorithm to use. See the ``Linkage Methods`` section below
        for full descriptions.
    metric : str or function, optional
        The distance metric to use in the case that y is a collection of
        observation vectors; ignored otherwise. See the ``pdist``
        function for a list of valid distance metrics. A custom distance
        function can also be used.

    Returns
    -------
    Z : ndarray
        The hierarchical clustering encoded as a linkage matrix.

    Notes
    -----
    1. For method 'single' an optimized algorithm based on minimum spanning
       tree is implemented. It has time complexity :math:`O(n^2)`.
       For methods 'complete', 'average', 'weighted' and 'ward' an algorithm
       called nearest-neighbors chain is implemented. It also has time
       complexity :math:`O(n^2)`.
       For other methods a naive algorithm is implemented with :math:`O(n^3)`
       time complexity.
       All algorithms use :math:`O(n^2)` memory.
       Refer to [1]_ for details about the algorithms.
    2. Methods 'centroid', 'median' and 'ward' are correctly defined only if
       Euclidean pairwise metric is used. If `y` is passed as precomputed
       pairwise distances, then it is a user responsibility to assure that
       these distances are in fact Euclidean, otherwise the produced result
       will be incorrect.

    See Also
    --------
    scipy.spatial.distance.pdist : pairwise distance metrics

    References
    ----------
    .. [1] Daniel Mullner, "Modern hierarchical, agglomerative clustering
           algorithms", :arXiv:`1109.2378v1`.
    s   Invalid method: {0}t   ordert   ci   t   throwt   nameRE   i   RD   s9   Method '{0}' requires the distance metric to be Euclideani    sk   The symmetric non-negative hollow observation matrix looks suspiciously like an uncondensed distance matrixs   `y` must be 1 or 2 dimensional.s>   The condensed distance matrix must contain only finite values.R   R   R	   R   R   N(   s   completes   averages   weighteds   ward(   t   _LINKAGE_METHODSR>   t   formatt   _convert_to_doubleR2   t   asarrayt   ndimR%   t
   is_valid_yt   TrueR;   t   _EUCLIDEAN_METHODSt   shapet   allcloset   diagt   allR9   R-   t   pdistt   isfinitet   intt	   num_obs_yR   t   mst_single_linkaget   nn_chaint   fast_linkage(   RE   RB   RC   t   nt   method_code(    (    s6   /tmp/pip-build-7oUkmx/scipy/scipy/cluster/hierarchy.pyR   Ú  s0    ´	5*
c           B` sz   e  Z d  Z d d d d d „ Z d „  Z d „  Z d „  Z d „  Z d „  Z	 d	 „  Z
 d
 „  Z d „  Z d „  d „ Z RS(   s1  
    A tree node class for representing a cluster.

    Leaf nodes correspond to original observations, while non-leaf nodes
    correspond to non-singleton clusters.

    The `to_tree` function converts a matrix returned by the linkage
    function into an easy-to-use tree representation.

    All parameter names are also attributes.

    Parameters
    ----------
    id : int
        The node id.
    left : ClusterNode instance, optional
        The left child tree node.
    right : ClusterNode instance, optional
        The right child tree node.
    dist : float, optional
        Distance for this cluster in the linkage matrix.
    count : int, optional
        The number of samples in this cluster.

    See Also
    --------
    to_tree : for converting a linkage matrix ``Z`` into a tree object.

    i    i   c         C` sæ   | d k  r t  d ƒ ‚ n  | d k  r6 t  d ƒ ‚ n  | d  k rN | d  k	 sf | d  k	 ru | d  k ru t  d ƒ ‚ n  | d k  r t  d ƒ ‚ n  | |  _ | |  _ | |  _ | |  _ |  j d  k rÏ | |  _ n | j | j |  _ d  S(   Ni    s   The id must be non-negative.s"   The distance must be non-negative.sI   Only full or proper binary trees are permitted.  This node has one child.i   s9   A cluster must contain at least one original observation.(   R>   R0   t   idt   leftt   rightt   distt   count(   t   selfR_   R`   Ra   Rb   Rc   (    (    s6   /tmp/pip-build-7oUkmx/scipy/scipy/cluster/hierarchy.pyt   __init__Ï  s     				c         C` s=   t  | t ƒ s- t d j t | ƒ ƒ ƒ ‚ n  |  j | j k  S(   Ns$   Can't compare ClusterNode to type {}(   t
   isinstanceR   R>   RK   t   typeRb   (   Rd   t   node(    (    s6   /tmp/pip-build-7oUkmx/scipy/scipy/cluster/hierarchy.pyt   __lt__ä  s    	c         C` s=   t  | t ƒ s- t d j t | ƒ ƒ ƒ ‚ n  |  j | j k S(   Ns$   Can't compare ClusterNode to type {}(   Rf   R   R>   RK   Rg   Rb   (   Rd   Rh   (    (    s6   /tmp/pip-build-7oUkmx/scipy/scipy/cluster/hierarchy.pyt   __gt__ê  s    	c         C` s=   t  | t ƒ s- t d j t | ƒ ƒ ƒ ‚ n  |  j | j k S(   Ns$   Can't compare ClusterNode to type {}(   Rf   R   R>   RK   Rg   Rb   (   Rd   Rh   (    (    s6   /tmp/pip-build-7oUkmx/scipy/scipy/cluster/hierarchy.pyt   __eq__ð  s    	c         C` s   |  j  S(   sK  
        The identifier of the target node.

        For ``0 <= i < n``, `i` corresponds to original observation i.
        For ``n <= i < 2n-1``, `i` corresponds to non-singleton cluster formed
        at iteration ``i-n``.

        Returns
        -------
        id : int
            The identifier of the target node.

        (   R_   (   Rd   (    (    s6   /tmp/pip-build-7oUkmx/scipy/scipy/cluster/hierarchy.pyt   get_idö  s    c         C` s   |  j  S(   s  
        The number of leaf nodes (original observations) belonging to
        the cluster node nd. If the target node is a leaf, 1 is
        returned.

        Returns
        -------
        get_count : int
            The number of leaf nodes below the target node.

        (   Rc   (   Rd   (    (    s6   /tmp/pip-build-7oUkmx/scipy/scipy/cluster/hierarchy.pyt	   get_count  s    c         C` s   |  j  S(   så   
        Return a reference to the left child tree object.

        Returns
        -------
        left : ClusterNode
            The left child of the target node.  If the node is a leaf,
            None is returned.

        (   R`   (   Rd   (    (    s6   /tmp/pip-build-7oUkmx/scipy/scipy/cluster/hierarchy.pyt   get_left  s    c         C` s   |  j  S(   sè   
        Returns a reference to the right child tree object.

        Returns
        -------
        right : ClusterNode
            The left child of the target node.  If the node is a leaf,
            None is returned.

        (   Ra   (   Rd   (    (    s6   /tmp/pip-build-7oUkmx/scipy/scipy/cluster/hierarchy.pyt	   get_right!  s    c         C` s   |  j  d k S(   sª   
        Returns True if the target node is a leaf.

        Returns
        -------
        leafness : bool
            True if the target node is a leaf node.

        N(   R`   R0   (   Rd   (    (    s6   /tmp/pip-build-7oUkmx/scipy/scipy/cluster/hierarchy.pyt   is_leaf.  s    
c         C` s   |  j  S(   N(   R_   (   t   x(    (    s6   /tmp/pip-build-7oUkmx/scipy/scipy/cluster/hierarchy.pyt   <lambda>:  s    c   
      C` s  |  j  } d g d | } t ƒ  } t ƒ  } |  | d <d } g  } xÇ | d k r| | } | j }	 | j ƒ  r | j | | ƒ ƒ | d } qE |	 | k rÇ | j | | d <| j |	 ƒ | d } qE |	 | k rþ | j | | d <| j |	 ƒ | d } qE | d } qE W| S(   s°  
        Performs pre-order traversal without recursive function calls.

        When a leaf node is first encountered, ``func`` is called with
        the leaf node as its argument, and its result is appended to
        the list.

        For example, the statement::

           ids = root.pre_order(lambda x: x.id)

        returns a list of the node ids corresponding to the leaf nodes
        of the tree as they appear from left to right.

        Parameters
        ----------
        func : function
            Applied to each leaf ClusterNode object in the pre-order traversal.
            Given the ``i``-th leaf node in the pre-order traversal ``n[i]``, the
            result of ``func(n[i])`` is stored in ``L[i]``. If not provided,
            the index of the original observation to which the node
            corresponds is used.

        Returns
        -------
        L : list
            The pre-order traversal.

        i   i    i   N(	   Rc   R0   t   setR_   Rp   t   appendR`   t   addRa   (
   Rd   t   funcR]   t   curNodet   lvisitedt   rvisitedt   kt   preordert   ndt   ndid(    (    s6   /tmp/pip-build-7oUkmx/scipy/scipy/cluster/hierarchy.pyt	   pre_order:  s.     			

	N(   R'   R(   t   __doc__R0   Re   Ri   Rj   Rk   Rl   Rm   Rn   Ro   Rp   R~   (    (    (    s6   /tmp/pip-build-7oUkmx/scipy/scipy/cluster/hierarchy.pyR   °  s   								c         C` sŠ   t  ƒ  } t |  ƒ } | j | ƒ g  } x[ | r… | j ƒ  } | j ƒ  s+ t j | | ƒ | j | j ƒ  ƒ | j | j ƒ  ƒ q+ q+ W| S(   sò   
    Returns clustering nodes in bottom-up order by distance.

    Parameters
    ----------
    Z : scipy.cluster.linkage array
        The linkage matrix.

    Returns
    -------
    nodes : list
        A list of ClusterNode objects.
    (	   R   R$   Rt   t   popleftRp   t   bisectt   insort_leftRo   Rn   (   t   Zt   qt   treet   nodesRh   (    (    s6   /tmp/pip-build-7oUkmx/scipy/scipy/cluster/hierarchy.pyt   _order_cluster_tree}  s    		c         C` s÷  t  |  ƒ } t |  ƒ } | d k	 r? | d k	 r? t d ƒ ‚ n | d k ri | d k ri t j | ƒ } ne | d k	 r¯ t j g  | D] } | j ^ q‚ ƒ } t j | | ƒ } n | t j t j | ƒ | ƒ } y t	 | ƒ } Wn) t
 k
 r	d } t j | g ƒ } n Xt j | | f d t ƒ}	 t j | ƒ }
 d | k rM|
 |	 d <n  x  t | ƒ D]’ \ } } | j ƒ  } |
 j ƒ  } |
 | j ƒ  | | <| | |
 | j ƒ  k c d 8<| d | k ræ| |	 t j | d | k ƒ d <n  | }
 qZW|	 j S(   sö  
    Given a linkage matrix Z, return the cut tree.

    Parameters
    ----------
    Z : scipy.cluster.linkage array
        The linkage matrix.
    n_clusters : array_like, optional
        Number of clusters in the tree at the cut point.
    height : array_like, optional
        The height at which to cut the tree.  Only possible for ultrametric
        trees.

    Returns
    -------
    cutree : array
        An array indicating group membership at each agglomeration step.  I.e.,
        for a full cut tree, in the first column each data point is in its own
        cluster.  At the next step, two nodes are merged.  Finally all singleton
        and non-singleton clusters are in one group.  If `n_clusters` or
        `height` is given, the columns correspond to the columns of `n_clusters` or
        `height`.

    Examples
    --------
    >>> from scipy import cluster
    >>> np.random.seed(23)
    >>> X = np.random.randn(50, 4)
    >>> Z = cluster.hierarchy.ward(X)
    >>> cutree = cluster.hierarchy.cut_tree(Z, n_clusters=[5, 10])
    >>> cutree[:10]
    array([[0, 0],
           [1, 1],
           [2, 2],
           [3, 3],
           [3, 4],
           [2, 2],
           [0, 0],
           [1, 5],
           [3, 6],
           [4, 7]])

    s8   At least one of either height or n_clusters must be Nonei   R.   i    N(   R!   R‡   R0   R>   R2   t   arangeR5   Rb   t   searchsortedt   lent	   TypeErrort   zerosRX   t	   enumerateR~   R1   t   mint   maxt   whereR9   (   Rƒ   t
   n_clusterst   heightt   nobsR†   t   cols_idxRq   t   heightst   n_colst   groupst
   last_groupt   iRh   t   idxt
   this_group(    (    s6   /tmp/pip-build-7oUkmx/scipy/scipy/cluster/hierarchy.pyR   ™  s8    ,% $
c         C` sŽ  t  j |  d d ƒ}  t |  d t d d ƒ|  j d d } d g | d d } x' t d | ƒ D] } t | ƒ | | <qa Wd } xò t d | d ƒ D]Ý } t |  | d f ƒ } t |  | d f ƒ } | | | k rê t	 d	 | ƒ ‚ n  | | | k rt	 d
 | ƒ ‚ n  t | | | | | | |  | d f ƒ } |  | d f | j
 k rdt	 d | ƒ ‚ n  | | | | <q• W| r†| | f S| Sd S(   s’  
    Converts a linkage matrix into an easy-to-use tree object.

    The reference to the root `ClusterNode` object is returned (by default).

    Each `ClusterNode` object has a ``left``, ``right``, ``dist``, ``id``,
    and ``count`` attribute. The left and right attributes point to
    ClusterNode objects that were combined to generate the cluster.
    If both are None then the `ClusterNode` object is a leaf node, its count
    must be 1, and its distance is meaningless but set to 0.

    *Note: This function is provided for the convenience of the library
    user. ClusterNodes are not used as input to any of the functions in this
    library.*

    Parameters
    ----------
    Z : ndarray
        The linkage matrix in proper form (see the `linkage`
        function documentation).
    rd : bool, optional
        When False (default), a reference to the root `ClusterNode` object is
        returned.  Otherwise, a tuple ``(r, d)`` is returned. ``r`` is a
        reference to the root node while ``d`` is a list of `ClusterNode`
        objects - one per original entry in the linkage matrix plus entries
        for all clustering steps.  If a cluster id is
        less than the number of samples ``n`` in the data that the linkage
        matrix describes, then it corresponds to a singleton cluster (leaf
        node).
        See `linkage` for more information on the assignment of cluster ids
        to clusters.

    Returns
    -------
    tree : ClusterNode or tuple (ClusterNode, list of ClusterNode)
        If ``rd`` is False, a `ClusterNode`.
        If ``rd`` is True, a list of length ``2*n - 1``, with ``n`` the number
        of samples.  See the description of `rd` above for more details.

    See Also
    --------
    linkage, is_valid_linkage, ClusterNode

    Examples
    --------
    >>> from scipy.cluster import hierarchy
    >>> x = np.random.rand(10).reshape(5, 2)
    >>> Z = hierarchy.linkage(x)
    >>> hierarchy.to_tree(Z)
    <scipy.cluster.hierarchy.ClusterNode object at ...
    >>> rootnode, nodelist = hierarchy.to_tree(Z, rd=True)
    >>> rootnode
    <scipy.cluster.hierarchy.ClusterNode object at ...
    >>> len(nodelist)
    9

    RF   RG   RH   RI   Rƒ   i    i   i   s_   Corrupt matrix Z. Index to derivative cluster is used before it is formed. See row %d, column 0s_   Corrupt matrix Z. Index to derivative cluster is used before it is formed. See row %d, column 1i   s1   Corrupt matrix Z. The count Z[%d,3] is incorrect.N(   R2   RM   R   RP   RR   R0   R   R   RX   R>   Rc   (   Rƒ   t   rdR]   t   dR™   R|   t   fit   fj(    (    s6   /tmp/pip-build-7oUkmx/scipy/scipy/cluster/hierarchy.pyR$   ê  s0    :+
c         C` s@   |  j  t k r! |  j t ƒ }  n  |  j j s< |  j ƒ  }  n  |  S(   N(   R.   t   boolt   astypet   flagst
   contiguousR1   (   t   X(    (    s6   /tmp/pip-build-7oUkmx/scipy/scipy/cluster/hierarchy.pyt   _convert_to_boolK  s
    c         C` sF   |  j  t j k r' |  j t j ƒ }  n  |  j j sB |  j ƒ  }  n  |  S(   N(   R.   R2   R6   R¡   R¢   R£   R1   (   R¤   (    (    s6   /tmp/pip-build-7oUkmx/scipy/scipy/cluster/hierarchy.pyRL   S  s
    c         C` sF  t  j |  d d ƒ}  t |  d t d d ƒ|  j } | d d } t  j | | d d d	 t  j ƒ} t |  ƒ }  t j	 |  | t
 | ƒ ƒ | d k r› | St  j | d d ƒ} t j | d t d d
 ƒ| j ƒ  } | j ƒ  } | | } | | } | | }	 | d }
 | d } |	 j ƒ  t  j |
 j ƒ  | j ƒ  ƒ } | | f S(   s­  
    Calculates the cophenetic distances between each observation in
    the hierarchical clustering defined by the linkage ``Z``.

    Suppose ``p`` and ``q`` are original observations in
    disjoint clusters ``s`` and ``t``, respectively and
    ``s`` and ``t`` are joined by a direct parent cluster
    ``u``. The cophenetic distance between observations
    ``i`` and ``j`` is simply the distance between
    clusters ``s`` and ``t``.

    Parameters
    ----------
    Z : ndarray
        The hierarchical clustering encoded as an array
        (see `linkage` function).
    Y : ndarray (optional)
        Calculates the cophenetic correlation coefficient ``c`` of a
        hierarchical clustering defined by the linkage matrix `Z`
        of a set of :math:`n` observations in :math:`m`
        dimensions. `Y` is the condensed distance matrix from which
        `Z` was generated.

    Returns
    -------
    c : ndarray
        The cophentic correlation distance (if ``Y`` is passed).
    d : ndarray
        The cophenetic distance matrix in condensed form. The
        :math:`ij` th entry is the cophenetic distance between
        original observations :math:`i` and :math:`j`.

    RF   RG   RH   RI   Rƒ   i    i   i   R.   t   YN(   R2   RM   R   RP   RR   RŒ   R6   RL   R   t   cophenetic_distancesRX   R0   R%   RO   t   meant   sumt   sqrt(   Rƒ   R¦   t   ZsR]   t   zzt   zRE   t   Yyt   Zzt	   numeratort   denomAt   denomBRG   (    (    s6   /tmp/pip-build-7oUkmx/scipy/scipy/cluster/hierarchy.pyR   [  s(    "	$




)c         C` sÍ   t  j |  d d ƒ}  |  j } t |  d t d d ƒ| t  j | ƒ k sV | d k  re t d ƒ ‚ n  t |  g ƒ \ }  | d d } t  j | d d	 f d
 t  j	 ƒ} t
 j |  | t | ƒ t | ƒ ƒ | S(   s=  
    Calculates inconsistency statistics on a linkage matrix.

    Parameters
    ----------
    Z : ndarray
        The :math:`(n-1)` by 4 matrix encoding the linkage (hierarchical
        clustering).  See `linkage` documentation for more information on its
        form.
    d : int, optional
        The number of links up to `d` levels below each non-singleton cluster.

    Returns
    -------
    R : ndarray
        A :math:`(n-1)` by 5 matrix where the ``i``'th row contains the link
        statistics for the non-singleton cluster ``i``. The link statistics are
        computed over the link heights for links :math:`d` levels below the
        cluster ``i``. ``R[i,0]`` and ``R[i,1]`` are the mean and standard
        deviation of the link heights, respectively; ``R[i,2]`` is the number
        of links included in the calculation; and ``R[i,3]`` is the
        inconsistency coefficient,

        .. math:: \frac{\mathtt{Z[i,2]} - \mathtt{R[i,0]}} {R[i,1]}

    Notes
    -----
    This function behaves similarly to the MATLAB(TM) ``inconsistent``
    function.

    RF   RG   RH   RI   Rƒ   i    s:   The second argument d must be a nonnegative integer value.i   i   R.   (   R2   RM   RR   R   RP   t   floorR>   R;   RŒ   R6   R   R   RX   (   Rƒ   R   R«   R]   t   R(    (    s6   /tmp/pip-build-7oUkmx/scipy/scipy/cluster/hierarchy.pyR   ™  s     	"""c      	   C` s˜  t  j |  d t  j d d ƒ}  |  j } t | ƒ d k s[ t | ƒ d k re | d d k re |  j ƒ  St | ƒ d k r† t d ƒ ‚ n  | d d k r  |  j ƒ  S|  j ƒ  } | d d … d d … f j ƒ  d	 k r| d d … d d … f j ƒ  d | d k rt d
 ƒ ‚ n  | d d … d d … f c d	 8<t  j	 | d f d t  j ƒ} t
 j | | t | d ƒ d ƒ t  j | | j | d d ƒ g ƒ S(   sÉ  
    Converts a linkage matrix generated by MATLAB(TM) to a new
    linkage matrix compatible with this module.

    The conversion does two things:

     * the indices are converted from ``1..N`` to ``0..(N-1)`` form,
       and

     * a fourth column ``Z[:,3]`` is added where ``Z[i,3]`` represents the
       number of original observations (leaves) in the non-singleton
       cluster ``i``.

    This function is useful when loading in linkages from legacy data
    files generated by MATLAB.

    Parameters
    ----------
    Z : ndarray
        A linkage matrix generated by MATLAB(TM).

    Returns
    -------
    ZS : ndarray
        A linkage matrix compatible with ``scipy.cluster.hierarchy``.

    R.   RF   RG   i    i   i   s&   The linkage array must be rectangular.Ng      ð?s%   The format of the indices is not 1..N(   R2   RM   R6   RR   RŠ   R1   R>   RŽ   R   RŒ   R   t   calculate_cluster_sizesRX   t   hstackt   reshape(   Rƒ   R«   t   Zpartt   CS(    (    s6   /tmp/pip-build-7oUkmx/scipy/scipy/cluster/hierarchy.pyR   Ì  s    	4

X"!c         C` sÃ   t  j |  d d d t  j ƒ}  |  j } t | ƒ d k s[ t | ƒ d k re | d d k re |  j ƒ  St |  d t d d ƒ|  d	 d	 … d d
 … f j ƒ  } | d	 d	 … d d … f c d 7<| S(   sÅ  
    Converts a linkage matrix to a MATLAB(TM) compatible one.

    Converts a linkage matrix ``Z`` generated by the linkage function
    of this module to a MATLAB(TM) compatible one. The return linkage
    matrix has the last column removed and the cluster indices are
    converted to ``1..N`` indexing.

    Parameters
    ----------
    Z : ndarray
        A linkage matrix generated by ``scipy.cluster.hierarchy``.

    Returns
    -------
    to_mlab_linkage : ndarray
        A linkage matrix compatible with MATLAB(TM)'s hierarchical
        clustering functions.

        The return linkage matrix has the last column removed
        and the cluster indices are converted to ``1..N`` indexing.

    RF   RG   R.   i    i   RH   RI   Rƒ   Ni   i   g      ð?(   R2   RM   R6   RR   RŠ   R1   R   RP   (   Rƒ   R«   t   ZP(    (    s6   /tmp/pip-build-7oUkmx/scipy/scipy/cluster/hierarchy.pyR#      s    	4
""c         C` s[   t  j |  d d ƒ}  t |  d t d d ƒ|  d d … d f |  d d	 … d f k j ƒ  S(
   s¿  
    Returns True if the linkage passed is monotonic.

    The linkage is monotonic if for every cluster :math:`s` and :math:`t`
    joined, the distance between them is no less than the distance
    between any previously joined clusters.

    Parameters
    ----------
    Z : ndarray
        The linkage matrix to check for monotonicity.

    Returns
    -------
    b : bool
        A boolean indicating whether the linkage is monotonic.

    RF   RG   RH   RI   Rƒ   i   Ni   iÿÿÿÿ(   R2   RM   R   RP   RU   (   Rƒ   (    (    s6   /tmp/pip-build-7oUkmx/scipy/scipy/cluster/hierarchy.pyR   $  s    c         C` sÚ  t  j |  d d ƒ}  t } | r+ d | n d } ydt |  ƒ t  j k r\ t d | ƒ ‚ n  |  j t  j k r t d | ƒ ‚ n  t |  j	 ƒ d k r© t
 d | ƒ ‚ n  |  j	 d	 d
 k rÏ t
 d | ƒ ‚ n  |  j	 d d	 k  rõ t
 d | ƒ ‚ n  |  d d … d f d k  j ƒ  r*t
 d | ƒ ‚ n  |  d d … d	 f d k  j ƒ  r_t
 d | ƒ ‚ n  |  d d … d f d k  j ƒ  r”t
 d | ƒ ‚ n  Wn> t k
 rÕ} | r³‚  n  | rÌt t | ƒ ƒ n  t } n X| S(   s'  Returns True if the inconsistency matrix passed is valid.

    It must be a :math:`n` by 4 array of doubles. The standard
    deviations ``R[:,1]`` must be nonnegative. The link counts
    ``R[:,2]`` must be positive and no greater than :math:`n-1`.

    Parameters
    ----------
    R : ndarray
        The inconsistency matrix to check for validity.
    warning : bool, optional
         When True, issues a Python warning if the linkage
         matrix passed is invalid.
    throw : bool, optional
         When True, throws a Python exception if the linkage
         matrix passed is invalid.
    name : str, optional
         This string refers to the variable name of the invalid
         linkage matrix.

    Returns
    -------
    b : bool
        True if the inconsistency matrix is valid.

    RF   RG   s   %r t    s?   Variable %spassed as inconsistency matrix is not a numpy array.s5   Inconsistency matrix %smust contain doubles (double).i   sC   Inconsistency matrix %smust have shape=2 (i.e. be two-dimensional).i   i   s+   Inconsistency matrix %smust have 4 columns.i    s2   Inconsistency matrix %smust have at least one row.Ns;   Inconsistency matrix %scontains negative link height means.sI   Inconsistency matrix %scontains negative link height standard deviations.s5   Inconsistency matrix %scontains negative link counts.(   R2   RM   RP   Rg   t   ndarrayR‹   R.   R6   RŠ   RR   R>   t   anyt	   ExceptionR-   t   strt   False(   R´   t   warningRH   RI   t   validt   name_strt   e(    (    s6   /tmp/pip-build-7oUkmx/scipy/scipy/cluster/hierarchy.pyR   >  sF    """
c         C` sR  t  j |  d d ƒ}  t } | r+ d | n d } yÜt |  ƒ t  j k r\ t d | ƒ ‚ n  |  j t  j k r t d | ƒ ‚ n  t |  j	 ƒ d k r© t
 d | ƒ ‚ n  |  j	 d	 d
 k rÏ t
 d | ƒ ‚ n  |  j	 d d k rñ t
 d ƒ ‚ n  |  j	 d } | d	 k rÎ|  d d … d f d k  j ƒ  sN|  d d … d	 f d k  j ƒ  rat
 d | ƒ ‚ n  |  d d … d f d k  j ƒ  r–t
 d | ƒ ‚ n  |  d d … d f d k  j ƒ  rÎt
 d | ƒ ‚ qÎn  t |  ƒ rít
 d | ƒ ‚ n  t |  ƒ rt
 d | ƒ ‚ n  Wn> t k
 rM} | r+‚  n  | rDt t | ƒ ƒ n  t } n X| S(   s  
    Checks the validity of a linkage matrix.

    A linkage matrix is valid if it is a two dimensional array (type double)
    with :math:`n` rows and 4 columns.  The first two columns must contain
    indices between 0 and :math:`2n-1`. For a given row ``i``, the following
    two expressions have to hold:

    .. math::

        0 \leq \mathtt{Z[i,0]} \leq i+n-1
        0 \leq Z[i,1] \leq i+n-1

    I.e. a cluster cannot join another cluster unless the cluster being joined
    has been generated.

    Parameters
    ----------
    Z : array_like
        Linkage matrix.
    warning : bool, optional
        When True, issues a Python warning if the linkage
        matrix passed is invalid.
    throw : bool, optional
        When True, throws a Python exception if the linkage
        matrix passed is invalid.
    name : str, optional
        This string refers to the variable name of the invalid
        linkage matrix.

    Returns
    -------
    b : bool
        True if the inconsistency matrix is valid.

    RF   RG   s   %r R»   s/   Passed linkage argument %sis not a valid array.s&   Linkage matrix %smust contain doubles.i   s=   Linkage matrix %smust have shape=2 (i.e. be two-dimensional).i   i   s%   Linkage matrix %smust have 4 columns.i    s6   Linkage must be computed on at least two observations.Ns$   Linkage %scontains negative indices.s&   Linkage %scontains negative distances.i   s#   Linkage %scontains negative counts.s9   Linkage %suses non-singleton cluster before it is formed.s/   Linkage %suses the same cluster more than once.(   R2   RM   RP   Rg   R¼   R‹   R.   R6   RŠ   RR   R>   R½   t+   _check_hierarchy_uses_cluster_before_formedt,   _check_hierarchy_uses_cluster_more_than_onceR¾   R-   R¿   RÀ   (   Rƒ   RÁ   RH   RI   RÂ   RÃ   R]   RÄ   (    (    s6   /tmp/pip-build-7oUkmx/scipy/scipy/cluster/hierarchy.pyR     sP    %D""
c         C` sk   |  j  d d } xS t d | d ƒ D]> } |  | d f | | k s_ |  | d f | | k r% t Sq% Wt S(   Ni    i   (   RR   R   RP   RÀ   (   Rƒ   R]   R™   (    (    s6   /tmp/pip-build-7oUkmx/scipy/scipy/cluster/hierarchy.pyRÅ   Ð  s
    4c         C` s½   |  j  d d } t g  ƒ } x™ t d | d ƒ D]„ } |  | d f | k sƒ |  | d f | k sƒ |  | d f |  | d f k r‡ t S| j |  | d f ƒ | j |  | d f ƒ q1 Wt S(   Ni    i   (   RR   Rs   R   RP   Ru   RÀ   (   Rƒ   R]   t   chosenR™   (    (    s6   /tmp/pip-build-7oUkmx/scipy/scipy/cluster/hierarchy.pyRÆ   Ø  s    Lc         C` s«   |  j  d d } t g  ƒ } xU t d | d ƒ D]@ } | j t |  | d f ƒ ƒ | j t |  | d f ƒ ƒ q1 Wt t d d | d ƒ ƒ } t | j | ƒ ƒ d k S(   Ni    i   i   (   RR   Rs   R   Ru   RX   t   rangeRŠ   t
   difference(   Rƒ   R]   RÇ   R™   t   must_chosen(    (    s6   /tmp/pip-build-7oUkmx/scipy/scipy/cluster/hierarchy.pyt&   _check_hierarchy_not_all_clusters_usedã  s    !c         C` s:   t  j |  d d ƒ}  t |  d t d d ƒ|  j d d S(   s&  
    Returns the number of original observations of the linkage matrix
    passed.

    Parameters
    ----------
    Z : ndarray
        The linkage matrix on which to perform the operation.

    Returns
    -------
    n : int
        The number of original observations in the linkage.

    RF   RG   RH   RI   Rƒ   i    i   (   R2   RM   R   RP   RR   (   Rƒ   (    (    s6   /tmp/pip-build-7oUkmx/scipy/scipy/cluster/hierarchy.pyR!   í  s    c         C` sf   t  |  d t ƒt j | d t ƒt j |  d d ƒ}  t j | d d ƒ} t j | ƒ t |  ƒ k S(   sÐ  
    Checks for correspondence between linkage and condensed distance matrices

    They must have the same number of original observations for
    the check to succeed.

    This function is useful as a sanity check in algorithms that make
    extensive use of linkage and distance matrices that must
    correspond to the same set of original observations.

    Parameters
    ----------
    Z : array_like
        The linkage matrix to check for correspondence.
    Y : array_like
        The condensed distance matrix to check for correspondence.

    Returns
    -------
    b : bool
        A boolean indicating whether the linkage matrix and distance
        matrix could possibly correspond to one another.

    RH   RF   RG   (   R   RP   R%   RO   R2   RM   RY   R!   (   Rƒ   R¦   (    (    s6   /tmp/pip-build-7oUkmx/scipy/scipy/cluster/hierarchy.pyR     s
    c         C` sý  t  j |  d d ƒ}  t |  d t d d ƒ|  j d d } t  j | f d d	 ƒ} t |  g ƒ \ }  | d
 k rõ | d k r t |  | ƒ } n= t  j | d d ƒ} t	 | d t d d ƒt | g ƒ \ } t
 j |  | | t | ƒ t | ƒ ƒ n| d k r&t
 j |  | t | ƒ t | ƒ ƒ nÓ | d k rWt
 j |  | t | ƒ t | ƒ ƒ n¢ | d k rt | g ƒ \ } t
 j |  | | t | ƒ t | ƒ ƒ n\ | d k rãt | g ƒ \ } t
 j |  | | t | ƒ t | ƒ ƒ n t d t | ƒ ƒ ‚ | S(   s$  
    Forms flat clusters from the hierarchical clustering defined by
    the given linkage matrix.

    Parameters
    ----------
    Z : ndarray
        The hierarchical clustering encoded with the matrix returned
        by the `linkage` function.
    t : float
        The threshold to apply when forming flat clusters.
    criterion : str, optional
        The criterion to use in forming flat clusters. This can
        be any of the following values:

          ``inconsistent`` : If a cluster node and all its
              descendants have an inconsistent value less than or equal
              to `t` then all its leaf descendants belong to the
              same flat cluster. When no non-singleton cluster meets
              this criterion, every node is assigned to its own
              cluster. (Default)

          ``distance`` : Forms flat clusters so that the original
              observations in each flat cluster have no greater a
              cophenetic distance than `t`.

          ``maxclust`` : Finds a minimum threshold ``r`` so that
              the cophenetic distance between any two original
              observations in the same flat cluster is no more than
              ``r`` and no more than `t` flat clusters are formed.

          ``monocrit`` : Forms a flat cluster from a cluster node c
              with index i when ``monocrit[j] <= t``.

              For example, to threshold on the maximum mean distance
              as computed in the inconsistency matrix R with a
              threshold of 0.8 do::

                  MR = maxRstat(Z, R, 3)
                  cluster(Z, t=0.8, criterion='monocrit', monocrit=MR)

          ``maxclust_monocrit`` : Forms a flat cluster from a
              non-singleton cluster node ``c`` when ``monocrit[i] <=
              r`` for all cluster indices ``i`` below and including
              ``c``. ``r`` is minimized such that no more than ``t``
              flat clusters are formed. monocrit must be
              monotonic. For example, to minimize the threshold t on
              maximum inconsistency values so that no more than 3 flat
              clusters are formed, do::

                  MI = maxinconsts(Z, R)
                  cluster(Z, t=3, criterion='maxclust_monocrit', monocrit=MI)

    depth : int, optional
        The maximum depth to perform the inconsistency calculation.
        It has no meaning for the other criteria. Default is 2.
    R : ndarray, optional
        The inconsistency matrix to use for the 'inconsistent'
        criterion. This matrix is computed if not provided.
    monocrit : ndarray, optional
        An array of length n-1. `monocrit[i]` is the
        statistics upon which non-singleton i is thresholded. The
        monocrit vector must be monotonic, i.e. given a node c with
        index i, for all node indices j corresponding to nodes
        below c, ``monocrit[i] >= monocrit[j]``.

    Returns
    -------
    fcluster : ndarray
        An array of length ``n``. ``T[i]`` is the flat cluster number to
        which original observation ``i`` belongs.

    RF   RG   RH   RI   Rƒ   i    i   R.   R™   R   R´   R%   t   maxclustt   monocritt   maxclust_monocrits'   Invalid cluster formation criterion: %sN(   R2   RM   R   RP   RR   RŒ   R;   R0   R   R   R   t
   cluster_int   floatRX   t   cluster_distt   cluster_maxclust_distt   cluster_monocritt   cluster_maxclust_monocritR>   R¿   (   Rƒ   t   tt	   criteriont   depthR´   RÍ   R]   R9   (    (    s6   /tmp/pip-build-7oUkmx/scipy/scipy/cluster/hierarchy.pyR   "  s2    J(%%((c   
      C` sÜ   t  j |  d d d t  j ƒ}  t |  ƒ t  j k sH t |  j ƒ d k rW t d ƒ ‚ n  t j	 |  d | ƒ} t
 | d | ƒ} | d k rŸ t | d | ƒ} n t  j | d d ƒ} t | d	 | d
 | d | d | ƒ}	 |	 S(   sç  
    Cluster observation data using a given metric.

    Clusters the original observations in the n-by-m data
    matrix X (n observations in m dimensions), using the euclidean
    distance metric to calculate distances between original observations,
    performs hierarchical clustering using the single linkage algorithm,
    and forms flat clusters using the inconsistency method with `t` as the
    cut-off threshold.

    A one-dimensional array ``T`` of length ``n`` is returned. ``T[i]`` is
    the index of the flat cluster to which the original observation ``i``
    belongs.

    Parameters
    ----------
    X : (N, M) ndarray
        N by M data matrix with N observations in M dimensions.
    t : float
        The threshold to apply when forming flat clusters.
    criterion : str, optional
        Specifies the criterion for forming flat clusters.  Valid
        values are 'inconsistent' (default), 'distance', or 'maxclust'
        cluster formation algorithms. See `fcluster` for descriptions.
    metric : str, optional
        The distance metric for calculating pairwise distances. See
        ``distance.pdist`` for descriptions and linkage to verify
        compatibility with the linkage method.
    depth : int, optional
        The maximum depth for the inconsistency calculation. See
        `inconsistent` for more information.
    method : str, optional
        The linkage method to use (single, complete, average,
        weighted, median centroid, ward). See `linkage` for more
        information. Default is "single".
    R : ndarray, optional
        The inconsistency matrix. It will be computed if necessary
        if it is not passed.

    Returns
    -------
    fclusterdata : ndarray
        A vector of length n. T[i] is the flat cluster number to
        which original observation i belongs.

    See Also
    --------
    scipy.spatial.distance.pdist : pairwise distance metrics

    Notes
    -----
    This function is similar to the MATLAB function ``clusterdata``.

    RF   RG   R.   i   s7   The observation matrix X must be an n by m numpy array.RC   RB   R   RÖ   R×   R´   RÕ   N(   R2   RM   R6   Rg   R¼   RŠ   RR   R‹   R%   RV   R   R0   R   R   (
   R¤   RÕ   RÖ   RC   R×   RB   R´   R¦   Rƒ   R9   (    (    s6   /tmp/pip-build-7oUkmx/scipy/scipy/cluster/hierarchy.pyR     s    8*$c         C` sƒ   t  j |  d d ƒ}  t |  d t d d ƒ|  j d d } t  j | f d d	 ƒ} t |  g ƒ \ }  t j |  | t	 | ƒ ƒ | S(
   s´  
    Returns a list of leaf node ids

    The return corresponds to the observation vector index as it appears
    in the tree from left to right. Z is a linkage matrix.

    Parameters
    ----------
    Z : ndarray
        The hierarchical clustering encoded as a matrix.  `Z` is
        a linkage matrix.  See `linkage` for more information.

    Returns
    -------
    leaves_list : ndarray
        The list of leaf node ids.

    RF   RG   RH   RI   Rƒ   i    i   R.   R™   (
   R2   RM   R   RP   RR   RŒ   R;   R   t   prelistRX   (   Rƒ   R]   t   ML(    (    s6   /tmp/pip-build-7oUkmx/scipy/scipy/cluster/hierarchy.pyR   Ø  s    i   i   i
   i   i   i2   iU   i-   i(   iZ   c         C` sP   t  g  ƒ } g  } x7 |  D]/ } | | k r | j | ƒ | j | ƒ q q W| S(   s~   
    Removes duplicates AND preserves the original order of the elements.
    The set class is not guaranteed to do this.
    (   Rs   Ru   Rt   (   t   Lt   seen_beforet   L2R™   (    (    s6   /tmp/pip-build-7oUkmx/scipy/scipy/cluster/hierarchy.pyt   _remove_dups  s    c         C` s)   x" t  D] } |  | k r t | Sq Wd  S(   N(   t   _dtextsortedkeyst   _dtextsizes(   t   pRz   (    (    s6   /tmp/pip-build-7oUkmx/scipy/scipy/cluster/hierarchy.pyt   _get_tick_text_size  s    c         C` s)   x" t  D] } |  | k r t | Sq Wd  S(   N(   t   _drotationsortedkeyst
   _drotation(   Rà   Rz   (    (    s6   /tmp/pip-build-7oUkmx/scipy/scipy/cluster/hierarchy.pyt   _get_tick_rotation  s    t   bc   #      C` s`  y7 | d  k r d d  l } n  d d  l } d d  l } Wn t k
 rV t d ƒ ‚ n X| d  k r{ | j j ƒ  } t } n t } t	 | ƒ d } | | d } t
 j d t	 | ƒ d d d ƒ } | d k r(| d k r| j d | g ƒ | j d | g ƒ n& | j | d g ƒ | j d | g ƒ |  } | } | rX| j g  ƒ | j g  ƒ q†| j | ƒ | d k r„| j j d ƒ n | j j d ƒ x! | j ƒ  D] } | j t ƒ q¡W|
 d  k rÜt t t	 | ƒ ƒ ƒ n |
 } |	 d  k rt t t	 | ƒ ƒ ƒ n |	 } | j | d | d	 | ƒn^| d k r†| d
 k ri| j | d g ƒ | j d | g ƒ n& | j d | g ƒ | j d | g ƒ | } |  } | r¾| j g  ƒ | j g  ƒ q†| j | ƒ | d
 k rê| j j d ƒ n | j j d
 ƒ x! | j ƒ  D] } | j t ƒ qW|	 d  k rBt t t	 | ƒ ƒ ƒ n |	 } |
 d  k	 rp| j | d |
 d	 | ƒq†| j | d	 | ƒn  t | ƒ } i  } x | D] } g  | | <qŸWxC t | | | ƒ D]/ \ } } } | | j t t | | ƒ ƒ ƒ qÆWi  } x7 | D]/ } | j j  | | d | f ƒ} | | | <qWx. | D]& } | | k r@| j! | | ƒ q@q@W| | k rŠ| j! | | ƒ n  | d  k	 rF| j" j# } x¡ | D]– \ }  }! | d k ræ| |! |  f d | d d d ƒ}" n" | |  |! f d d d | d ƒ}" | j$ |" ƒ |" j% | j& ƒ |" j' d ƒ |" j( d ƒ q©Wn  | r\| j j) ƒ  n  d  S(   Ni    s~   You must install the matplotlib library to plot the dendrogram. Use no_plot=True to calculate the dendrogram without plotting.i
   gš™™™™™©?i   t   topt   bottomt   rotationt   sizeR`   Ra   t   colorst   widthid   R’   g      ð?g      à?Rz   (   s   topRç   (   s   lefts   right(   s   lefts   right(*   R0   t   matplotlib.pylabt   matplotlib.patchest   matplotlib.collectionst   ImportErrort   pylabt   gcaRP   RÀ   RŠ   R2   Rˆ   t   set_ylimt   set_xlimt
   set_xtickst   set_xticklabelst   xaxist   set_ticks_positiont   get_xticklinest   set_visibleRÐ   Rä   Rá   t
   set_ytickst   set_yticklabelst   yaxist   get_yticklinesRÝ   t   zipRt   t   listt   collectionst   LineCollectiont   add_collectiont   patchest   Ellipset
   add_artistt   set_clip_boxt   bboxt	   set_alphat   set_facecolort   draw_if_interactive(#   t   icoordst   dcoordst   ivlRà   R]   t   mht   orientationt	   no_labelst
   color_listt   leaf_font_sizet   leaf_rotationt   contraction_markst   axt   above_threshold_colort
   matplotlibt   trigger_redrawt   ivwt   dvwt   iv_tickst   xlinest   ylinest   linet   leaf_rott	   leaf_fontt   colors_usedt   color_to_linest   colort   xlinet   ylinet   colors_to_collectionst   collR  Rq   RE   RÄ   (    (    s6   /tmp/pip-build-7oUkmx/scipy/scipy/cluster/hierarchy.pyt   _plot_dendrogram  s¦    	#***"$%"t   gt   rRG   t   mRE   Rz   c         C` sÆ   |  d	 k r' d d d d d d g }  n' t |  ƒ t t f k rN t d ƒ ‚ n  g  |  D] } t | t ƒ ^ qU } t | k r‹ t d ƒ ‚ n  x! t t ƒ D] } t j	 | ƒ q˜ Wt j
 t |  ƒ ƒ d	 S(
   sæ  
    Set list of matplotlib color codes for use by dendrogram.

    Note that this palette is global (i.e. setting it once changes the colors
    for all subsequent calls to `dendrogram`) and that it affects only the
    the colors below ``color_threshold``.

    Note that `dendrogram` also accepts a custom coloring function through its
    ``link_color_func`` keyword, which is more flexible and non-global.

    Parameters
    ----------
    palette : list of str or None
        A list of matplotlib color codes.  The order of the color codes is the
        order in which the colors are cycled through when color thresholding in
        the dendrogram.

        If ``None``, resets the palette to its default (which is
        ``['g', 'r', 'c', 'm', 'y', 'k']``).

    Returns
    -------
    None

    See Also
    --------
    dendrogram

    Notes
    -----
    Ability to reset the palette with ``None`` added in Scipy 0.17.0.

    Examples
    --------
    >>> from scipy.cluster import hierarchy
    >>> ytdist = np.array([662., 877., 255., 412., 996., 295., 468., 268., 400.,
    ...                    754., 564., 138., 219., 869., 669.])
    >>> Z = hierarchy.linkage(ytdist, 'single')
    >>> dn = hierarchy.dendrogram(Z, no_plot=True)
    >>> dn['color_list']
    ['g', 'b', 'b', 'b', 'b']
    >>> hierarchy.set_link_color_palette(['c', 'm', 'y', 'k'])
    >>> dn = hierarchy.dendrogram(Z, no_plot=True)
    >>> dn['color_list']
    ['c', 'b', 'b', 'b', 'b']
    >>> dn = hierarchy.dendrogram(Z, no_plot=True, color_threshold=267,
    ...                           above_threshold_color='k')
    >>> dn['color_list']
    ['c', 'm', 'm', 'k', 'k']

    Now reset the color palette to its default:

    >>> hierarchy.set_link_color_palette(None)

    R)  R*  RG   R+  RE   Rz   s   palette must be a list or tuples/   all palette list elements must be color stringsN(   R0   Rg   Rÿ   t   tupleR‹   Rf   R   RÀ   t   _link_line_colorst   removet   extend(   t   paletteRà   t   _ptypesR™   (    (    s6   /tmp/pip-build-7oUkmx/scipy/scipy/cluster/hierarchy.pyR"   ¦  s    8"Ræ   c      5   C` s  t  j |  d d ƒ}  | d d d d g k r< t d ƒ ‚ n  t |  d t d	 d
 ƒ|  j } | d d } t | ƒ t t f k r t | ƒ } n t	 d ƒ ‚ | d d d d d t
 f k rÉ t d ƒ ‚ n  | d k pÞ | d k r| | k pö | d k r| } n  n  | d k rd } n  | d k rA| d k r>t  j } n  n  | rPg  } n t
 } g  } g  } g  } d g } t g } g  } | t
 k p¤t | t ƒ o¤| d k rÊt |  d d … d f ƒ d } n  i | d 6| d 6| d 6| d 6| d 6} | rÿg  n t
 } t d
 |  d | d | d | d  | d! | d" | d# | d$ | d% |	 d& d | d d' d( d | d) | d* | d+ | d, | d- | d | d. | d/ | d0 | d1 | d2 | ƒ |
 r
t |  d d … d f ƒ } t | | | | | | | | | d3 | d4 | d0 | d5 | d2 | ƒ	n  | S(6   s¥(  
    Plots the hierarchical clustering as a dendrogram.

    The dendrogram illustrates how each cluster is
    composed by drawing a U-shaped link between a non-singleton
    cluster and its children.  The top of the U-link indicates a
    cluster merge.  The two legs of the U-link indicate which clusters
    were merged.  The length of the two legs of the U-link represents
    the distance between the child clusters.  It is also the
    cophenetic distance between original observations in the two
    children clusters.

    Parameters
    ----------
    Z : ndarray
        The linkage matrix encoding the hierarchical clustering to
        render as a dendrogram. See the ``linkage`` function for more
        information on the format of ``Z``.
    p : int, optional
        The ``p`` parameter for ``truncate_mode``.
    truncate_mode : str, optional
        The dendrogram can be hard to read when the original
        observation matrix from which the linkage is derived is
        large. Truncation is used to condense the dendrogram. There
        are several modes:

        ``None``
          No truncation is performed (default).
          Note: ``'none'`` is an alias for ``None`` that's kept for
          backward compatibility.

        ``'lastp'``
          The last ``p`` non-singleton clusters formed in the linkage are the
          only non-leaf nodes in the linkage; they correspond to rows
          ``Z[n-p-2:end]`` in ``Z``. All other non-singleton clusters are
          contracted into leaf nodes.

        ``'level'``
          No more than ``p`` levels of the dendrogram tree are displayed.
          A "level" includes all nodes with ``p`` merges from the last merge.

          Note: ``'mtica'`` is an alias for ``'level'`` that's kept for
          backward compatibility.

    color_threshold : double, optional
        For brevity, let :math:`t` be the ``color_threshold``.
        Colors all the descendent links below a cluster node
        :math:`k` the same color if :math:`k` is the first node below
        the cut threshold :math:`t`. All links connecting nodes with
        distances greater than or equal to the threshold are colored
        blue. If :math:`t` is less than or equal to zero, all nodes
        are colored blue. If ``color_threshold`` is None or
        'default', corresponding with MATLAB(TM) behavior, the
        threshold is set to ``0.7*max(Z[:,2])``.
    get_leaves : bool, optional
        Includes a list ``R['leaves']=H`` in the result
        dictionary. For each :math:`i`, ``H[i] == j``, cluster node
        ``j`` appears in position ``i`` in the left-to-right traversal
        of the leaves, where :math:`j < 2n-1` and :math:`i < n`.
    orientation : str, optional
        The direction to plot the dendrogram, which can be any
        of the following strings:

        ``'top'``
          Plots the root at the top, and plot descendent links going downwards.
          (default).

        ``'bottom'``
          Plots the root at the bottom, and plot descendent links going
          upwards.

        ``'left'``
          Plots the root at the left, and plot descendent links going right.

        ``'right'``
          Plots the root at the right, and plot descendent links going left.

    labels : ndarray, optional
        By default ``labels`` is None so the index of the original observation
        is used to label the leaf nodes.  Otherwise, this is an :math:`n`
        -sized list (or tuple). The ``labels[i]`` value is the text to put
        under the :math:`i` th leaf node only if it corresponds to an original
        observation and not a non-singleton cluster.
    count_sort : str or bool, optional
        For each node n, the order (visually, from left-to-right) n's
        two descendent links are plotted is determined by this
        parameter, which can be any of the following values:

        ``False``
          Nothing is done.

        ``'ascending'`` or ``True``
          The child with the minimum number of original objects in its cluster
          is plotted first.

        ``'descendent'``
          The child with the maximum number of original objects in its cluster
          is plotted first.

        Note ``distance_sort`` and ``count_sort`` cannot both be True.
    distance_sort : str or bool, optional
        For each node n, the order (visually, from left-to-right) n's
        two descendent links are plotted is determined by this
        parameter, which can be any of the following values:

        ``False``
          Nothing is done.

        ``'ascending'`` or ``True``
          The child with the minimum distance between its direct descendents is
          plotted first.

        ``'descending'``
          The child with the maximum distance between its direct descendents is
          plotted first.

        Note ``distance_sort`` and ``count_sort`` cannot both be True.
    show_leaf_counts : bool, optional
         When True, leaf nodes representing :math:`k>1` original
         observation are labeled with the number of observations they
         contain in parentheses.
    no_plot : bool, optional
        When True, the final rendering is not performed. This is
        useful if only the data structures computed for the rendering
        are needed or if matplotlib is not available.
    no_labels : bool, optional
        When True, no labels appear next to the leaf nodes in the
        rendering of the dendrogram.
    leaf_rotation : double, optional
        Specifies the angle (in degrees) to rotate the leaf
        labels. When unspecified, the rotation is based on the number of
        nodes in the dendrogram (default is 0).
    leaf_font_size : int, optional
        Specifies the font size (in points) of the leaf labels. When
        unspecified, the size based on the number of nodes in the
        dendrogram.
    leaf_label_func : lambda or function, optional
        When leaf_label_func is a callable function, for each
        leaf with cluster index :math:`k < 2n-1`. The function
        is expected to return a string with the label for the
        leaf.

        Indices :math:`k < n` correspond to original observations
        while indices :math:`k \geq n` correspond to non-singleton
        clusters.

        For example, to label singletons with their node id and
        non-singletons with their id, count, and inconsistency
        coefficient, simply do::

            # First define the leaf label function.
            def llf(id):
                if id < n:
                    return str(id)
                else:
                    return '[%d %d %1.2f]' % (id, count, R[n-id,3])
            # The text for the leaf nodes is going to be big so force
            # a rotation of 90 degrees.
            dendrogram(Z, leaf_label_func=llf, leaf_rotation=90)

    show_contracted : bool, optional
        When True the heights of non-singleton nodes contracted
        into a leaf node are plotted as crosses along the link
        connecting that leaf node.  This really is only useful when
        truncation is used (see ``truncate_mode`` parameter).
    link_color_func : callable, optional
        If given, `link_color_function` is called with each non-singleton id
        corresponding to each U-shaped link it will paint. The function is
        expected to return the color to paint the link, encoded as a matplotlib
        color string code. For example::

            dendrogram(Z, link_color_func=lambda k: colors[k])

        colors the direct links below each untruncated non-singleton node
        ``k`` using ``colors[k]``.
    ax : matplotlib Axes instance, optional
        If None and `no_plot` is not True, the dendrogram will be plotted
        on the current axes.  Otherwise if `no_plot` is not True the
        dendrogram will be plotted on the given ``Axes`` instance. This can be
        useful if the dendrogram is part of a more complex figure.
    above_threshold_color : str, optional
        This matplotlib color string sets the color of the links above the
        color_threshold. The default is 'b'.

    Returns
    -------
    R : dict
        A dictionary of data structures computed to render the
        dendrogram. Its has the following keys:

        ``'color_list'``
          A list of color names. The k'th element represents the color of the
          k'th link.

        ``'icoord'`` and ``'dcoord'``
          Each of them is a list of lists. Let ``icoord = [I1, I2, ..., Ip]``
          where ``Ik = [xk1, xk2, xk3, xk4]`` and ``dcoord = [D1, D2, ..., Dp]``
          where ``Dk = [yk1, yk2, yk3, yk4]``, then the k'th link painted is
          ``(xk1, yk1)`` - ``(xk2, yk2)`` - ``(xk3, yk3)`` - ``(xk4, yk4)``.

        ``'ivl'``
          A list of labels corresponding to the leaf nodes.

        ``'leaves'``
          For each i, ``H[i] == j``, cluster node ``j`` appears in position
          ``i`` in the left-to-right traversal of the leaves, where
          :math:`j < 2n-1` and :math:`i < n`. If ``j`` is less than ``n``, the
          ``i``-th leaf node corresponds to an original observation.
          Otherwise, it corresponds to a non-singleton cluster.

    See Also
    --------
    linkage, set_link_color_palette

    Notes
    -----
    It is expected that the distances in ``Z[:,2]`` be monotonic, otherwise
    crossings appear in the dendrogram.

    Examples
    --------
    >>> from scipy.cluster import hierarchy
    >>> import matplotlib.pyplot as plt

    A very basic example:

    >>> ytdist = np.array([662., 877., 255., 412., 996., 295., 468., 268.,
    ...                    400., 754., 564., 138., 219., 869., 669.])
    >>> Z = hierarchy.linkage(ytdist, 'single')
    >>> plt.figure()
    >>> dn = hierarchy.dendrogram(Z)

    Now plot in given axes, improve the color scheme and use both vertical and
    horizontal orientations:

    >>> hierarchy.set_link_color_palette(['m', 'c', 'y', 'k'])
    >>> fig, axes = plt.subplots(1, 2, figsize=(8, 3))
    >>> dn1 = hierarchy.dendrogram(Z, ax=axes[0], above_threshold_color='y',
    ...                            orientation='top')
    >>> dn2 = hierarchy.dendrogram(Z, ax=axes[1], above_threshold_color='#bcbddc',
    ...                            orientation='right')
    >>> hierarchy.set_link_color_palette(None)  # reset to default after use
    >>> plt.show()

    RF   RG   Ræ   R`   Rç   Ra   s>   orientation must be one of 'top', 'left', 'bottom', or 'right'RH   RI   Rƒ   i    i   s$   The second argument must be a numbert   lastpt   mlabt   mticat   levelt   nones   Invalid truncation mode.t   defaultNi   gffffffæ?t   icoordt   dcoordR  t   leavesR  Rà   t   truncate_modet   color_thresholdt
   get_leavesR  t   labelst
   count_sortt   distance_sortt   show_leaf_countsR™   t   ivg        R]   t   icoord_listt   dcoord_listt   lvst   current_colort   currently_below_thresholdt   leaf_label_funcR  t   link_color_funcR  R  R  R  (   R2   RM   R>   R   RP   RR   Rg   RX   RÐ   R‹   R0   t   infRÀ   Rf   R   R   t   _dendrogram_calculate_infoR(  (   Rƒ   Rà   R;  R<  R=  R  R>  R?  R@  RA  t   no_plotR  R  R  RH  t   show_contractedRI  R  R  R«   R]   RE  RC  RD  R  RF  RG  R  R´   R  R  (    (    s6   /tmp/pip-build-7oUkmx/scipy/scipy/cluster/hierarchy.pyR   í  sŠ    ÿ 					#	
c	   	      C` sš   | d  k	 r" | j t | ƒ ƒ n  | d  k	 r– | rP | j | t | ƒ ƒ ƒ q– | d  k	 rz | j | t | | ƒ ƒ q– | j t t | ƒ ƒ ƒ n  d  S(   N(   R0   Rt   RX   R¿   (	   Rƒ   Rà   R]   R5  RE  R  RH  R™   R>  (    (    s6   /tmp/pip-build-7oUkmx/scipy/scipy/cluster/hierarchy.pyt   _append_singleton_leaf_nodeL	  s    c
   
      C` sœ   | d  k	 r" | j t | ƒ ƒ n  | d  k	 r˜ | rP | j | t | ƒ ƒ ƒ q˜ |	 rˆ | j d t t |  | | d f ƒ ƒ d ƒ q˜ | j d ƒ n  d  S(   Nt   (i   t   )R»   (   R0   Rt   RX   R¿   (
   Rƒ   Rà   R]   R5  RE  R  RH  R™   R>  RA  (    (    s6   /tmp/pip-build-7oUkmx/scipy/scipy/cluster/hierarchy.pyt   _append_nonsingleton_leaf_nodef	  s    2c         C` sX   t  |  | t |  | | d f ƒ | | ƒ t  |  | t |  | | d f ƒ | | ƒ d  S(   Ni    i   (   t   _append_contraction_marks_subRX   (   Rƒ   RB  R™   R]   R  (    (    s6   /tmp/pip-build-7oUkmx/scipy/scipy/cluster/hierarchy.pyt   _append_contraction_marksx	  s    *c         C` sˆ   | | k r„ | j  | |  | | d f f ƒ t |  | t |  | | d f ƒ | | ƒ t |  | t |  | | d f ƒ | | ƒ n  d  S(   Ni   i    i   (   Rt   RR  RX   (   Rƒ   RB  R™   R]   R  (    (    s6   /tmp/pip-build-7oUkmx/scipy/scipy/cluster/hierarchy.pyRR  }	  s    !*iÿÿÿÿg        c   0   7   C` s¸  | d k r t  d ƒ ‚ n  |
 d k r6 t  d ƒ ‚ n  | d k r!d | | |
 k oa | k n rÜ |  |
 | d f } t |  | | | | | | |
 | |	 ƒ
 | d* k	 rÈ t |  | d |
 | | ƒ n  | d d d	 | f S|
 | k  r%t |  | | | | | | |
 | ƒ	 | d d d	 d	 f Sn| d
 k r |
 | k r»| | k r»|  |
 | d f } t |  | | | | | | |
 | |	 ƒ
 | d* k	 r§t |  | d |
 | | ƒ n  | d d d	 | f S|
 | k  r%t |  | | | | | | |
 | ƒ	 | d d d	 d	 f Sn% | d+ k r%d } t j | t ƒ n  |
 | k  rgt |  | | | | | | |
 | ƒ	 | d d d	 d	 f St |  |
 | d f ƒ } t |  |
 | d f ƒ } | | k rÒ|  | | d f } |  | | d f } n d } d	 } | | k r|  | | d f }  |  | | d f }! n d }  d	 }! | d k s9| t	 k rc| |  k rT| }" | }# q| }" | }# nº | d k r™| |  k rŠ| }" | }# q| }" | }# n„ | d k s±| t	 k rÛ| |! k rÌ| }" | }# q| }" | }# nB | d k r| |! k r| }" | }# q| }" | }# n | }" | }# t
 d |  d | d | d | d | d | d | d | d | d |	 d |" d | d | d | d | d  | d! | d" | d# | d$ | d% | d
 | d d& | d' | d( | ƒ \ }$ }% }& }' |  |
 | d f }( |( | k sø| d k r4| }) | d r'| d d t t ƒ | d <n  t | d <n t	 | d <t | d }) t
 d |  d | d | d | d | d | d | d | d | d |	 d |# d | |% d | d | d | d  | d! | d" | d# | d$ | d% | d
 | d d& | d' | d( | ƒ \ }* }+ }, }- t |' |- |( ƒ }. | j |$ |$ |* |* g ƒ | j |& |( |( |, g ƒ | d* k	 r| t |
 ƒ ƒ }/ t |/ t ƒ st d) ƒ ‚ n  | j |/ ƒ n | j |) ƒ |$ |* d |% |+ |( |. f S(,   s¸  
    Calculates the endpoints of the links as well as the labels for the
    the dendrogram rooted at the node with index i. iv is the independent
    variable value to plot the left-most leaf node below the root node i
    (if orientation='top', this would be the left-most x value where the
    plotting of this root node i and its descendents should begin).

    ivl is a list to store the labels of the leaf nodes. The leaf_label_func
    is called whenever ivl != None, labels == None, and
    leaf_label_func != None. When ivl != None and labels != None, the
    labels list is used only for labeling the leaf nodes. When
    ivl == None, no labels are generated for leaf nodes.

    When get_leaves==True, a list of leaves is built as they are visited
    in the dendrogram.

    Returns a tuple with l being the independent variable coordinate that
    corresponds to the midpoint of cluster to the left of cluster i if
    i is non-singleton, otherwise the independent coordinate of the leaf
    node if i is a leaf node.

    Returns
    -------
    A tuple (left, w, h, md), where:

      * left is the independent variable coordinate of the center of the
        the U of the subtree

      * w is the amount of space used for the subtree (in independent
        variable units)

      * h is the height of the subtree in dependent variable units

      * md is the ``max(Z[*,2]``) for all nodes ``*`` below and including
        the target node.

    i    s"   Invalid singleton cluster count n.iÿÿÿÿs   Invalid root cluster index i.R2  i   g      @g      $@g        R5  R3  s<   Mode 'mlab' is deprecated in scipy 0.19.0 (it never worked).i   i   t	   ascendingt
   descendingRƒ   Rà   R;  R<  R=  R  R>  R?  R@  RA  R™   RB  R  R]   RC  RD  RE  RF  R  RG  RH  R  RI  R  s6   link_color_func must return a matplotlib color string!N(   s   mlab(   R>   RQ  R0   RS  RN  R*   R+   t   DeprecationWarningRX   RP   RK  RŠ   R-  RÀ   R   Rt   Rf   R   R‹   (0   Rƒ   Rà   R;  R<  R=  R  R>  R?  R@  RA  R™   RB  R  R]   RC  RD  RE  t   mhrRF  R  RG  RH  R5  R  RI  R  R   t   msgt   aat   abt   nat   dat   nbt   dbt   uat   ubt   uivat   uwat   uaht   uamdt   hRG   t   uivbt   uwbt   ubht   ubmdt   max_distt   v(    (    s6   /tmp/pip-build-7oUkmx/scipy/scipy/cluster/hierarchy.pyRK  „	  s
   2$										

c         C` s°  t  j |  d d ƒ}  t  j | d d ƒ} t |  ƒ t  j k rN t d ƒ ‚ n  t | ƒ t  j k rr t d ƒ ‚ n  |  j } | j } t | ƒ d k r¥ t d ƒ ‚ n  t | ƒ d k rÆ t d ƒ ‚ n  | d | d k ré t d	 ƒ ‚ n  | d } i  } i  } xª t d | ƒ D]™ } |  | | k rp| | | k r9t	 S| |  | | | k si| | | |  | k r¨t	 Sq| | | k r„t	 S| | | |  | <|  | | | | <qWt
 S(
   s’  
    Determines if two different cluster assignments are equivalent.

    Parameters
    ----------
    T1 : array_like
        An assignment of singleton cluster ids to flat cluster ids.
    T2 : array_like
        An assignment of singleton cluster ids to flat cluster ids.

    Returns
    -------
    b : bool
        Whether the flat cluster assignments `T1` and `T2` are
        equivalent.

    RF   RG   s   T1 must be a numpy array.s   T2 must be a numpy array.i   s   T1 must be one-dimensional.s   T2 must be one-dimensional.i    s0   T1 and T2 must have the same number of elements.(   R2   RM   Rg   R¼   R‹   RR   RŠ   R>   R   RÀ   RP   (   t   T1t   T2t   T1St   T2SR]   t   d1t   d2R™   (    (    s6   /tmp/pip-build-7oUkmx/scipy/scipy/cluster/hierarchy.pyR   m
  s8    		
0c         C` sŠ   t  j |  d d d t  j ƒ}  t |  d t d d ƒ|  j d d } t  j | d f ƒ } t |  g ƒ \ }  t j	 |  | t
 | ƒ ƒ | S(	   s^  
    Returns the maximum distance between any non-singleton cluster.

    Parameters
    ----------
    Z : ndarray
        The hierarchical clustering encoded as a matrix. See
        ``linkage`` for more information.

    Returns
    -------
    maxdists : ndarray
        A ``(n-1)`` sized numpy array of doubles; ``MD[i]`` represents
        the maximum distance between any cluster (including
        singletons) below and including the node with index i. More
        specifically, ``MD[i] = Z[Q(i)-n, 2].max()`` where ``Q(i)`` is the
        set of all node indices below and including node i.

    RF   RG   R.   RH   RI   Rƒ   i    i   (   R2   RM   R6   R   RP   RR   RŒ   R;   R   t   get_max_dist_for_each_clusterRX   (   Rƒ   R]   t   MD(    (    s6   /tmp/pip-build-7oUkmx/scipy/scipy/cluster/hierarchy.pyR   ¡
  s    c         C` sá   t  j |  d d ƒ}  t  j | d d ƒ} t |  d t d d ƒt | d t d d ƒ|  j d d } |  j d | j d k r t d	 ƒ ‚ n  t  j | d f ƒ } t |  | g ƒ \ }  } t	 j
 |  | | t | ƒ d
 ƒ | S(   sœ  
    Returns the maximum inconsistency coefficient for each
    non-singleton cluster and its descendents.

    Parameters
    ----------
    Z : ndarray
        The hierarchical clustering encoded as a matrix. See
        `linkage` for more information.
    R : ndarray
        The inconsistency matrix.

    Returns
    -------
    MI : ndarray
        A monotonic ``(n-1)``-sized numpy array of doubles.

    RF   RG   RH   RI   Rƒ   R´   i    i   sQ   The inconsistency matrix and linkage matrix each have a different number of rows.i   (   R2   RM   R   RP   R   RR   R>   RŒ   R;   R   t   get_max_Rfield_for_each_clusterRX   (   Rƒ   R´   R]   t   MI(    (    s6   /tmp/pip-build-7oUkmx/scipy/scipy/cluster/hierarchy.pyR    ¿
  s    c         C` s)  t  j |  d d ƒ}  t  j | d d ƒ} t |  d t d d ƒt | d t d d ƒt | ƒ t k	 rw t d ƒ ‚ n  | d k  s | d	 k rž t d
 ƒ ‚ n  |  j	 d | j	 d k rÇ t d ƒ ‚ n  |  j	 d d } t  j
 | d f ƒ } t |  | g ƒ \ }  } t j |  | | t | ƒ | ƒ | S(   s¿  
    Returns the maximum statistic for each non-singleton cluster and
    its descendents.

    Parameters
    ----------
    Z : array_like
        The hierarchical clustering encoded as a matrix. See `linkage` for more
        information.
    R : array_like
        The inconsistency matrix.
    i : int
        The column of `R` to use as the statistic.

    Returns
    -------
    MR : ndarray
        Calculates the maximum statistic for the i'th column of the
        inconsistency matrix `R` for each non-singleton cluster
        node. ``MR[j]`` is the maximum over ``R[Q(j)-n, i]`` where
        ``Q(j)`` the set of all node ids corresponding to nodes below
        and including ``j``.

    RF   RG   RH   RI   Rƒ   R´   s&   The third argument must be an integer.i    i   s/   i must be an integer between 0 and 3 inclusive.sQ   The inconsistency matrix and linkage matrix each have a different number of rows.i   (   R2   RM   R   RP   R   Rg   RX   R‹   R>   RR   RŒ   R;   R   Rt  (   Rƒ   R´   R™   R]   t   MR(    (    s6   /tmp/pip-build-7oUkmx/scipy/scipy/cluster/hierarchy.pyR   á
  s    c      	   C` sf  t  j |  d d ƒ}  t  j | d d ƒ} t | ƒ t  j k sN | j d k r] t d ƒ ‚ n  t |  d t d d ƒt | ƒ |  j	 d d	 k rŸ t
 d
 ƒ ‚ n  t  j | ƒ } t | ƒ } t  j | f d d ƒ} t  j | f d d ƒ} |  j	 d d	 } t |  | g ƒ \ }  } t j |  | | | t | ƒ t | ƒ ƒ } | d k r\t
 d | ƒ ‚ n  | | f S(   só  
    Returns the root nodes in a hierarchical clustering.

    Returns the root nodes in a hierarchical clustering corresponding
    to a cut defined by a flat cluster assignment vector ``T``. See
    the ``fcluster`` function for more information on the format of ``T``.

    For each flat cluster :math:`j` of the :math:`k` flat clusters
    represented in the n-sized flat cluster assignment vector ``T``,
    this function finds the lowest cluster node :math:`i` in the linkage
    tree Z such that:

      * leaf descendents belong only to flat cluster j
        (i.e. ``T[p]==j`` for all :math:`p` in :math:`S(i)` where
        :math:`S(i)` is the set of leaf ids of leaf nodes descendent
        with cluster node :math:`i`)

      * there does not exist a leaf that is not descendent with
        :math:`i` that also belongs to cluster :math:`j`
        (i.e. ``T[q]!=j`` for all :math:`q` not in :math:`S(i)`).  If
        this condition is violated, ``T`` is not a valid cluster
        assignment vector, and an exception will be thrown.

    Parameters
    ----------
    Z : ndarray
        The hierarchical clustering encoded as a matrix. See
        `linkage` for more information.
    T : ndarray
        The flat cluster assignment vector.

    Returns
    -------
    L : ndarray
        The leader linkage node id's stored as a k-element 1-D array
        where ``k`` is the number of flat clusters found in ``T``.

        ``L[j]=i`` is the linkage cluster node id that is the
        leader of flat cluster with id M[j].  If ``i < n``, ``i``
        corresponds to an original observation, otherwise it
        corresponds to a non-singleton cluster.

        For example: if ``L[3]=2`` and ``M[3]=8``, the flat cluster with
        id 8's leader is linkage node 2.
    M : ndarray
        The leader linkage node id's stored as a k-element 1-D array where
        ``k`` is the number of flat clusters found in ``T``. This allows the
        set of flat cluster ids to be any arbitrary set of ``k`` integers.

    RF   RG   R™   s4   T must be a one-dimensional numpy array of integers.RH   RI   Rƒ   i    i   s!   Mismatch: len(T)!=Z.shape[0] + 1.R.   sX   T is not a valid assignment vector. Error found when examining linkage node %d (< 2n-1).(   R2   RM   Rg   R¼   R.   R‹   R   RP   RŠ   RR   R>   t   uniqueRŒ   R;   R   R   RX   (   Rƒ   R9   t   Clt   kkRÚ   t   MR]   R,   (    (    s6   /tmp/pip-build-7oUkmx/scipy/scipy/cluster/hierarchy.pyR     s$    3$*(X   R   t
   __future__R    R   R   R*   R   R   R   t   numpyR2   R»   R   t   scipy.spatial.distancet   spatialR%   t   scipy._lib.sixR   R   RJ   RQ   t   __all__t   UserWarningR&   R-   R8   R;   RA   R   R   R	   R   R
   R   R   R   R   t   _cnode_bareRg   t   _cnode_typeR‡   R0   R   RÀ   R$   R¥   RL   R   R   R   R#   R   R   R   RÅ   RÆ   RË   R!   R   R   R   R   RJ  Rß   Rã   Rÿ   t   keysRÞ   t   sortRâ   RÝ   Rá   Rä   R(  R-  R"   RP   R   RN  RQ  RS  RR  RK  R   R   R    R   R   (    (    (    s6   /tmp/pip-build-7oUkmx/scipy/scipy/cluster/hierarchy.pyt   <module>…   sÆ   '										,	-	*ÖÉ	Qa		>3	4	$	AQ			
		 nG	#,

			ƒ	G					ÿ Z						Ý	4		"	-