a
    J5dO                     @   s   d dl mZmZmZ d dlZddlmZ ddlm	Z	 ddl
mZmZ ddlmZ ddlmZmZ d	gZG d
d de	ZG dd	 d	ZdS )    )AnyIterableUnionN   )lib)	ParamEnum)requires_geosUnsupportedGEOSVersionError)BaseGeometry)is_empty
is_missingSTRtreec                   @   s4   e Zd ZdZdZdZdZdZdZdZ	dZ
d	Zd
ZdS )BinaryPredicatez/The enumeration of GEOS binary predicates typesr                        	   N)__name__
__module____qualname____doc__Z
intersectsZwithincontainsoverlapsZcrossesZtouchesZcoversZ
covered_byZcontains_properly r   r   K/var/www/html/django/DPS/env/lib/python3.9/site-packages/shapely/strtree.pyr      s   r   c                   @   s|   e Zd ZdZdee edddZdd Zdd	 Z	e
d
d ZdddZedeedf dddZeddddZdS )r   a  
    A query-only R-tree spatial index created using the
    Sort-Tile-Recursive (STR) [1]_ algorithm.

    The tree indexes the bounding boxes of each geometry.  The tree is
    constructed directly at initialization and nodes cannot be added or
    removed after it has been created.

    All operations return indices of the input geometries.  These indices
    can be used to index into anything associated with the input geometries,
    including the input geometries themselves, or custom items stored in
    another object of the same length as the geometries.

    Bounding boxes limited to two dimensions and are axis-aligned (equivalent to
    the ``bounds`` property of a geometry); any Z values present in geometries
    are ignored for purposes of indexing within the tree.

    Any mixture of geometry types may be stored in the tree.

    Note: the tree is more efficient for querying when there are fewer
    geometries that have overlapping bounding boxes and where there is greater
    similarity between the outer boundary of a geometry and its bounding box.
    For example, a MultiPolygon composed of widely-spaced individual Polygons
    will have a large overall bounding box compared to the boundaries of its
    individual Polygons, and the bounding box may also potentially overlap many
    other geometries within the tree.  This means that the resulting tree may be
    less efficient to query than a tree constructed from individual Polygons.

    Parameters
    ----------
    geoms : sequence
        A sequence of geometry objects.
    node_capacity : int, default 10
        The maximum number of child nodes per parent node in the tree.

    References
    ----------
    .. [1] Leutenegger, Scott T.; Edgington, Jeffrey M.; Lopez, Mario A.
       (February 1997). "STR: A Simple and Efficient Algorithm for
       R-Tree Packing".
       https://ia600900.us.archive.org/27/items/nasa_techdoc_19970016975/19970016975.pdf
    
   )geomsnode_capacityc                 C   s(   t j|t jdd| _t| j|| _d S )NT)dtypecopy)nparrayZobject__geometriesr   r   
geometries_tree)selfr    r!   r   r   r   __init__H   s    zSTRtree.__init__c                 C   s   | j jS N)r(   countr)   r   r   r   __len__T   s    zSTRtree.__len__c                 C   s   t | jffS r+   )r   r'   r-   r   r   r   
__reduce__W   s    zSTRtree.__reduce__c                 C   s   | j S )aH  
        Geometries stored in the tree in the order used to construct the tree.

        The order of this array corresponds to the tree indices returned by
        other STRtree methods.

        Do not attempt to modify items in the returned array.

        Returns
        -------
        ndarray of Geometry objects
        )r&   r-   r   r   r   r'   Z   s    zSTRtree.geometriesNc                 C   s  t |}d}|jdkr(t |d}d}|du rN| j|d}|rJ|d S |S |dkrtjdk rhtd|du rxt	d	t j|d
