
    hT                        d dl Z 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Zd dlmZ d dlmZ d dlmZ d dlmZmZ g dZ G d	 d
      Z G d d      Z	 	 	 	 d'dZdddde
ej0                     dededz  deej6                  ej8                  f   fdZd(dZd Zd Z d Z!d Z"d Z#	 d(ddddde
ej0                     de$dz  dededz  de$deej6                  ej8                  f   fdZ%d  Z&d)d!Z'd" Z(d# Z)d$ej8                  d%efd&Z*y)*    N)Version)NDArray)GeometryType)GeoDataFrame)SHAPELY_GE_204)from_shapelyfrom_wkb)point
linestringpolygon
multipointmultilinestringmultipolygonc                       e Zd ZdZd ZddZy)
ArrowTablea  
    Wrapper class for Arrow data.

    This class implements the `Arrow PyCapsule Protocol`_ (i.e. having an
    ``__arrow_c_stream__`` method). This object can then be consumed by
    your Arrow implementation of choice that supports this protocol.

    .. _Arrow PyCapsule Protocol: https://arrow.apache.org/docs/format/CDataInterface/PyCapsuleInterface.html

    Example
    -------
    >>> import pyarrow as pa
    >>> pa.table(gdf.to_arrow())  # doctest: +SKIP

    c                     || _         y N)	_pa_table)selfpa_tables     I/var/www/html/immo/lib/python3.12/site-packages/geopandas/io/_geoarrow.py__init__zArrowTable.__init__.   s	    !    Nc                 :    | j                   j                  |      S )N)requested_schema)r   __arrow_c_stream__r   r   s     r   r   zArrowTable.__arrow_c_stream__1   s    ~~00BR0SSr   r   )__name__
__module____qualname____doc__r   r    r   r   r   r      s     "Tr   r   c                       e Zd ZdZd ZddZy)GeoArrowArraya  
    Wrapper class for a geometry array as Arrow data.

    This class implements the `Arrow PyCapsule Protocol`_ (i.e. having an
    ``__arrow_c_array/stream__`` method). This object can then be consumed by
    your Arrow implementation of choice that supports this protocol.

    .. _Arrow PyCapsule Protocol: https://arrow.apache.org/docs/format/CDataInterface/PyCapsuleInterface.html

    Example
    -------
    >>> import pyarrow as pa
    >>> pa.array(ser.to_arrow())  # doctest: +SKIP

    c                      || _         || _        y r   )	_pa_array	_pa_field)r   pa_fieldpa_arrays      r   r   zGeoArrowArray.__init__F   s    !!r   Nc                     |t        d      | j                  j                         | j                  j	                         d   fS )Nz5Requested schema is not supported for geometry arrays   )NotImplementedErrorr'   __arrow_c_schema__r&   __arrow_c_array__r   s     r   r.   zGeoArrowArray.__arrow_c_array__J   sI    '%G  NN--/NN,,.q1
 	
r   r   )r   r   r    r!   r   r.   r"   r   r   r$   r$   5   s     "
r   r$   Tc                    | j                   dk(  }| j                  |   }t        j                  |      j	                         d   }t        j                  | j                  d            }|D ]  }	d||	<   	 t        j                  j                  ||      }
i }|j                         dk(  rt        ||      D ]  \  }}	t        t        j                  | |	   j                        ||	| |	   j                  |      \  }}|
j!                  |||      }
|j"                  d	   j%                         j'                  d
      ||	<    |
