3
¾ hØ–  ã               @   sp   d dl Zd dlmZmZ d dlZdddddgZdd	d„Zdd
d„Z	G dd„ de
ƒZG dd„ de
ƒZddd„ZdS )é    N)ÚheappushÚheappopÚminkowski_distance_pÚminkowski_distanceÚdistance_matrixÚ	RectangleÚKDTreeé   c             C   s¢   t j| ƒ} t j|ƒ}t jt j| j|jƒdƒ}| j|ƒ} |j|ƒ}|t jkrbt jt j||  ƒddS |dkr‚t jt j||  ƒddS t jt j||  ƒ| ddS dS )a[  
    Compute the pth power of the L**p distance between two arrays.

    For efficiency, this function computes the L**p distance but does
    not extract the pth root. If `p` is 1 or infinity, this is equal to
    the actual L**p distance.

    Parameters
    ----------
    x : (M, K) array_like
        Input array.
    y : (N, K) array_like
        Input array.
    p : float, 1 <= p <= infinity
        Which Minkowski p-norm to use.

    Examples
    --------
    >>> from scipy.spatial import minkowski_distance_p
    >>> minkowski_distance_p([[0,0],[0,0]], [[1,1],[0,1]])
    array([2, 1])

    Zfloat64é   )ÚaxisNéÿÿÿÿr   r   )	ÚnpÚasarrayZpromote_typesÚdtypeÚastypeÚinfÚamaxÚabsÚsum)ÚxÚyÚpZcommon_datatype© r   ú5/tmp/pip-build-riy7u7_k/scipy/scipy/spatial/kdtree.pyr      s    




c             C   sJ   t j| ƒ} t j|ƒ}|t jks&|dkr2t| ||ƒS t| ||ƒd|  S dS )a­  
    Compute the L**p distance between two arrays.

    Parameters
    ----------
    x : (M, K) array_like
        Input array.
    y : (N, K) array_like
        Input array.
    p : float, 1 <= p <= infinity
        Which Minkowski p-norm to use.

    Examples
    --------
    >>> from scipy.spatial import minkowski_distance
    >>> minkowski_distance([[0,0],[0,0]], [[1,1],[0,1]])
    array([ 1.41421356,  1.        ])

    r
   g      ð?N)r   r   r   r   )r   r   r   r   r   r   r   7   s
    

c               @   sX   e Zd ZdZdd„ Zdd„ Zdd„ Zdd	„ Zddd„Zddd„Z	ddd„Z
ddd„ZdS )r   zLHyperrectangle class.

    Represents a Cartesian product of intervals.
    c             C   s8   t j||ƒjtƒ| _t j||ƒjtƒ| _| jj\| _dS )zConstruct a hyperrectangle.N)	r   Úmaximumr   ÚfloatÚmaxesZminimumÚminsÚshapeÚm)Úselfr   r   r   r   r   Ú__init__X   s    zRectangle.__init__c             C   s   dt t| j| jƒƒ S )Nz<Rectangle %s>)ÚlistÚzipr   r   )r    r   r   r   Ú__repr__^   s    zRectangle.__repr__c             C   s   t j| j| j ƒS )zTotal volume.)r   Úprodr   r   )r    r   r   r   Úvolumea   s    zRectangle.volumec             C   sH   t j| jƒ}|||< t| j|ƒ}t j| jƒ}|||< t|| jƒ}||fS )a²  
        Produce two hyperrectangles by splitting.

        In general, if you need to compute maximum and minimum
        distances to the children, it can be done more efficiently
        by updating the maximum and minimum distances to the parent.

        Parameters
        ----------
        d : int
            Axis to split hyperrectangle along.
        split : float
            Position along axis `d` to split at.

        )r   Úcopyr   r   r   )r    ÚdÚsplitZmidÚlessÚgreaterr   r   r   r)   e   s    zRectangle.splitç       @c             C   s(   t dtjdtj| j| || j ƒƒ|ƒS )zÞ
        Return the minimum distance between input and points in the hyperrectangle.

        Parameters
        ----------
        x : array_like
            Input.
        p : float, optional
            Input.

        r   )r   r   r   r   r   )r    r   r   r   r   r   Úmin_distance_point}   s    zRectangle.min_distance_pointc             C   s    t dtj| j| || j ƒ|ƒS )zä
        Return the maximum distance between input and points in the hyperrectangle.

        Parameters
        ----------
        x : array_like
            Input array.
        p : float, optional
            Input.

        r   )r   r   r   r   r   )r    r   r   r   r   r   Úmax_distance_point‹   s    zRectangle.max_distance_pointc             C   s,   t dtjdtj| j|j |j| j ƒƒ|ƒS )zØ
        Compute the minimum distance between points in the two hyperrectangles.

        Parameters
        ----------
        other : hyperrectangle
            Input.
        p : float
            Input.

        r   )r   r   r   r   r   )r    Úotherr   r   r   r   Úmin_distance_rectangle™   s    z Rectangle.min_distance_rectanglec             C   s$   t dtj| j|j |j| j ƒ|ƒS )zâ
        Compute the maximum distance between points in the two hyperrectangles.

        Parameters
        ----------
        other : hyperrectangle
            Input.
        p : float, optional
            Input.

        r   )r   r   r   r   r   )r    r/   r   r   r   r   Úmax_distance_rectangle§   s    z Rectangle.max_distance_rectangleN)r,   )r,   )r,   )r,   )Ú__name__Ú