d}|jdkrt	dzt 
||j}W n t	y   t	dY n0 | j||}|r|d S |S t|}| j||}|r
|d S |S )a  
        Return the integer indices of all combinations of each input geometry
        and tree geometries where the bounding box of each input geometry
        intersects the bounding box of a tree geometry.

        If the input geometry is a scalar, this returns an array of shape (n, ) with
        the indices of the matching tree geometries.  If the input geometry is an
        array_like, this returns an array with shape (2,n) where the subarrays
        correspond to the indices of the input geometries and indices of the
        tree geometries associated with each.  To generate an array of pairs of
        input geometry index and tree geometry index, simply transpose the
        result.

        If a predicate is provided, the tree geometries are first queried based
        on the bounding box of the input geometry and then are further filtered
        to those that meet the predicate when comparing the input geometry to
        the tree geometry:
        predicate(geometry, tree_geometry)

        The 'dwithin' predicate requires GEOS >= 3.10.

        Bounding boxes are limited to two dimensions and are axis-aligned
        (equivalent to the ``bounds`` property of a geometry); any Z values
        present in input geometries are ignored when querying the tree.

        Any input geometry that is None or empty will never match geometries in
        the tree.

        Parameters
        ----------
        geometry : Geometry or array_like
            Input geometries to query the tree and filter results using the
            optional predicate.
        predicate : {None, 'intersects', 'within', 'contains', 'overlaps', 'crosses','touches', 'covers', 'covered_by', 'contains_properly', 'dwithin'}, optional
            The predicate to use for testing geometries from the tree
            that are within the input geometry's bounding box.
        distance : number or array_like, optional
            Distances around each input geometry within which to query the tree
            for the 'dwithin' predicate.  If array_like, shape must be
            broadcastable to shape of geometry.  Required if predicate='dwithin'.

        Returns
        -------
        ndarray with shape (n,) if geometry is a scalar
            Contains tree geometry indices.

        OR

        ndarray with shape (2, n) if geometry is an array_like
            The first subarray contains input geometry indices.
            The second subarray contains tree geometry indices.

        Examples
        --------
        >>> from shapely import box, Point
        >>> import numpy as np
        >>> points = [Point(0, 0), Point(1, 1), Point(2,2), Point(3, 3)]
        >>> tree = STRtree(points)

        Query the tree using a scalar geometry:

        >>> indices = tree.query(box(0, 0, 1, 1))
        >>> indices.tolist()
        [0, 1]

        Query using an array of geometries:

        >>> boxes = np.array([box(0, 0, 1, 1), box(2, 2, 3, 3)])
        >>> arr_indices = tree.query(boxes)
        >>> arr_indices.tolist()
        [[0, 0, 1, 1], [0, 1, 2, 3]]

        Or transpose to get all pairs of input and tree indices:

        >>> arr_indices.T.tolist()
        [[0, 0], [0, 1], [1, 2], [1, 3]]

        Retrieve the tree geometries by results of query:

        >>> tree.geometries.take(indices).tolist()
        [<POINT (0 0)>, <POINT (1 1)>]

        Retrieve all pairs of input and tree geometries:

        >>> np.array([boxes.take(arr_indices[0]),tree.geometries.take(arr_indices[1])]).T.tolist()
        [[<POLYGON ((1 0, 1 1, 0 1, 0 0, 1 0))>, <POINT (0 0)>],
         [<POLYGON ((1 0, 1 1, 0 1, 0 0, 1 0))>, <POINT (1 1)>],
         [<POLYGON ((3 2, 3 3, 2 3, 2 2, 3 2))>, <POINT (2 2)>],
         [<POLYGON ((3 2, 3 3, 2 3, 2 2, 3 2))>, <POINT (3 3)>]]

        Query using a predicate:

        >>> tree = STRtree([box(0, 0, 0.5, 0.5), box(0.5, 0.5, 1, 1), box(1, 1, 2, 2)])
        >>> tree.query(box(0, 0, 1, 1), predicate="contains").tolist()
        [0, 1]
        >>> tree.query(Point(0.75, 0.75), predicate="dwithin", distance=0.5).tolist()
        [0, 1, 2]

        >>> tree.query(boxes, predicate="contains").tolist()
        [[0, 0], [0, 1]]
        >>> tree.query(boxes, predicate="dwithin", distance=0.5).tolist()
        [[0, 0, 0, 1], [0, 1, 2, 2]]

        Retrieve custom items associated with tree geometries (records can
        be in whatever data structure so long as geometries and custom data
        can be extracted into arrays of the same length and order):

        >>> records = [
        ...     {"geometry": Point(0, 0), "value": "A"},
        ...     {"geometry": Point(2, 2), "value": "B"}
        ... ]
        >>> tree = STRtree([record["geometry"] for record in records])
        >>> items = np.array([record["value"] for record in records])
        >>> items.take(tree.query(box(0, 0, 1, 1))).tolist()
        ['A']


        Notes
        -----
        In the context of a spatial join, input geometries are the "left"
        geometries that determine the order of the results, and tree geometries
        are "right" geometries that are joined against the left geometries. This
        effectively performs an inner join, where only those combinations of
        geometries that can be joined based on overlapping bounding boxes or
        optional predicate are returned.
        Fr   TNr   dwithin)r   r   r   z'dwithin predicate requires GEOS >= 3.10z9distance parameter must be provided for dwithin predicateZfloat64r"   z(Distance array should be one dimensionalz.Could not broadcast distance to match geometry)r$   asarrayndimexpand_dimsr(   queryr   Zgeos_versionr	   