|fS |j                         dk(  rnt        ||      D ][  \  }}	t)        t        j                  | |	   j                        |	| |	   j                        \  }}|
j!                  |||      }
d||	<   ] |
|fS t+        d|       )a  
    Convert GeoDataFrame to a pyarrow.Table.

    Parameters
    ----------
    df : GeoDataFrame
        The GeoDataFrame to convert.
    index : bool, default None
        If ``True``, always include the dataframe's index(es) as columns
        in the file output.
        If ``False``, the index(es) will not be written to the file.
        If ``None``, the index(ex) will be included as columns in the file
        output except `RangeIndex` which is stored as metadata only.
    geometry_encoding : {'WKB', 'geoarrow' }, default 'WKB'
        The GeoArrow encoding to use for the data conversion.
    interleaved : bool, default True
        Only relevant for 'geoarrow' encoding. If True, the geometries'
        coordinates are interleaved in a single fixed size list array.
        If False, the coordinates are stored as separate arrays in a
        struct type.
    include_z : bool, default None
        Only relevant for 'geoarrow' encoding (for WKB, the dimensionality
        of the individial geometries is preserved).
        If False, return 2D geometries. If True, include the third dimension
        in the output (if a geometry has no third dimension, the z-coordinates
        will be NaN). By default, will infer the dimensionality from the
        input geometries. Note that this inference can be unreliable with
        empty geometries (for a guaranteed result, it is recommended to
        specify the keyword).

    geometryr   F)deepN)preserve_indexgeoarrow)	include_z