__module__Ú__qualname__Ú__doc__r!   r$   r&   r)   r-   r.   r0   r1   r   r   r   r   r   S   s   


c               @   s¶   e Zd ZdZd"dd„ZG dd„ deƒZG dd„ deƒZG d	d
„ d
eƒZdd„ Z	ddde
jfdd„Zddde
jfdd„Zd#dd„Zd$dd„Zd%dd„Zd&dd„Zd'dd„Zd(dd „Zd!S ))r   a  
    kd-tree for quick nearest-neighbor lookup

    This class provides an index into a set of k-D points which
    can be used to rapidly look up the nearest neighbors of any point.

    Parameters
    ----------
    data : (N,K) array_like
        The data points to be indexed. This array is not copied, and
        so modifying this data will result in bogus results.
    leafsize : int, optional
        The number of points at which the algorithm switches over to
        brute-force.  Has to be positive.

    Raises
    ------
    RuntimeError
        The maximum recursion limit can be exceeded for large data
        sets.  If this happens, either increase the value for the `leafsize`
        parameter or increase the recursion limit by::

            >>> import sys
            >>> sys.setrecursionlimit(10000)

    See Also
    --------
    cKDTree : Implementation of `KDTree` in Cython

    Notes
    -----
    The algorithm used is described in Maneewongvatana and Mount 1999.
    The general idea is that the kd-tree is a binary tree, each of whose
    nodes represents an axis-aligned hyperrectangle. Each node specifies
    an axis and splits the set of points based on whether their coordinate
    along that axis is greater than or less than a particular value.

    During construction, the axis and splitting point are chosen by the
    "sliding midpoint" rule, which ensures that the cells do not all
    become long and thin.

    The tree can be queried for the r closest neighbors of any given point
    (optionally returning only those within some maximum distance of the
    point). It can also be queried, with a substantial gain in efficiency,
    for the r approximate closest neighbors.

    For large dimensions (20 is already large) do not expect this to run
    significantly faster than brute force. High-dimensional nearest-neighbor
    queries are a substantial open problem in computer science.

    The tree also supports all-neighbors queries, both with arrays of points
    and with other kd-trees. These do use a reasonably efficient algorithm,
    but the kd-tree is not necessarily the best data structure for this
    sort of calculation.

    é
   c             C   s–   t j|ƒ| _| jjjdkr"tdƒ‚t j| jƒ\| _| _t	|ƒ| _
| j
dk rRtdƒ‚t j| jdd| _t j| jdd| _| jt j| jƒ| j| jƒ| _d S )NÚcz&KDTree does not work with complex datar
   zleafsize must be at least 1r   )r   )r   r   Údatar   ÚkindÚ	TypeErrorr   Únr   ÚintÚleafsizeÚ
ValueErrorr   r   Úaminr   Ú_KDTree__buildÚarangeÚtree)r    r8   r=   r   r   r   r!   ï   s    

