a
    1$eN                     @   s   d dl mZ d dlZd dlZd dlZd dlmZ d dlm	Z
 d dlmZmZ dd
dZdd Zdd Zdd ZeeeeeedddZdeeeee eeee eed	ddZdS )    )OptionalN)GeoDataFrame)_compat)
_check_crs_crs_mismatch_warninner
intersectsleftrightc                 K   s   d|v rb| d}d}|dkrN||krNd| d| d| }	tj|	tdd ntj|tdd |}|rtt| }
td	|
 d
t	| |||| t
| ||}t|| ||||}|S )a  Spatial join of two GeoDataFrames.

    See the User Guide page :doc:`../../user_guide/mergingdata` for details.


    Parameters
    ----------
    left_df, right_df : GeoDataFrames
    how : string, default 'inner'
        The type of join:

        * 'left': use keys from left_df; retain only left_df geometry column
        * 'right': use keys from right_df; retain only right_df geometry column
        * 'inner': use intersection of keys from both dfs; retain only
          left_df geometry column
    predicate : string, default 'intersects'
        Binary predicate. Valid values are determined by the spatial index used.
        You can check the valid values in left_df or right_df as
        ``left_df.sindex.valid_query_predicates`` or
        ``right_df.sindex.valid_query_predicates``
        Replaces deprecated ``op`` parameter.
    lsuffix : string, default 'left'
        Suffix to apply to overlapping column names (left GeoDataFrame).
    rsuffix : string, default 'right'
        Suffix to apply to overlapping column names (right GeoDataFrame).

    Examples
    --------
    >>> import geodatasets
    >>> chicago = geopandas.read_file(
    ...     geodatasets.get_path("geoda.chicago_health")
    ... )
    >>> groceries = geopandas.read_file(
    ...     geodatasets.get_path("geoda.groceries")
    ... ).to_crs(chicago.crs)

    >>> chicago.head()  # doctest: +SKIP
        ComAreaID  ...                                           geometry
    0         35  ...  POLYGON ((-87.60914 41.84469, -87.60915 41.844...
    1         36  ...  POLYGON ((-87.59215 41.81693, -87.59231 41.816...
    2         37  ...  POLYGON ((-87.62880 41.80189, -87.62879 41.801...
    3         38  ...  POLYGON ((-87.60671 41.81681, -87.60670 41.816...
    4         39  ...  POLYGON ((-87.59215 41.81693, -87.59215 41.816...
    [5 rows x 87 columns]

    >>> groceries.head()  # doctest: +SKIP
        OBJECTID     Ycoord  ...  Category                         geometry
    0        16  41.973266  ...       NaN  MULTIPOINT (-87.65661 41.97321)
    1        18  41.696367  ...       NaN  MULTIPOINT (-87.68136 41.69713)
    2        22  41.868634  ...       NaN  MULTIPOINT (-87.63918 41.86847)
    3        23  41.877590  ...       new  MULTIPOINT (-87.65495 41.87783)
    4        27  41.737696  ...       NaN  MULTIPOINT (-87.62715 41.73623)
    [5 rows x 8 columns]

    >>> groceries_w_communities = geopandas.sjoin(groceries, chicago)
    >>> groceries_w_communities.head()  # doctest: +SKIP
            OBJECTID     Ycoord     Xcoord  ... GonorrF GonorrM Tuberc
    0          16  41.973266 -87.657073  ...   170.8   468.7   13.6
    87        365  41.961707 -87.654058  ...   170.8   468.7   13.6
    90        373  41.963131 -87.656352  ...   170.8   468.7   13.6
    140       582  41.969131 -87.674882  ...   170.8   468.7   13.6
    1          18  41.696367 -87.681315  ...   800.5   741.1    2.6
    [5 rows x 95 columns]

    See also
    --------
    overlay : overlay operation resulting in a new geometry
    GeoDataFrame.sjoin : equivalent method

    Notes
    -----
    Every operation in GeoPandas is planar, i.e. the potential third
    dimension is not taken into account.
    opzwThe `op` parameter is deprecated and will be removed in a future release. Please use the `predicate` parameter instead.r   z@A non-default value for `predicate` was passed (got `predicate="z"` in combination with `op="zr"`). The value of `predicate` will be overridden by the value of `op`, , which may result in unexpected behavior.
   
stacklevelz,sjoin() got an unexpected keyword argument '')popwarningswarnUserWarningFutureWarningnextiterkeys	TypeError_basic_checks_geom_predicate_query_frame_join)left_dfright_dfhow	predicatelsuffixrsuffixkwargsr   Zdeprecation_messageZoverride_messagefirstindicesjoined r&   Q/var/www/html/django/DPS/env/lib/python3.9/site-packages/geopandas/tools/sjoin.pysjoin   s.    S
r(   c                 C   s   t | tstdt| t |ts8tdt|g d}||vrXtd||t| |spt| |dd d|}d|}t| j	||gst|j	||grtd||d	S )
a  Checks the validity of join input parameters.

    `how` must be one of the valid options.
    `'index_'` concatenated with `lsuffix` or `rsuffix` must not already
    exist as columns in the left or right data frames.

    Parameters
    ------------
    left_df : GeoDataFrame
    right_df : GeoData Frame
    how : str, one of 'left', 'right', 'inner'
        join type
    lsuffix : str
        left index suffix
    rsuffix : str
        right index suffix
    z('left_df' should be GeoDataFrame, got {}z)'right_df' should be GeoDataFrame, got {})r	   r
   r   z*`how` was "{}" but is expected to be in {}r   r   index_{}z:'{0}' and '{1}' cannot be names in the frames being joinedN)

isinstancer   
ValueErrorformattyper   r   anycolumnsisin)r   r   r   r    r!   Zallowed_hows
index_leftindex_rightr&   r&   r'   r      s2    





r   c           	      C   s   t  H t ddt |}|dkr6d}| j}|j}n|j}| j}W d   n1 sV0    Y  |r|j||dd\}}t||d}ntjd	d
gt	d}|dkr|j
d
d	dd}|S )aR  Compute geometric comparisons and get matching indices.

    Parameters
    ----------
    left_df : GeoDataFrame
    right_df : GeoDataFrame
    predicate : string
        Binary predicate to query.

    Returns
    -------
    DataFrame
        DataFrame with matching indices in
        columns named `_key_left` and `_key_right`.
    ignorez Generated spatial index is emptyZwithincontainsNF)r   sort)	_key_left
