
    h[d                     H   d dl Z d dlmZ d dlZd dlZd dlmZ d dl	m
Z
 d dlmZmZ 	 	 	 	 	 	 ddZd	 Zd d
Zd dZd Zdej&                  dej&                  fdZd Zd Z	 d dZ	 d dedededededededz  fdZd Z	 	 	 	 	 	 d!dededededz  dedededz  dedefdZy)"    N)partial)GeoDataFrame)PANDAS_GE_30)
_check_crs_crs_mismatch_warnleftrightc                     |r1t        t        |j                                     }	t        d|	 d      t	        |      }t        | |||||       t        | ||||      }
t        | ||
d|||||	      \  }}|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).
    distance : number or array_like, optional
        Distance(s) around each input geometry within which to query the tree
        for the 'dwithin' predicate. If array_like, must be
        one-dimesional with length equal to length of left GeoDataFrame.
        Required if ``predicate='dwithin'``.
    on_attribute : string, list or tuple
        Column name(s) to join on as an additional join restriction on top
        of the spatial predicate. These must be found in both DataFrames.
        If set, observations are joined only if the predicate applies
        and values in specified columns match.

    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       community                           geometry
    0        16          UPTOWN  MULTIPOINT ((-87.65661 41.97321))
    1        18     MORGAN PARK  MULTIPOINT ((-87.68136 41.69713))
    2        22  NEAR WEST SIDE  MULTIPOINT ((-87.63918 41.86847))
    3        23  NEAR WEST SIDE  MULTIPOINT ((-87.65495 41.87783))
    4        27         CHATHAM  MULTIPOINT ((-87.62715 41.73623))
    [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.
    z,sjoin() got an unexpected keyword argument '')on_attributeN)nextiterkeys	TypeError_maybe_make_list_basic_checks_geom_predicate_query_frame_join)left_dfright_dfhow	predicatelsuffixrsuffixdistancer   kwargsfirstindicesjoined_s                H/var/www/html/immo/lib/python3.12/site-packages/geopandas/tools/sjoin.pysjoinr"      s    ~ T&++-()FugQOPP#L1L'8S'7V#9h\G !
IFA M    c                 f    t        | t              rt        |       S | t        | t              s| gS | S N)
isinstancetuplelist)objs    r!   r   r      s0    #uCy
z#t4uJr#   c                    t        | t              st        dt        |              t        |t              st        dt        |             g d}||vrt        d| d|       t	        | |      st        | |d       |r~|D ]x  }|| vr||vrt        d| d	      || vrt        d| d
      ||vrt        d| d      || j                  j                  |j                  j                  fv sot        d       yy)a2  Check 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
    on_attribute : list, default None
        list of column names to merge on along with geometry
    z&'left_df' should be GeoDataFrame, got z''right_df' should be GeoDataFrame, got )r   r	   innerz`how` was "z" but is expected to be in    
stacklevelzExpected column z( is missing from both of the dataframes.z$ is missing from the left dataframe.z% is missing from the right dataframe.zMActive geometry column cannot be used as an input for on_attribute parameter.N)r&   r   
ValueErrortyper   r   geometryname)r   r   r   r   r   r   allowed_howsattrs           r!   r   r      sD   ( g|,A$w-QRRh-B4>BRSTT-L
,;se+F|nUVVgx(7H;  	DG#$h*> &tf,TU  7" &tf,PQ  8# &tf,QR  ((--x/@/@/E/EFF 2 	 r#   c                    |}|dk(  rd}| j                   }|j                  }n|j                   }| j                  }|r|j                  ||d|      \  }}	nJt        j                  g t        j
                        t        j                  g t        j
                        }	}|dk(  r%||	}}	t        j                  |	|f      }
||
   }|	|
   }	|r|D ]  }t        | |||	|      \  \  }}	} ||	fS )a  Compute geometric comparisons and get matching indices.

    Parameters
    ----------
    left_df : GeoDataFrame
    right_df : GeoDataFrame
    predicate : string
        Binary predicate to query.
    on_attribute: list, default None
        list of column names to merge on along with geometry


    Returns
    -------
    DataFrame
        DataFrame with matching indices in
        columns named `_key_left` and `_key_right`.
    withincontainsF)r   sortr   dtype)sindexr1   querynparrayintplexsort_filter_shared_attribute)r   r   r   r   r   original_predicater;   input_geomsl_idxr_idxindexerr4   r    s                r!   r   r      s   & #H 	'' &&||958 $ 
u
 xx"''2BHHRrww4OuX% eu**eU^,gg  	D 85%!NUEA	
 %<r#   c                    | j                   j                  }t        r| j                         }n| }|j                  d       |j                  j                  d      }t        |      D ]b  \  }}|	||   }d|v r|j                  d      d   }	d| |	 }nd| }|| j                  v s||j                  v rt        d| d	      |||<   d |t        j                  |      fS )