zKDTree.__init__c               @   s4   e Zd Zdd„ Zdd„ Zdd„ Zdd„ Zd	d
„ ZdS )zKDTree.nodec             C   s   t | ƒt |ƒk S )N)Úid)r    r/   r   r   r   Ú__lt__þ   s    zKDTree.node.__lt__c             C   s   t | ƒt |ƒkS )N)rC   )r    r/   r   r   r   Ú__gt__  s    zKDTree.node.__gt__c             C   s   t | ƒt |ƒkS )N)rC   )r    r/   r   r   r   Ú__le__  s    zKDTree.node.__le__c             C   s   t | ƒt |ƒkS )N)rC   )r    r/   r   r   r   Ú__ge__  s    zKDTree.node.__ge__c             C   s   t | ƒt |ƒkS )N)rC   )r    r/   r   r   r   Ú__eq__
  s    zKDTree.node.__eq__N)r2   r3   r4   rD   rE   rF   rG   rH   r   r   r   r   Únodeý   s
   rI   c               @   s   e Zd Zdd„ ZdS )zKDTree.leafnodec             C   s   || _ t|ƒ| _d S )N)ÚidxÚlenÚchildren)r    rJ   r   r   r   r!     s    zKDTree.leafnode.__init__N)r2   r3   r4   r!   r   r   r   r   Úleafnode  s   rM   c               @   s   e Zd Zdd„ ZdS )zKDTree.innernodec             C   s*   || _ || _|| _|| _|j|j | _d S )N)Ú	split_dimr)   r*   r+   rL   )r    rN   r)   r*   r+   r   r   r   r!     s
    zKDTree.innernode.__init__N)r2   r3   r4   r!   r   r   r   r   Ú	innernode  s   rO   c             C   s¸  t |ƒ| jkrtj|ƒS | j| }tj|| ƒ}|| }|| }||krRtj|ƒS |d d …|f }|| d }tj||kƒd }	tj||kƒd }
t |	ƒdkrÌtj|ƒ}tj||kƒd }	tj||kƒd }
t |
ƒdkrtj	|ƒ}tj||k ƒd }	tj||kƒd }
t |	ƒdkrdtj
||d kƒs6td| ƒ‚|d }tjt |ƒd ƒ}	tjt |ƒd gƒ}
tj|ƒ}|||< tj|ƒ}|||< tj||| j||	 ||ƒ| j||
 ||ƒƒS d S )Nr	   r   zTroublesome data array: %sr
   )rK   r=   r   rM   r8   r   ZargmaxZnonzeror?   r   Úallr>   rA   Úarrayr'   rO   r@   )r    rJ   r   r   r8   r(   ÚmaxvalÚminvalr)   Zless_idxZgreater_idxZ	lessmaxesZgreaterminsr   r   r   Z__build  sB    






zKDTree.__buildr
   r   r	   c                sÄ  t jdt j|| j | j| ƒƒ}ˆ t jkr>|ˆ C }t j|ƒ}n