_key_rightr6   r7   r/   Zdtyper/   )r   catch_warningsfilterwarningsr   sindexgeometryquerypd	DataFramefloatrename)	r   r   r   Zoriginal_predicater<   Zinput_geomsl_idxr_idxr$   r&   r&   r'   r      s(    
$r   c              	      s  d  }|jdd}z|jj}|j||_W nB tyr    fddt|jjD }|jj}|j||_Y n0 | }d }|jdd}z|jj}	|j||_W nB ty   fddt|jjD }|jj}	|j||_Y n0 | }|dkr|| 	d} |j
| ddd	j
|j|jjd
dddd  d fd	|jdgd
d}
t|trp||
j_n||
j_n|dkr| 	d} |j
| ddddj
|j|jjd
ddddd  d fd	|jdgd
d}
t|tr||
j_n||
j_n||j|jjd
dj
| j
|dddddddd  d fd	|jddgd
d|jj}
t|trv|	|
j_n|	|
j_|
S )a2  Join the GeoDataFrames at the DataFrame level.

    Parameters
    ----------
    join_df : DataFrame
        Indices and join data returned by the geometric join.
        Must have columns `_key_left` and `_key_right`
        with integer indices representing the matches
        from `left_df` and `right_df` respectively.
        Additional columns may be included and will be copied to
        the resultant GeoDataFrame.
    left_df : GeoDataFrame
    right_df : GeoDataFrame
    lsuffix : string
        Suffix to apply to overlapping column names (left GeoDataFrame).
    rsuffix : string
        Suffix to apply to overlapping column names (right GeoDataFrame).
    how : string
        The type of join to use on the DataFrame level.

    Returns
    -------
    GeoDataFrame
        Joined GeoDataFrame.
    r)   T)deepc                    s"   g | ]\}}d   t| qS r)   r,   str.0posZix)r    r&   r'   