zf
    Equivalent of df.reset_index(), but with adding 'suffix' to auto-generated
    column names.
    Tinplacecopylevelr       index_r   z4' cannot be a column name in the frames being joined)indexnamesr   reset_indexcolumnsto_numpy	enumeratesplitr/   pdIndex)
dfsuffixotherindex_originaldf_resetcolumn_namesilabel	new_labellevs
             r!   _reset_index_with_suffixrb      s    
 XX^^N>># T*##,,$,7Ln- (5=$QI)#ooc*1-$VHSE2	$VH-	BJJ&)u}}*D 	{"VW  (LO(  RXXl+++r#   c           	         | j                  |      t              dk(  r| |fS |\  }}|s|st        d       fd}t        ||t	        |dd            }t        ||t	        |dd            }	t        j                  | D 
cg c]
  }
 ||
       c}
      }t        j                  |D 
cg c]
  }
 |	|
       c}
      }g }|j                  s3||j                         | j                          z     j                         }|j                  sB|j                  ||j                         |j                          z     j                                |r)t        j                  dt        |       dt        d	
       ||fS c c}
w c c}
w )z
    Add suffixes to overlapping labels (ignoring the geometry column).

    This is based on pandas' merge logic at https://github.com/pandas-dev/pandas/blob/
    a0779adb183345a8eb4be58b3ad00c223da58768/pandas/core/reshape/merge.py#L2300-L2370
    r   z)columns overlap but no suffix specified: c                 ,    | v r| |k7  r	||  d| S | S )Nr     )xrY   r1   	to_renames      r!   renamerz2_process_column_names_with_suffix.<locals>.renamer1  s*    	>a8m0BS&?"r#   _geometry_column_nameN)rY   r1   z1Passing 'suffixes' which cause duplicate columns zM in the result is deprecated and will raise a MergeError in a future version.r,   r-   )intersectionlenr/   r   getattrrV   rW   	is_unique
duplicatedtolistextendwarningswarnsetFutureWarning)r   r	   suffixesr   r   r   r   rh   lrenamerrrenamerlableft_renamedright_renameddupsrg   s                 @r!   !_process_column_names_with_suffixr|     s    !!%(I
9~U{GW7DYKPQQ
 "94@H
 #:DAH 88d;sXc];<LHHu=hsm=>MD!! \446DOO<M;MNOVVX""=3355;K;K;M:MNOVVX	
 ?D	{ KT U		
 &&+ <=s   F/Fc                    t         r| j                  t        |            } n| j                  t        |      d       t        | j                  j                        }t        |      D ]  \  }}|	d||<    || j                  _        | S )z
    Set back the the original index columns, and restoring their name as `None`
    if they didn't have a name originally.
    TrH   N)r   	set_indexr(   rO   rP   rT   )r   index_namesindex_names_originaljoined_index_namesr^   r_   s         r!   _restore_indexr   Z  s    
 !!${"34k*D9 fll00123 )5=$(q!) ,FLLMr#   c                    |dk(  r| |fS | \  }}|dk(  r,t        j                  ||f      }||   ||   }}|||   }||}}t        j                  |      }|t        j                  ||          }	t        j                  ||	      }
t        j
                  ||
|	      }t        j
                  ||
d      }|%t        j
                  ||
t         j                        }|dk(  r||}}||f|fS )a  Adjust the indexers for the join based on the `how` parameter.

    The left/right indexers from the query represents an inner join.
    For a left or right join, we need to adjust them to include the rows
    that would not be present in an inner join.
    r+   r	   )r=   r@   arangeisinsearchsortedinsertnan)r   	distancesoriginal_lengthr   r   rD   rE   rF   idxl_idx_missing
insert_idxs              r!   _adjust_indexersr   m  s     g~	!!LE5
g~**eU^,W~uW~u !'*I eu ))O
$Ce,,-M6JIIeZ7EIIeZ,EIIiRVV<	
g~eu5>9$$r#   c	                 n   |r|j                  |d      }|dv r(|j                  |j                  j                  d      }n'| j                  | j                  j                  d      } | j                  d      } | j                  j
                  }	| j                  j                  }