t j|ƒ}|t|ƒ| jfg}g }	|dkrld}
n(ˆ t jkr„dd|  }
ndd| ˆ   }
ˆ t jkr°|t jkr°|ˆ  }xØ|rŠt	|ƒ\}}}t
|tjƒrp| j|j }t||t jd d …f ˆ ƒ}xptt|ƒƒD ]`}|| |k r
t|	ƒ|kr2t	|	ƒ t|	||  |j| fƒ t|	ƒ|kr
|	d d  }q
W q´|||
 kr€P ||j |jk r¢|j|j }}n|j|j }}t||||fƒ t|ƒ}ˆ t jkrðt|t|j||j  ƒƒ}nxˆ dkr0t j|j||j  ƒ||j< |||j  ||j  }n8t j|j||j  ƒˆ  ||j< |||j  ||j  }|||
 kr´t||t|ƒ|fƒ q´W ˆ t jkrªtdd„ |	D ƒƒS t‡ fdd„|	D ƒƒS d S )Nr   r
   c             S   s   g | ]\}}| |f‘qS r   r   )Ú.0r(   Úir   r   r   ú
<listcomp>”  s    z"KDTree.__query.<locals>.<listcomp>c                s"   g | ]\}}| d ˆ   |f‘qS )g      ð?r   )rT   r(   rU   )r   r   r   rV   –  s    )r   r   r   r   r   r   r   ÚtuplerB   r   Ú
isinstancer   rM   r8   rJ   r   ÚnewaxisÚrangerK   r   rN   r)   r*   r+   r"   Úmaxr   Úsorted)r    r   ÚkÚepsr   Údistance_upper_boundZside_distancesZmin_distanceÚqZ	neighborsZepsfacrI   r8   ÚdsrU   ZnearZfarÚsdr   )r   r   Z__queryF  s^     





 zKDTree.__queryc             C   s   t j|ƒ}|jjdkrtdƒ‚t j|ƒd | jkrJtd| jt j|ƒf ƒ‚|dk rZtdƒ‚t j|ƒdd… }|f kr|dkrœt j|t	d}t j|t	d}n’|dkræt j||f t
d}|jt jƒ t j||f td}|j| jƒ nH|dkr&t j|t
d}|jt jƒ t j|td}|j| jƒ ntdƒ‚xât j|ƒD ]Ô}	| j||	 ||||d	}
|dkr†d
d„ |
D ƒ||	< dd„ |
D ƒ||	< n†|dkrÊxztt|
ƒƒD ]&}|
| \||	|f < ||	|f < qžW nB|dkr:t|
ƒdkrø|
d \||	< ||	< nt j||	< | j||	< q:W ||fS | j|||||d	}
|dkrTdd„ |
D ƒdd„ |
D ƒfS |dkr‚t|
ƒdkrt|
d S t j| jfS nz|dkrôt j|t
d}|jt jƒ t j|td}|j| jƒ x*tt|
ƒƒD ]}|
| \||< ||< qÎW ||fS tdƒ‚dS )aC  
        Query the kd-tree for nearest neighbors

        Parameters
        ----------
        x : array_like, last dimension self.m
            An array of points to query.
        k : int, optional
            The number of nearest neighbors to return.
        eps : nonnegative float, optional
            Return approximate nearest neighbors; the kth returned value
            is guaranteed to be no further than (1+eps) times the
            distance to the real kth nearest neighbor.
        p : float, 1<=p<=infinity, optional
            Which Minkowski p-norm to use.
            1 is the sum-of-absolute-values "Manhattan" distance
            2 is the usual Euclidean distance
            infinity is the maximum-coordinate-difference distance
        distance_upper_bound : nonnegative float, optional
            Return only neighbors within this distance. This is used to prune
            tree searches, so if you are doing a series of nearest-neighbor
            queries, it may help to supply the distance to the nearest neighbor
            of the most recent point.

        Returns
        -------
        d : float or array of floats
            The distances to the nearest neighbors.
            If x has shape tuple+(self.m,), then d has shape tuple if
            k is one, or tuple+(k,) if k is larger than one. Missing
            neighbors (e.g. when k > n or distance_upper_bound is
            given) are indicated with infinite distances.  If k is None,
            then d is an object array of shape tuple, containing lists
            of distances. In either case the hits are sorted by distance
            (nearest first).
        i : integer or array of integers
            The locations of the neighbors in self.data. i is the same
            shape as d.

        Examples
        --------
        >>> from scipy import spatial
        >>> x, y = np.mgrid[0:5, 2:8]
        >>> tree = spatial.KDTree(list(zip(x.ravel(), y.ravel())))
        >>> tree.data
        array([[0, 2],
               [0, 3],
               [0, 4],
               [0, 5],
               [0, 6],
               [0, 7],
               [1, 2],
               [1, 3],
               [1, 4],
               [1, 5],
               [1, 6],
               [1, 7],
               [2, 2],
               [2, 3],
               [2, 4],
               [2, 5],
               [2, 6],
               [2, 7],
               [3, 2],
               [3, 3],
               [3, 4],
               [3, 5],
               [3, 6],
               [3, 7],
               [4, 2],
               [4, 3],
               [4, 4],
               [4, 5],
               [4, 6],
               [4, 7]])
        >>> pts = np.array([[0, 0], [2.1, 2.9]])
        >>> tree.query(pts)
        (array([ 2.        ,  0.14142136]), array([ 0, 13]))
        >>> tree.query(pts[0])
        (2.0, 0)

        r7   z&KDTree does not work with complex datar
   z7x must consist of vectors of length %d but has shape %sz*Only p-norms with 1<=p<=infinity permittedN)r   zeRequested %s nearest neighbors; acceptable numbers are integers greater than or equal to one, or None)r]   r^   r   r_   c             S   s   g | ]\}}|‘qS r   r   )rT   r(   rU   r   r   r   rV     s    z KDTree.query.<locals>.<listcomp>c             S   s   g | ]\}}|‘qS r   r   )rT   r(   rU   r   r   r   rV     s    r   c             S   s   g | ]\}}|‘qS r   r   )rT   r(   rU   r   r   r   rV     s    c             S   s   g | ]\}}|‘qS r   r   )rT   r(   rU   r   r   r   rV     s    r   r   )r   r   r   r9   r:   r   r   r>   ÚemptyÚobjectr   Úfillr   r<   r;   ÚndindexÚ_KDTree__queryrZ   rK   )r    r   r]   r^   r   r_   ÚretshapeÚddÚiir7   ÚhitsÚjr   r   r   Úquery˜  sj    S




(




zKDTree.queryç       @c                s>   t ˆjˆjƒ}‡ ‡‡‡‡‡‡fdd„‰‡fdd„‰ˆˆj|ƒS )Nc                sž   |j ˆˆƒˆdˆ   krg S |jˆˆƒˆdˆ   k r<ˆ| ƒS t| tjƒrnˆj| j }| jt|ˆˆƒˆk jƒ S |j	| j
| j	ƒ\}}ˆ| j|ƒˆ| j|ƒ S d S )Ng      ð?)r-   r.   rX   r   rM   r8   rJ   r   Útolistr)   rN   r*   r+   )rI   Zrectr(   r*   r+   )r^   r   Úrr    Útraverse_checkingÚtraverse_no_checkingr   r   r   rq   )  s    
z4KDTree.__query_ball_point.<locals>.traverse_checkingc                s.   t | tjƒr| jjƒ S ˆ | jƒˆ | jƒ S d S )N)rX   r   rM   rJ   ro   r*   r+   )rI   )rr   r   r   rr   6  s    
z7KDTree.__query_ball_point.<locals>.traverse_no_checking)r   r   r   rB   )r    r   rp   r   r^   ÚRr   )r^   r   rp   r    rq   rr   r   r   Z__query_ball_point&  s    zKDTree.__query_ball_pointc             C   s¶   t j|ƒ}|jjdkrtdƒ‚|jd | jkrFtd|jd	 | jf ƒ‚t|jƒdkrd| j	||||ƒS |jdd
… }t j
|td}x,t j|ƒD ]}| j	|| |||d||< qŒW |S dS )a]  Find all points within distance r of point(s) x.

        Parameters
        ----------
        x : array_like, shape tuple + (self.m,)
            The point or points to search for neighbors of.
        r : positive float
            The radius of points to return.
        p : float, optional
            Which Minkowski p-norm to use.  Should be in the range [1, inf].
        eps : nonnegative float, optional
            Approximate search. Branches of the tree are not explored if their
            nearest points are further than ``r / (1 + eps)``, and branches are
            added in bulk if their furthest points are nearer than
            ``r * (1 + eps)``.

        Returns
        -------
        results : list or array of lists
            If `x` is a single point, returns a list of the indices of the
            neighbors of `x`. If `x` is an array of points, returns an object
            array of shape tuple containing lists of neighbors.

        Notes
        -----
        If you have many points whose neighbors you want to find, you may save
        substantial amounts of time by putting them in a KDTree and using
        query_ball_tree.

        Examples
        --------
        >>> from scipy import spatial
        >>> x, y = np.mgrid[0:5, 0:5]
        >>> points = np.c_[x.ravel(), y.ravel()]
        >>> tree = spatial.KDTree(points)
        >>> tree.query_ball_point([2, 0], 1)
        [5, 10, 11, 15]

        Query multiple points and plot the results:

        >>> import matplotlib.pyplot as plt
        >>> points = np.asarray(points)
        >>> plt.plot(points[:,0], points[:,1], '.')
        >>> for results in tree.query_ball_point(([2, 0], [3, 3]), 1):
        ...     nearby_points = points[results]
        ...     plt.plot(nearby_points[:,0], nearby_points[:,1], 'o')
        >>> plt.margins(0.1, 0.1)
        >>> plt.show()

        r7   z&KDTree does not work with complex datar
   z?Searching for a %d-dimensional point in a %d-dimensional KDTreeN)r   )r   r^   r   r   r   )r   r   r   r9   r:   r   r   r>   rK   Ú_KDTree__query_ball_pointrc   rd   rf   )r    r   rp   r   r^   rh   Úresultr7   r   r   r   Úquery_ball_point?  s    3
zKDTree.query_ball_pointc                sf   dd„ t ˆjƒD ƒ‰‡ ‡‡‡‡‡‡‡fdd„‰‡‡fdd„‰ˆˆjtˆjˆjƒˆjtˆjˆjƒƒ ˆS )a  Find all pairs of points whose distance is at most r

        Parameters
        ----------
        other : KDTree instance
            The tree containing points to search against.
        r : float
            The maximum distance, has to be positive.
        p : float, optional
            Which Minkowski norm to use.  `p` has to meet the condition
            ``1 <= p <= infinity``.
        eps : float, optional
            Approximate search.  Branches of the tree are not explored
            if their nearest points are further than ``r/(1+eps)``, and
            branches are added in bulk if their furthest points are nearer
            than ``r * (1+eps)``.  `eps` has to be non-negative.

        Returns
        -------
        results : list of lists
            For each element ``self.data[i]`` of this tree, ``results[i]`` is a
            list of the indices of its neighbors in ``other.data``.

        c             S   s   g | ]}g ‘qS r   r   )rT   rU   r   r   r   rV   š  s    z*KDTree.query_ball_tree.<locals>.<listcomp>c          	      s’  |j |ˆƒˆdˆ   krd S |j|ˆƒˆdˆ   k rBˆ| |ƒ nLt| tjƒrÚt|tjƒr¤ˆj|j }xp| jD ]0}ˆ|  |jt|ˆj| ˆƒˆk jƒ 7  < qnW n4|j	|j
|j	ƒ\}}ˆ| ||j|ƒ ˆ| ||j|ƒ n´t|tjƒr|j	| j
| j	ƒ\}}ˆ| j|||ƒ ˆ| j|||ƒ np|j	| j
| j	ƒ\}}	|j	|j
|j	ƒ\}
}ˆ| j||j|
ƒ ˆ| j||j|ƒ ˆ| j|	|j|
ƒ ˆ| j|	|j|ƒ d S )Ng      ð?)r0   r1   rX   r   rM   r8   rJ   r   ro   r)   rN   r*   r+   )Únode1Úrect1Únode2Úrect2r(   rU   r*   r+   Úless1Úgreater1Úless2Úgreater2)r^   r/   r   rp   Úresultsr    rq   rr   r   r   rq   œ  s,    2z1KDTree.query_ball_tree.<locals>.traverse_checkingc                sv   t | tjƒrZt |tjƒr@x>| jD ]}ˆ |  |jjƒ 7  < q W qrˆ| |jƒ ˆ| |jƒ nˆ| j|ƒ ˆ| j|ƒ d S )N)rX   r   rM   rJ   ro   r*   r+   )rw   ry   rU   )r   rr   r   r   rr   ¶  s    z4KDTree.query_ball_tree.<locals>.traverse_no_checking)rZ   r;   rB   r   r   r   )r    r/   rp   r   r^   r   )r^   r/   r   rp   r   r    rq   rr   r   Úquery_ball_tree  s    zKDTree.query_ball_treec                sV   t ƒ ‰‡ ‡‡‡‡‡‡fdd„‰‡‡fdd„‰ˆˆjtˆjˆjƒˆjtˆjˆjƒƒ ˆS )a  
        Find all pairs of points within a distance.

        Parameters
        ----------
        r : positive float
            The maximum distance.
        p : float, optional
            Which Minkowski norm to use.  `p` has to meet the condition
            ``1 <= p <= infinity``.
        eps : float, optional
            Approximate search.  Branches of the tree are not explored
            if their nearest points are further than ``r/(1+eps)``, and
            branches are added in bulk if their furthest points are nearer
            than ``r * (1+eps)``.  `eps` has to be non-negative.

        Returns
        -------
        results : set
            Set of pairs ``(i,j)``, with ``i < j``, for which the corresponding
            positions are close.

        c                s@  |j |ˆƒˆdˆ   krd S |j|ˆƒˆdˆ   k rBˆ| |ƒ nút| tjƒrvt|tjƒr@t| ƒt|ƒkrÈˆj|j }xÂ| jD ]@}x:|jt|ˆj| ˆƒˆk D ]}||k r¤ˆj	||fƒ q¤W q‚W nvˆj|j }xž| jD ]^}xX|jt|ˆj| ˆƒˆk D ]8}||k rˆj	||fƒ n||k  rþˆj	||fƒ  qþW qÜW n4|j
|j|j
ƒ\}}ˆ| ||j|ƒ ˆ| ||j|ƒ nÆt|tjƒrº|j
| j| j
ƒ\}}ˆ| j|||ƒ ˆ| j|||ƒ n‚|j
| j| j
ƒ\}	}
|j
|j|j
ƒ\}}ˆ| j|	|j|ƒ ˆ| j|	|j|ƒ t| ƒt|ƒkr*ˆ| j|
|j|ƒ ˆ| j|
|j|ƒ d S )Ng      ð?)r0   r1   rX   r   rM   rC   r8   rJ   r   Úaddr)   rN   r*   r+   )rw   rx   ry   rz   r(   rU   rl   r*   r+   r{   r|   r}   r~   )r^   r   rp   r   r    rq   rr   r   r   rq   à  sB    ""

z-KDTree.query_pairs.<locals>.traverse_checkingc                s$  t | tjƒrÊt |tjƒr°t| ƒt|ƒkr`x„| jD ]*}x$|jD ]}||k r<ˆ j||fƒ q<W q0W qÈxf| jD ]B}x<|jD ]2}||k rˆ j||fƒ qt||k rtˆ j||fƒ qtW qhW nˆ| |jƒ ˆ| |jƒ nVt| ƒt|ƒkrˆ| j|jƒ ˆ| j|jƒ ˆ| j|jƒ nˆ| j|ƒ ˆ| j|ƒ d S )N)rX   r   rM   rC   rJ   r   r*   r+   )rw   ry   rU   rl   )r   rr   r   r   rr     s*    z0KDTree.query_pairs.<locals>.traverse_no_checking)ÚsetrB   r   r   r   )r    rp   r   r^   r   )r^   r   rp   r   r    rq   rr   r   Úquery_pairsÆ  s    - zKDTree.query_pairsc                sØ   ‡ ‡‡‡‡‡fdd„‰t ˆjˆjƒ}t ˆ jˆ jƒ}tjˆƒf kr|tjˆgƒ‰tjdtd‰ˆˆj|ˆ j|tj	dƒƒ ˆd S t
tjˆƒƒdkrÌtjˆƒ‰ˆj\}tj|td‰ˆˆj|ˆ j|tj	|ƒƒ ˆS tdƒ‚dS )aè  
        Count how many nearby pairs can be formed.

        Count the number of pairs (x1,x2) can be formed, with x1 drawn
        from self and x2 drawn from ``other``, and where
        ``distance(x1, x2, p) <= r``.
        This is the "two-point correlation" described in Gray and Moore 2000,
        "N-body problems in statistical learning", and the code here is based
        on their algorithm.

        Parameters
        ----------
        other : KDTree instance
            The other tree to draw points from.
        r : float or one-dimensional array of floats
            The radius to produce a count for. Multiple radii are searched with
            a single tree traversal.
        p : float, 1<=p<=infinity, optional
            Which Minkowski p-norm to use

        Returns
        -------
        result : int or 1-D array of ints
            The number of pairs. Note that this is internally stored in a numpy
            int, and so may overflow if very large (2e9).

        c                sö  |j |ˆƒ}|j|ˆƒ}ˆ| |k}ˆ||   | j|j 7  < ||ˆ| kˆ| |k@  }t|ƒdkrld S t| tjƒr2t|tjƒrøtˆj| j	 d d …t