field_namecrsinterleaved   ARROW:extension:name	geoarrow.wkbr5   r6   WKBz3Expected geometry encoding 'WKB' or 'geoarrow' got )dtypescolumnsnpasarraynonzeropd	DataFramecopypaTablefrom_pandaslowerzipconstruct_geometry_arrayarrayr6   
set_columnmetadatadecoderemoveprefixconstruct_wkb_array
ValueError)dfindexgeometry_encodingr7   r4   maskgeometry_columnsgeometry_indicesdf_attrcoltablegeometry_encoding_dictifieldgeom_arrwkb_arrs                   r   geopandas_to_arrowr`   U   s   L 99
"Dzz$'zz$'//1!4ll2777./G
    HH   ?E J.*,<= 	FAs6C'#sGKK'OE8 $$Qx8E67k* #3'	8 ((( 
	 	 	"e	+*,<= 	0FAs0

2c7==)cr#w{{NE7 $$Qw7E*/"3'	0 ((( ABSATU
 	
r   r0   r;   shapely_arrr5   r6   returnc                   t         j                  dkD  rddi}n0t        j                  |       j                         rt	        d      i }t        j
                  | fi |}ddi}|)t        j                  d|j                         i      |d<   nd	|d<   t        j                  |t        j                         d
|      }t        j                  t        j                  |      t        j                               }||fS )N)   
   r   flavorisoz)Cannot write 3D geometries with GEOS<3.10ARROW:extension:namegeoarrow.wkbr6   ARROW:extension:metadata{}T)typenullablerM   )shapelygeos_versionhas_zanyrQ   to_wkbjsondumpsto_json_dictrE   r]   binaryrK   r?   r@   )ra   r5   r6   kwargsr_   extension_metadatar]   parrs           r   rP   rP      s     j(E"==%))+HIInn[3F3G0.A
9=C$$&':
56 :>56HHt>PE 88BJJw'5D$;r   c                 z   |rt        j                  |t        j                         d      }t        j                  |t	        |            }|1t         j
                  j                  | j                         |      }|S t         j
                  j                  | j                         ||      }|S |dk(  rt        j                  dt        j                         d      t        j                  dt        j                         d      g}t         j                  j                  | d d df   j                         | d d d	f   j                         g||
      }|S t        j                  dt        j                         d      t        j                  dt        j                         d      t        j                  dt        j                         d      g}t         j                  j                  | d d df   j                         | d d d	f   j                         | d d df   j                         g||
      }|S )NFrm   rl   rl   rU   xyxyr   r+   )fieldsrU   z   )
rE   r]   float64list_lenFixedSizeListArrayfrom_arraysravelStructArrayrD   )coordsr7   dimsrU   coords_fieldtypry   r   s           r   _convert_inner_coordsr      s   xxbjjlUChh|SY/<((44V\\^#4ND2 K/ ((44St 5 D. K' 4<bjjlU;bjjlU;F >>--1""$fQTl&7&7&9:6PT . D K bjjlU;bjjlU;bjjlU;F
 >>--1""$fQTl&7&7&96!Q$<;L;L;NO . D
 Kr   c                 X    t        j                  t        j                  d| d            S )NverticesFr{   rE   r   r]   
point_types    r   _linestring_typer      s    88BHHZeDEEr   c                     t        j                  t        j                  dt        j                  t        j                  d| d            d            S )Nringsr   Fr{   r   r   s    r   _polygon_typer      s>    88
HHRXXj*uEF	
 r   c                 X    t        j                  t        j                  d| d            S )NpointsFr{   r   r   s    r   _multipoint_typer      s    88BHHXzEBCCr   c                 j    t        j                  t        j                  dt        |       d            S )NlinestringsFr{   )rE   r   r]   r   r   s    r   _multilinestring_typer      s)    88
 0 <uM r   c                 j    t        j                  t        j                  dt        |       d            S )NpolygonsFr{   )rE   r   r]   r   r   s    r   _multipolygon_typer     s#    88BHHZz)BUSTTr   )r5   r6   r7   r4   r7   c                   t        j                  |       }t        |       dk(  s|j                         rt	        d      t        j
                  | |      \  }}}|j                         r|t        j                  k(  r2|r0t        t        j                        t        d      k  rt        d      t        j                  |t        j                               }|t        j                  k(  rit        sct!        j"                  |      d   }	|	t!        j$                  t        |	            z
  }	t!        j&                  ||	t         j(                  d      }nd }|j*                  d   d	k(  rd
}
n-|j*                  d   dk(  rd}
nt        d|j*                         i }|)t-        j.                  d|j1                         i      |d<   nd|d<   |t        j                  k(  r;t3        |||
|      }d|d<   t        j4                  ||j6                  d|      }||fS |t        j8                  k(  rt        |      dk(  sJ d       |\  }t3        |||
      }t        j:                  j=                  t        j                  |      |t?        |j6                        |      }d|d<   t        j4                  ||j6                  d|      }||fS |t        j@                  k(  rt        |      d	k(  sJ d       |\  }}t3        |||
      }t        j:                  j=                  t        j                  |      |      }t        j:                  j=                  t        j                  |      ||      }|jC                  tE        |j6                              }d|d<   t        j4                  ||j6                  d|      }||fS |t        jF                  k(  rt        |      dk(  sJ d       |\  }t3        |||
      }t        j:                  j=                  t        j                  |      |tI        |j6                        |      }d|d<   t        j4                  ||j6                  d|      }||fS |t        jJ                  k(  rt        |      d	k(  sJ d       |\  }}t3        |||
      }t        j:                  j=                  t        j                  |      |      }t        j:                  j=                  t        j                  |      ||      }|jC                  tM        |j6                              }d|d<   t        j4                  ||j6                  d|      }||fS |t        jN                  k(  rt        |      dk(  sJ d       |\  }}}t3        |||
      }t        j:                  j=                  t        j                  |      |      }t        j:                  j=                  t        j                  |      |      }t        j:                  j=                  t        j                  |      ||      }|jC                  tQ        |j6                              }d|d<   t        j4                  ||j6                  d|      }||fS t        d |       )!Nr   z`Converting an empty or all-missing GeoDataFrame to the 'geoarrow' encoding is not yet supported.)r4   z15.0.0zConverting point geometries with missing values is not supported for interleaved coordinates with pyarrow < 15.0.0. Please upgrade to a newer version of pyarrow.r|   )axisr   r~   rd   xyzzUnexpected coords dimensions: r6   rj   rk   )rU   geoarrow.pointrh   T)rm   rM   r+   zExpected one offsets arraygeoarrow.linestringzExpected two offsets arraysgeoarrow.polygonr}   geoarrow.multipointgeoarrow.multilinestringzExpected three offsets arraysgeoarrow.multipolygonzUnsupported type for geoarrow: ))rn   
is_missingr   allr,   to_ragged_arrayrq   r   POINTr   rE   __version__rQ   rK   bool_r   r?   rA   arangeinsertnanshapers   rt   ru   r   r]   rl   
LINESTRING	ListArrayr   r   POLYGONcastr   
MULTIPOINTr   MULTILINESTRINGr   MULTIPOLYGONr   )ra   r4   r5   r6   r7   rU   	geom_typer   offsetsindicesr   rx   ry   r]   geom_offsets_parrring_offsets_parr1polygon_offsets_parr2s                       r   rJ   rJ   
  s    k*D