ValueErrorZbroadcast_toshaper0   r   	get_value)r)   geometry	predicateZdistance	is_scalarindicesr   r   r   r5   j   s<     




zSTRtree.queryz3.6.0)returnc                 C   sn   | j jdkrdS tj|td}t| s6t| r>td| j 	t
|d }|jdkrf|d S |S dS )a  
        Return the index of the nearest geometry in the tree for each input
        geometry based on distance within two-dimensional Cartesian space.

        This distance will be 0 when input geometries intersect tree geometries.

        If there are multiple equidistant or intersected geometries in the tree,
        only a single result is returned for each input geometry, based on the
        order that tree geometries are visited; this order may be
        nondeterministic.

        If any input geometry is None or empty, an error is raised.  Any Z
        values present in input geometries are ignored when finding nearest
        tree geometries.

        Parameters
        ----------
        geometry : Geometry or array_like
            Input geometries to query the tree.

        Returns
        -------
        scalar or ndarray
            Indices of geometries in tree. Return value will have the same shape
            as the input.

            None is returned if this index is empty. This may change in
            version 2.0.

        See also
        --------
        query_nearest: returns all equidistant geometries, exclusive geometries, and optional distances

        Examples
        --------
        >>> from shapely.geometry import Point
        >>> tree = STRtree([Point(i, i) for i in range(10)])

        Query the tree for nearest using a scalar geometry:

        >>> index = tree.nearest(Point(2.2, 2.2))
        >>> index
        2
        >>> tree.geometries.take(index)
        <POINT (2 2)>

        Query the tree for nearest using an array of geometries:

        >>> indices = tree.nearest([Point(2.2, 2.2), Point(4.4, 4.4)])
        >>> indices.tolist()
        [2, 4]
        >>> tree.geometries.take(indices).tolist()
        [<POINT (2 2)>, <POINT (4 4)>]

        Nearest only return one object if there are multiple equidistant results:

        >>> tree = STRtree ([Point(0, 0), Point(0, 0)])
        >>> tree.nearest(Point(0, 0))
        0
        r   Nr1   zMCannot determine nearest geometry for empty geometry or missing value (None).r   )r(   r,   r$   r2   objectr   anyr   r6   nearestZ
atleast_1dr3   )r)   r9   Zgeometry_arrr<   r   r   r   r@     s    ?
zSTRtree.nearestFTc                 C   s   t j|td}d}|jdkr,t |d}d}|durVt |sFtd|dkrVtd|p\d}t |sptd|d	vrtd
t |std|d	vrtd| j||||}|r|s|d d S |d d |d fS |s|d S |S )a  Return the index of the nearest geometries in the tree for each input
        geometry based on distance within two-dimensional Cartesian space.

        This distance will be 0 when input geometries intersect tree geometries.

        If there are multiple equidistant or intersected geometries in tree and
        `all_matches` is True (the default), all matching tree geometries are
        returned; otherwise only the first matching tree geometry is returned.
        Tree indices are returned in the order they are visited for each input
        geometry and may not be in ascending index order; no meaningful order is
        implied.

        The max_distance used to search for nearest items in the tree may have a
        significant impact on performance by reducing the number of input
        geometries that are evaluated for nearest items in the tree.  Only those
        input geometries with at least one tree geometry within +/- max_distance
        beyond their envelope will be evaluated.  However, using a large
        max_distance may have a negative performance impact because many tree
        geometries will be queried for each input geometry.

        The distance, if returned, will be 0 for any intersected geometries in
        the tree.

        Any geometry that is None or empty in the input geometries is omitted
        from the output.  Any Z values present in input geometries are ignored
        when finding nearest tree geometries.

        Parameters
        ----------
        geometry : Geometry or array_like
            Input geometries to query the tree.
        max_distance : float, optional
            Maximum distance within which to query for nearest items in tree.
            Must be greater than 0.
        return_distance : bool, default False
            If True, will return distances in addition to indices.
        exclusive : bool, default False
            If True, the nearest tree geometries that are equal to the input
            geometry will not be returned.
        all_matches : bool, default True
            If True, all equidistant and intersected geometries will be returned
            for each input geometry.
            If False, only the first nearest geometry will be returned.

        Returns
        -------
        tree indices or tuple of (tree indices, distances) if geometry is a scalar
            indices is an ndarray of shape (n, ) and distances (if present) an
            ndarray of shape (n, )

        OR

        indices or tuple of (indices, distances)
            indices is an ndarray of shape (2,n) and distances (if present) an
            ndarray of shape (n).
            The first subarray of indices contains input geometry indices.
            The second subarray of indices contains tree geometry indices.

        See also
        --------
        nearest: returns singular nearest geometry for each input

        Examples
        --------
        >>> import numpy as np
        >>> from shapely import box, Point
        >>> points = [Point(0, 0), Point(1, 1), Point(2,2), Point(3, 3)]
        >>> tree = STRtree(points)

        Find the nearest tree geometries to a scalar geometry:

        >>> indices = tree.query_nearest(Point(0.25, 0.25))
        >>> indices.tolist()
        [0]

        Retrieve the tree geometries by results of query:

        >>> tree.geometries.take(indices).tolist()
        [<POINT (0 0)>]

        Find the nearest tree geometries to an array of geometries:

        >>> query_points = np.array([Point(2.25, 2.25), Point(1, 1)])
        >>> arr_indices = tree.query_nearest(query_points)
        >>> arr_indices.tolist()
        [[0, 1], [2, 1]]

        Or transpose to get all pairs of input and tree indices:

        >>> arr_indices.T.tolist()
        [[0, 2], [1, 1]]

        Retrieve all pairs of input and tree geometries:

        >>> list(zip(query_points.take(arr_indices[0]), tree.geometries.take(arr_indices[1])))
        [(<POINT (2.25 2.25)>, <POINT (2 2)>), (<POINT (1 1)>, <POINT (1 1)>)]

        All intersecting geometries in the tree are returned by default:

        >>> tree.query_nearest(box(1,1,3,3)).tolist()
        [1, 2, 3]

        Set all_matches to False to to return a single match per input geometry:

        >>> tree.query_nearest(box(1,1,3,3), all_matches=False).tolist()
        [1]

        Return the distance to each nearest tree geometry:

        >>> index, distance = tree.query_nearest(Point(0.5, 0.5), return_distance=True)
        >>> index.tolist()
        [0, 1]
        >>> distance.round(4).tolist()
        [0.7071, 0.7071]

        Return the distance for each input and nearest tree geometry for an array
        of geometries:

        >>> indices, distance = tree.query_nearest([Point(0.5, 0.5), Point(1, 1)], return_distance=True)
        >>> indices.tolist()
        [[0, 0, 1], [0, 1, 1]]
        >>> distance.round(4).tolist()
        [0.7071, 0.7071, 0.0]

        Retrieve custom items associated with tree geometries (records can
        be in whatever data structure so long as geometries and custom data
        can be extracted into arrays of the same length and order):

        >>> records = [
        ...     {"geometry": Point(0, 0), "value": "A"},
        ...     {"geometry": Point(2, 2), "value": "B"}
        ... ]
        >>> tree = STRtree([record["geometry"] for record in records])
        >>> items = np.array([record["value"] for record in records])
        >>> items.take(tree.query_nearest(Point(0.5, 0.5))).tolist()
        ['A']
        r1   Fr   TNz1max_distance parameter only accepts scalar valuesz#max_distance must be greater than 0z.exclusive parameter only accepts scalar values>   FTz#exclusive parameter must be booleanz0all_matches parameter only accepts scalar valuesz%all_matches parameter must be booleanr   )	r$   r2   r>   r3   r4   Zisscalarr6   r(   query_nearest)r)   r9   Zmax_distanceZreturn_distanceZ	exclusiveZall_matchesr;   resultsr   r   r   rA   a  s<     



zSTRtree.query_nearest)r   )NN)NFFT)r   r   r   r   r   r
   intr*   r.   r/   propertyr'   r5   r   r   r   r@   rA   r   r   r   r   r      s(   . 

 'P    )typingr   r   r   numpyr$    r   Z_enumr   Z
decoratorsr   r	   Zgeometry.baser
   Z
predicatesr   r   __all__r   r   r   r   r   r   <module>   s   