jd d …f ˆ j|j	 t
jd d …d d …f ˆƒjƒ }|jƒ  ˆ|  t
j|ˆ| dd7  < n8|j|j|jƒ\}	}
ˆ| ||j|	|ƒ ˆ| ||j|
|ƒ nÀt|tjƒrz|j| j| jƒ\}	}
ˆ| j|	|||ƒ ˆ| j|
|||ƒ nx|j| j| jƒ\}}|j|j|jƒ\}}ˆ| j||j||ƒ ˆ| j||j||ƒ ˆ| j||j||ƒ ˆ| j||j||ƒ d S )Nr   Úright)Zside)r0   r1   rL   rK   rX   r   rM   r   r8   rJ   r   rY   ZravelÚsortZsearchsortedr)   rN   r*   r+   )rw   rx   ry   rz   rJ   Zmin_rZmax_rZ	c_greaterra   r*   r+   r{   r|   r}   r~   )r/   r   rp   ru   r    Útraverser   r   r†   M  s6     
"z(KDTree.count_neighbors.<locals>.traverser
   )r   r   zDr must be either a single value or a one-dimensional array of valuesN)r   r   r   r   r   rQ   Úzerosr<   rB   rA   rK   r   r>   )r    r/   rp   r   ZR1ZR2r;   r   )r/   r   rp   ru   r    r†   r   Úcount_neighbors1  s    !