;1
!-
 	

 ")!8!8y"Ivw xxz+++''(*;;9 
 xx288:.***> jj&q)G		#g, 77GYYvwQ?F ||B1	b	Q	9&,,HII)+
9=C$$&':
56 :>56L&&&$V[$TJ5E12II'	
 d{	l--	-7|q >">> !%fk4@||''HH\"E+;EJJ+Gd ( 
 6K12II'	
 d{	l**	*7|q ?"?? %,"l%fk4@))"((<*@%H||''(>T'Ryyuzz235G12II'	
 d{	l--	-7|q >">> !%fk4@||''HH\"E0@0LSW ( 
 6K12II'	
 d{	l22	27|q ?"?? %,"l%fk4@))"((<*@%H||''(>T'Ryy.uzz:;5O12II'	
 d{	l//	/7|q A"AA 6=3o|%fk4@))"((<*@%H))"((?*CVL||''(>T'Ryy+EJJ785L12II'	
 d{ :9+FGGr   c                 &   | j                   x}o|j                  dd       x}[|j                  d      rJ|j                  dd       x}	 #t        j                  |j                               }|j                         |fS t        | j                  t        j                        rp| j                  j                  }|j                  d      rI| j                  j                         }|r't        j                  |j                               }||fS d }||fS y )Nr8   s	   geoarrow.s   ARROW:extension:metadatar9   )rM   get
startswithrs   loadsrN   
isinstancerl   rE   ExtensionTypeextension_name__arrow_ext_serialize__)r]   metaext_nameext_metaext_meta_sers        r   _get_arrow_geometry_fieldr     s    +!8$??HL""<0 $)Dd KKH  $zz(//*;<H((22%**b../::,,{+ ::==?L::l&9&9&;< X%%  X%%r   c                     t        | t        j                        st        j                  |       } g }t	        | j
                        D ]3  \  }}t        |      }||j                  ||j                  g|       5 t        |      dk(  rt        d      | j                  |D cg c]  }|d   	 c}      }|i } |j                  di |}	|D ]  \  }}
}}d}|	d|v r|d   }|dk(  r$t        t        j                  | |
         |      }nQ|j!                  d      d   t"        v r)t%        t'        | |
   j)                         |      |      }nt+        d	|       |	j-                  ||
|        t/        |	|xs |d   d   
      S c c}w )a2  
    Convert Arrow table object to a GeoDataFrame based on GeoArrow extension types.

    Parameters
    ----------
    table : pyarrow.Table
        The Arrow table to convert.
    geometry : str, default None
        The name of the geometry column to set as the active geometry
        column. If None, the first geometry column found will be used.
    to_pandas_kwargs : dict, optional
        Arguments passed to the `pa.Table.to_pandas` method for non-geometry columns.
        This can be used to control the behavior of the conversion of the non-geometry
        columns to a pandas DataFrame. For example, you can use this to control the
        dtype conversion of the columns. By default, the `to_pandas` method is called
        with no additional arguments.

    Returns
    -------
    GeoDataFrame

    Nr   z,No geometry column found in the Arrow table.r+   r6   ri   r6   .!Unknown GeoArrow extension type: )r0   r"   )r   rE   rF   rZ   	enumerateschemar   appendnamer   rQ   drop	to_pandasr	   r?   rK   splitGEOARROW_ENCODINGSr   construct_shapely_arraycombine_chunks	TypeErrorr   r   )rZ   r0   to_pandas_kwargsgeom_fieldsr\   r]   geomf