<listcomp>  s   z_frame_join.<locals>.<listcomp>c                    s"   g | ]\}}d   t| qS rF   rG   rI   )r!   r&   r'   rL     s   r   r6   )
left_indexright_index   )Zaxisr7   z_{})left_onrN   suffixesr	   )rM   rN   r   )r   rP   rN   rQ   r
   )rP   rN   r   )rM   Zright_onr   rQ   )r,   copyindexnamerB   r   	enumeratenamesZreset_indexZ	set_indexmergeZdropr=   r*   listZset_geometry)join_dfr   r   r   r    r!   r1   Zleft_index_namer2   Zright_index_namer%   r&   )r    r!   r'   r      s    










	



r   )r   r   max_distancer   return_distance	exclusivec                 C   s   t js t jrt js tdt j |dk}|r:| j}|j}n|j}| j}|r|j|d|||d}	|rp|	\\}
}}n|	\}
}d }|r||
 }}t	j
|dd}|| ||  }}|d ur|| }n
|
| }}t|||d}ntjg dtd}|S )	NzKCurrently, only PyGEOS >= 0.10.0 or Shapely >= 2.0 supports `nearest_all`. r
   T)Z
return_allrZ   r[   r\   Zstable)kind)r6   r7   	distancesr8   )compatZUSE_SHAPELY_20Z
USE_PYGEOSZPYGEOS_GE_010NotImplementedErrorZINSTALL_PYGEOS_ERRORr<   r=   ZnearestnpZargsortr?   r@   rA   )r   r   rZ   r   r[   r\   Zuse_left_as_sindexr<   r>   resZ	input_idxZtree_idxr^   rC   rD   Z
sort_orderrY   r&   r&   r'   _nearest_querya  sL    



rc   F)	r   r   r   rZ   r    r!   distance_colr\   returnc                    s   t | |||| | jjjdd |jjjdd  du}t| |||||}	|r`|	jd id}	n
|	d t|	| ||||}
|r fdd|
jD  g }|
| }
|
S )a  Spatial join of two GeoDataFrames based on the distance between their geometries.

    Results will include multiple output records for a single input record
    where there are multiple equidistant nearest or intersected neighbors.

    Distance is calculated in CRS units and can be returned using the
    `distance_col` parameter.

    See the User Guide page
    https://geopandas.readthedocs.io/en/latest/docs/user_guide/mergingdata.html
    for more details.


    Parameters
    ----------
    left_df, right_df : GeoDataFrames
    how : string, default 'inner'
        The type of join:

        * 'left': use keys from left_df; retain only left_df geometry column
        * 'right': use keys from right_df; retain only right_df geometry column
        * 'inner': use intersection of keys from both dfs; retain only
          left_df geometry column
    max_distance : float, default None
        Maximum distance within which to query for nearest geometry.
        Must be greater than 0.
        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.
    lsuffix : string, default 'left'
        Suffix to apply to overlapping column names (left GeoDataFrame).
    rsuffix : string, default 'right'
        Suffix to apply to overlapping column names (right GeoDataFrame).
    distance_col : string, default None
        If set, save the distances computed between matching geometries under a
        column of this name in the joined GeoDataFrame.
    exclusive : bool, default False
        If True, the nearest geometries that are equal to the input geometry
        will not be returned, default False.
        Requires Shapely >= 2.0.

    Examples
    --------
    >>> import geodatasets
    >>> groceries = geopandas.read_file(
    ...     geodatasets.get_path("geoda.groceries")
    ... )
    >>> chicago = geopandas.read_file(
    ...     geodatasets.get_path("geoda.chicago_health")
    ... ).to_crs(groceries.crs)

    >>> chicago.head()  # doctest: +SKIP
        ComAreaID  ...                                           geometry
    0         35  ...  POLYGON ((-87.60914 41.84469, -87.60915 41.844...
    1         36  ...  POLYGON ((-87.59215 41.81693, -87.59231 41.816...
    2         37  ...  POLYGON ((-87.62880 41.80189, -87.62879 41.801...
    3         38  ...  POLYGON ((-87.60671 41.81681, -87.60670 41.816...
    4         39  ...  POLYGON ((-87.59215 41.81693, -87.59215 41.816...
    [5 rows x 87 columns]

    >>> groceries.head()  # doctest: +SKIP
        OBJECTID     Ycoord  ...  Category                         geometry
    0        16  41.973266  ...       NaN  MULTIPOINT (-87.65661 41.97321)
    1        18  41.696367  ...       NaN  MULTIPOINT (-87.68136 41.69713)
    2        22  41.868634  ...       NaN  MULTIPOINT (-87.63918 41.86847)
    3        23  41.877590  ...       new  MULTIPOINT (-87.65495 41.87783)
    4        27  41.737696  ...       NaN  MULTIPOINT (-87.62715 41.73623)
    [5 rows x 8 columns]

    >>> groceries_w_communities = geopandas.sjoin_nearest(groceries, chicago)
    >>> groceries_w_communities[["Chain", "community", "geometry"]].head(2)
                    Chain community                              geometry
    0   VIET HOA PLAZA    UPTOWN  MULTIPOINT (1168268.672 1933554.350)
    87      JEWEL OSCO    UPTOWN  MULTIPOINT (1168837.980 1929246.962)


    To include the distances:

    >>> groceries_w_communities = geopandas.sjoin_nearest(groceries, chicago, distance_col="distances")
    >>> groceries_w_communities[["Chain", "community", "distances"]].head(2)  # doctest: +SKIP
                    Chain community  distances
    0   VIET HOA PLAZA    UPTOWN        0.0
    87      JEWEL OSCO    UPTOWN        0.0

    In the following example, we get multiple groceries for Uptown because all
    results are equidistant (in this case zero because they intersect).
    In fact, we get 4 results in total:

    >>> chicago_w_groceries = geopandas.sjoin_nearest(groceries, chicago, distance_col="distances", how="right")
    >>> uptown_results = chicago_w_groceries[chicago_w_groceries["community"] == "UPTOWN"]
    >>> uptown_results[["Chain", "community"]]  # doctest: +SKIP
                Chain community
    30  VIET HOA PLAZA    UPTOWN
    30      JEWEL OSCO    UPTOWN
    30          TARGET    UPTOWN
    30       Mariano's    UPTOWN

    See also
    --------
    sjoin : binary predicate joins
    GeoDataFrame.sjoin_nearest : equivalent method

    Notes
    -----
    Since this join relies on distances, results will be inaccurate
    if your geometries are in a geographic CRS.

    Every operation in GeoPandas is planar, i.e. the potential third
    dimension is not taken into account.
    rO   r   Nr^   r9   c                    s   g | ]}| kr|qS r&   r&   )rJ   crd   r&   r'   rL   &      z!sjoin_nearest.<locals>.<listcomp>)	r   r=   valuesZcheck_geographic_crsrc   rB   r   r   r/   )r   r   r   rZ   r    r!   rd   r\   r[   rY   r%   r/   r&   rg   r'   sjoin_nearest  s    |
rj   )r   r   r	   r
   )r   Nr	   r
   NF)typingr   r   numpyra   Zpandasr?   Z	geopandasr   r   r_   Zgeopandas.arrayr   r   r(   r   r   r   rA   rH   boolrc   rj   r&   r&   r&   r'   <module>   sL       
t27y9      