zKDTree.count_neighborsc                sT   t jjˆjˆjfƒ‰‡ ‡‡‡‡‡fdd„‰ˆˆjtˆjˆjƒˆjtˆjˆjƒƒ ˆS )a¾  
        Compute a sparse distance matrix

        Computes a distance matrix between two KDTrees, leaving as zero
        any distance greater than max_distance.

        Parameters
        ----------
        other : KDTree

        max_distance : positive float

        p : float, optional

        Returns
        -------
        result : dok_matrix
            Sparse matrix representing the results in "dictionary of keys" format.

        c                sf  |j |ˆƒˆ krd S t| tjƒr°t|tjƒrzx€| jD ]@}x:|jD ]0}tˆj| ˆj| ˆƒ}|ˆ kr@|ˆ||f< q@W q4W n4|j|j|jƒ\}}ˆ| ||j	|ƒ ˆ| ||j
|ƒ n²t|tjƒrò|j| j| jƒ\}}ˆ| j	|||ƒ ˆ| j
|||ƒ np|j| j| jƒ\}	}
|j|j|jƒ\}}ˆ| j	|	|j	|ƒ ˆ| j	|	|j
|ƒ ˆ| j
|
|j	|ƒ ˆ| j
|
|j
|ƒ d S )N)r0   rX   r   rM   rJ   r   r8   r)   rN   r*   r+   )rw   rx   ry   rz   rU   rl   r(   r*   r+   r{   r|   r}   r~   )Úmax_distancer/   r   ru   r    r†   r   r   r†   •  s,    z/KDTree.sparse_distance_matrix.<locals>.traverse)ÚscipyÚsparseZ
dok_matrixr;   rB   r   r   r   )r    r/   r‰   r   r   )r‰   r/   r   ru   r    r†   r   Úsparse_distance_matrix~  s
    zKDTree.sparse_distance_matrixN)r6   )rn   r   )rn   r   )rn   r   )rn   r   )rn   )rn   )r2   r3   r4   r5   r!   rd   rI   rM   rO   r@   r   r   rg   rm   rt   rv   r€   rƒ   rˆ   rŒ   r   r   r   r   r   ¶   s   8