t        | ||      \  } }|j                  d      }|j                  j
                  }|j                  j                  }t        |||       \  }}t        ||||f| |      \  }}|| _	        ||_	        | j                  d|	 }|j                  d| }|dk(  rt        |      n
t        |       }t        |||||      \  \  }}}t        j                  t        |            }| j                  d||fi      }|j                  d||fi      }t        ri }nt!        d	      }t        j"                  ||gfd
di|}|dv rt%        |||
      }||fS |j'                  |j                  j                        }t%        |||      }||fS )ab  Join the GeoDataFrames at the DataFrame level.

    Parameters
    ----------
    left_df : GeoDataFrame
    right_df : GeoDataFrame
    indices : tuple of ndarray
        Indices returned by the geometric join. Tuple with with integer
        indices representing the matches from `left_df` and `right_df`
        respectively.
    distances : ndarray, optional
        Passed trough and adapted based on the indices, if needed.
    how : string
        The type of join to use on the DataFrame level.
    lsuffix : string
        Suffix to apply to overlapping column names (left GeoDataFrame).
    rsuffix : string
        Suffix to apply to overlapping column names (right GeoDataFrame).
    on_attribute: list, default None
        list of column names to merge on along with geometry


    Returns
    -------
    GeoDataFrame
        Joined GeoDataFrame.
    rM   )axis)r+   r   F)deepNr	   r   rJ   r   )dropr1   r2   rK   rO   nlevelsrP   rb   r|   rR   rk   r   rV   
RangeIndex_reindex_with_indexersr   dictconcatr   set_geometry)r   r   r   r   r   r   r   r   r   left_nlevelsleft_index_originalleft_column_namesright_nlevelsright_index_originalright_column_names
left_indexright_indexr   rD   rE   	new_indexr   r	   r   r   s                            r!   r   r     sH   L ==A=6
==!2!2!7!7a=@,,w//441,=lll&G==((L!----!9'7H!UG}}%}(HNN**M#>>//#;Hgw#W H  -N	'-)) (GO)H,/J"">M2K (+g~c(m3w<O 0OS)!NUEI c%j)I))1y%.@*ABD++QE0B,CDE5!YYe}7177F

4GH
 9 $$X%6%6%;%;<5IJ9r#   r   r   max_distancer   return_distance	exclusiver   c                 h   |dk(  }|r| j                   }|j                  }	n|j                   }| j                  }	|r\|j                  |	d|||      }
|r	|
\  \  }}}n|
\  }}d }|r-||}}t        j                  |d      }||   ||   }}|||   }ny||}}ntt        j
                  g t        j                        t        j
                  g t        j                        }}|r&t        j
                  g t        j                        }nd }|r!|D ]  }t        | ||||      \  \  }}}||   } ||f|fS )Nr	   T)
return_allr   r   r   stable)kindr9   )	r;   r1   nearestr=   argsortr>   r?   float64rA   )r   r   r   r   r   r   r   use_left_as_sindexr;   r<   res	input_idxtree_idxr   rD   rE   
sort_orderr4   shared_attribute_rowss                      r!   _nearest_queryr     s]    !!  nn%+  
 /2,!Y9$'!YI#Y5EE9J ,eJ.?5E$%j1	$h5E xx"''2BHHRrww4Ou2::6II  	9D4L5%51NUE1 ""78I		9 5>9$$r#   c                     | |   j                   |   j                  ||   j                   |   j                  k(  }||   }||   }||f|fS )zReturn the indices for the left and right dataframe that share the same entry
    in the attribute column.

    Also returns a Boolean `shared_attribute_rows` for rows with the same entry.
    )ilocvalues)r   r   rD   rE   	attributer   s         r!   rA   rA   .  se     		&--)1D1I1I%1P1W1WW  '(E'(E5>000r#   r   r   distance_colreturnc           
      "   t        | ||||       | j                  j                  j                  d       |j                  j                  j                  d       |du}t	        | |||||      \  }	}
t        | ||	|
|||d      \  }}
|r|
||<   |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.

    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.35))
    1  COUNTY FAIR FOODS  MORGAN PARK  MULTIPOINT ((1162302.618 1832900.224))


    To include the distances:

    >>> groceries_w_communities = geopandas.sjoin_nearest(groceries, chicago, distance_col="distances")
    >>> groceries_w_communities[["Chain", "community", "distances"]].head(2)
                   Chain    community  distances
    0     VIET HOA PLAZA       UPTOWN        0.0
    1  COUNTY FAIR FOODS  MORGAN PARK        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"]]
                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.
    rM   r-   N)r   r1   r   check_geographic_crsr   r   )r   r   r   r   r   r   r   r   r   r   r   r   s               r!   sjoin_nearestr   =  s    v '8S'7;00A0>11Q1?"$.O'GY $	FI (|Mr#   )r+   
intersectsr   r	   NNr%   )r+   Nr   r	   NF)rq   	functoolsr   numpyr=   pandasrV   	geopandasr   geopandas._compatr   geopandas.arrayr   r   r"   r   r   r   rb   rW   r|   r   r   r   floatstrboolr(   r   rA   r   re   r#   r!   <module>r      sX       " * : 	wt3l8v,@8'
((8'888'v&'%f \L !%5%5%5% 5% 
	5%
 5% 5% +5%p1$ !%#XXX 
X $,	X
 X X *X X Xr#   