table_attrrR   rY   r   r   r6   r^   s                  r   arrow_to_geopandasr     s   . eRXX&Kell+ 75(/5::5567
 ;1GHH;7aQqT78J				1 0	1B&1 $"3(EX$55/C~%s 4#>H^^C #'99#'c
(A(A(CXNTWH ?zJKK
		!S(#$  X%BQ1BCC+ 8s   %Fc                 F   t        t        j                        t        d      k  rt        d      | j	                         \  }}t        j
                  j                  |      }t        j                  j                  |j                         |      }t        |      }|t        d      |\  }}d}|	d|v r|d   }|dk(  r"t        t        j                  |      |      }	|	S |j                  d      d	   t        v rt        t!        ||      |      }	|	S t        d
|       )z
    Convert Arrow array object (representing single GeoArrow array) to a
    geopandas GeometryArray.

    Specifically for GeoSeries.from_arrow.
    z14.0.0z.Importing from Arrow requires pyarrow >= 14.0.Nz!No GeoArrow geometry field found.r6   ri   r   r   r+   r   )r   rE   r   rQ   r.   Field_import_from_c_capsuleArrayr-   r   r	   r?   rK   r   r   r   r   )
arrschema_capsulearray_capsuler]   pa_arr	geom_infor   r   r6   r^   s
             r   arrow_to_geometry_arrayr      s    r~~!22IJJ$'$9$9$;!NMHH++N;EXX,,U-E-E-GWF)%0I<=="Hh
C 1uo>!BHHV,#6 O 
	Q	#5	5 7 IsS O <XJGHHr   c           	         t         j                  j                  | j                        r| j                  j                  dk(  r]t        j                  t        j                  | j                  d            t        j                  | j                  d            g      }|S t        j                  t        j                  | j                  d            t        j                  | j                  d            t        j                  | j                  d            g      }|S t        j                  | j                        j                  t        |       d      S )Nr   r   r   r   r   )rE   types	is_structrl   
num_fieldsr?   column_stackr@   r]   valuesreshaper   )r   r   s     r   _get_inner_coordsr   !  s    	xx#((#88!#__CIIcN+RZZ		#-GHF  __JJsyy~.JJsyy~.JJsyy~.F  zz#**%--c#h;;r   r   r   c                    t        | t        j                        r| j                  } |dk(  r2t	        |       }t        j                  t        j                  |d      }n|dk(  r^t	        | j                        }t        j                  | j                        }|f}t        j                  t        j                  ||      }no|dk(  rt	        | j                  j                        }t        j                  | j                        }t        j                  | j                  j                        }||f}t        j                  t        j                  ||      }n|dk(  r^t	        | j                        }t        j                  | j                        }|f}t        j                  t        j                  ||      }nu|dk(  rt	        | j                  j                        }t        j                  | j                        }t        j                  | j                  j                        }||f}t        j                  t        j                   ||      }n|dk(  rt	        | j                  j                  j                        }t        j                  | j                        }t        j                  | j                  j                        }t        j                  | j                  j                  j                        }|||f}t        j                  t        j"                  ||      }nt%        |      | j&                  r:t        j                  | j)                               }t        j*                  |d|      }|S )zo
    Construct a NumPy array of shapely geometries from a pyarrow.Array
    with GeoArrow extension type.

    r   Nr   r   r   r   r   )r   rE   ExtensionArraystorager   rn   from_ragged_arrayr   r   r   r?   r@   r   r   r   r   r   r   rQ   
null_countis_nullwhere)	r   r   r   resultoffsets1r   offsets2offsets3rU   s	            r   r   r   5  s    #r(()kk))"3'**<+=+=vtL	0	0"3::.::ckk*+**<+B+BFGT	-	-"3::#4#45::ckk*::cjj001X&**<+?+?Q	0	0"3::.::ckk*+**<+B+BFGT	5	5"3::#4#45::ckk*::cjj001X&**((&'
 
2	2"3::#4#4#;#;<::ckk*::cjj001::cjj//778Xx0**<+D+DfgV (( ~~zz#++-($f-Mr   )Nr<   TNr   )NN)+rs   packaging.versionr   numpyr?   pandasrB   pyarrowrE   numpy.typingr   rn   r   	geopandasr   geopandas._compatr   geopandas.arrayr   r	   r   r   r$   r`   object_strtupler   r   rP   r   r   r   r   r   r   boolrJ   r   r   r   r   r   r"   r   r   <module>r     s    %         " , 2 T T0
 
D T)t !	$  
t	
 288RXX@DFDU "]H !]H$]Hd{]H 	]H
 
t]H ]H 288RXX]HF.9DxB<(9 93 9r   