,R 

B
E
k
Mé@B c             C   s  t j| ƒ} | j\}}t j|ƒ}|j\}}||kr@td||f ƒ‚|| | |kr„t| dd…t jdd…f |t jdd…dd…f |ƒS t j||ftd}||k rÎx\t|ƒD ] }	t| |	 ||ƒ||	dd…f< q¨W n.x,t|ƒD ] }
t| ||
 |ƒ|dd…|
f< qØW |S dS )aE  
    Compute the distance matrix.

    Returns the matrix of all pair-wise distances.

    Parameters
    ----------
    x : (M, K) array_like
        Matrix of M vectors in K dimensions.
    y : (N, K) array_like
        Matrix of N vectors in K dimensions.
    p : float, 1 <= p <= infinity
        Which Minkowski p-norm to use.
    threshold : positive int
        If ``M * N * K`` > `threshold`, algorithm uses a Python loop instead
        of large temporary arrays.

    Returns
    -------
    result : (M, N) ndarray
        Matrix containing the distance from every vector in `x` to every vector
        in `y`.

    Examples
    --------
    >>> from scipy.spatial import distance_matrix
    >>> distance_matrix([[0,0],[0,1]], [[1,0],[1,1]])
    array([[ 1.        ,  1.41421356],
           [ 1.41421356,  1.        ]])

    zGx contains %d-dimensional vectors but y contains %d-dimensional vectorsN)r   )	r   r   r   r>   r   rY   rc   r   rZ   )r   r   r   Ú	thresholdr   r]   r;   Úkkru   rU   rl   r   r   r   r   ´  s    !



4" )r	   )r	   )r	   r   )Znumpyr   Úheapqr   r   Zscipy.sparserŠ   Ú__all__r   r   rd   r   r   r   r   r   r   r   Ú<module>   s    
+
c      