a
    1$ef                     @   s  d dl Z d dlm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mZ d dlmZ d d	lmZmZmZ d dlZeee e Zed
 ed dada da!da"dd Z#da$da%dd Z&dd Z'dd Z(dd Z)dddddddddddddd d d!d!d!d"d#d$Z*d%d& Z+d'd( Z,d)d* Z-dBd+d,Z.dCd-d.Z/dDd/d0Z0d1d2 Z1d3d4 Z2d5d6 Z3dEd8d9Z4d:d; Z5d<d= Z6d>d? Z7d@dA Z8dS )F    N)Version)Path)is_integer_dtype)mapping)BaseGeometry)GeoDataFrame	GeoSeries)urlparse)uses_netlocuses_paramsuses_relative fileFc                  C   s   t d u rzpdd l a zddl ma W n: ty\   zddl ma W n tyV   d aY n0 Y n0 ttt jjtdkaW n0 ty }  zda t	| a
W Y d } ~ n
d } ~ 0 0 d S )Nr   )Env)driversz1.9.0F)fionar   	fiona_envImportErrorr   r   __version__base_versionFIONA_GE_19strfiona_import_errorerr r   M/var/www/html/django/DPS/env/lib/python3.9/site-packages/geopandas/io/file.py_import_fiona"   s     
r   c               
   C   sJ   t d u rFzdd l a W n0 tyD }  zda t| aW Y d } ~ n
d } ~ 0 0 d S )Nr   F)pyogrior   r   pyogrio_import_errorr   r   r   r   _import_pyogrioC   s    r    c                 C   s    t d u rtd|  dt d S )Nthe zr requires the 'fiona' package, but it is not installed or does not import correctly.
Importing fiona resulted in: )r   r   r   funcr   r   r   _check_fionaO   s    r$   c                 C   s   t d u rtd|  dd S )Nr!   z requires the 'pyogrio' package, but it is not installed or does not import correctly.
Importing pyogrio resulted in: {pyogrio_import_error})r   r   r"   r   r   r   _check_pyogrioW   s    
r%   c                 C   s   | d u rdd l }|jj} | d u r>t  tr0d} nt  tr>d} | dkrVt  t| n:| dkrnt  t| n"| d u rt	d| dt
 dt | S )Nr   r   r   zThe zx requires the 'pyogrio' or 'fiona' package, but neither is installed or imports correctly.
Importing fiona resulted in: z 
Importing pyogrio resulted in: )	geopandasoptionsZ	io_enginer   r   r    r   r$   r%   r   r   r   )enginer#   r&   r   r   r   _check_engine`   s2    

r)   ZBNAZDXFZCSVESRI ShapefileZGeoJSONZ
GeoJSONSeqZGPKGZGMLZGPXZGPSTrackMakerzMapInfo FileZDGNZ
FlatGeobuf)z.bnaz.dxfz.csvz.shpz.dbfz.jsonz.geojsonz	.geojsonlz	.geojsonsz.gpkgz.gmlz.xmlz.gpxz.gtmz.gtzz.tabz.mifz.midz.dgnz.fgbc                 C   s.   t | trtj| } nt | tr*|  } | S )zExpand paths that use ~.)
isinstancer   ospath
expanduserr   r-   r   r   r   _expand_user   s
    

r0   c                 C   s*   zt | jtv W S  ty$   Y dS 0 dS )z+Check to see if *url* has a valid protocol.FN)	parse_urlscheme_VALID_URLS	Exception)urlr   r   r   _is_url   s    r6   c                 C   s,   t jj| }|jr |jdS |jdS )z"Check if a given path is a zipfilez.zip)r   r-   
ParsedPathZfrom_uriarchiveendswith)r-   parsedr   r   r   _is_zip   s
    
r;   c           
      K   s   t |d}t| } d}t| rftj| ,}|jddksH| } d}W d   n1 s\0    Y  |dkrt	| f|||d|S |d	krt
jj| r|  }t|tr|d
n|}	d}n| }	t|	|f|||d|S td| ddS )a  
    Returns a GeoDataFrame from a file or URL.

    .. note::

        GeoPandas currently defaults to use Fiona as the engine in ``read_file``.
        However, GeoPandas 1.0 will switch to use pyogrio as the default engine, since
        pyogrio can provide a significant speedup compared to Fiona. We recommend to
        already install pyogrio and specify the engine by using the ``engine`` keyword
        (``geopandas.read_file(..., engine="pyogrio")``), or by setting the default for
        the ``engine`` keyword globally with::

            geopandas.options.io_engine = "pyogrio"

    Parameters
    ----------
    filename : str, path object or file-like object
        Either the absolute or relative path to the file or URL to
        be opened, or any object with a read() method (such as an open file
        or StringIO)
    bbox : tuple | GeoDataFrame or GeoSeries | shapely Geometry, default None
        Filter features by given bounding box, GeoSeries, GeoDataFrame or a shapely
        geometry. With engine="fiona", CRS mis-matches are resolved if given a GeoSeries
        or GeoDataFrame. With engine="pyogrio", bbox must be in the same CRS as the
        dataset. Tuple is (minx, miny, maxx, maxy) to match the bounds property of
        shapely geometry objects. Cannot be used with mask.
    mask : dict | GeoDataFrame or GeoSeries | shapely Geometry, default None
        Filter for features that intersect with the given dict-like geojson
        geometry, GeoSeries, GeoDataFrame or shapely geometry.
        CRS mis-matches are resolved if given a GeoSeries or GeoDataFrame.
        Cannot be used with bbox.
    rows : int or slice, default None
        Load in specific rows by passing an integer (first `n` rows) or a
        slice() object.
    engine : str, "fiona" or "pyogrio"
        The underlying library that is used to read the file. Currently, the
        supported options are "fiona" and "pyogrio". Defaults to "fiona" if
        installed, otherwise tries "pyogrio".
    **kwargs :
        Keyword args to be passed to the engine. In case of the "fiona" engine,
        the keyword arguments are passed to :func:`fiona.open` or
        :class:`fiona.collection.BytesCollection` when opening the file.
        For more information on possible keywords, type:
        ``import fiona; help(fiona.open)``. In case of the "pyogrio" engine,
        the keyword arguments are passed to :func:`pyogrio.read_dataframe`.


    Examples
    --------
    >>> df = geopandas.read_file("nybb.shp")  # doctest: +SKIP

    Specifying layer of GPKG:

    >>> df = geopandas.read_file("file.gpkg", layer='cities')  # doctest: +SKIP

    Reading only first 10 rows:

    >>> df = geopandas.read_file("nybb.shp", rows=10)  # doctest: +SKIP

    Reading only geometries intersecting ``mask``:

    >>> df = geopandas.read_file("nybb.shp", mask=polygon)  # doctest: +SKIP

    Reading only geometries intersecting ``bbox``:

    >>> df = geopandas.read_file("nybb.shp", bbox=(0, 0, 10, 20))  # doctest: +SKIP

    Returns
    -------
    :obj:`geopandas.GeoDataFrame` or :obj:`pandas.DataFrame` :
        If `ignore_geometry=True` a :obj:`pandas.DataFrame` will be returned.

    Notes
    -----
    The format drivers will attempt to detect the encoding of your data, but
    may fail. In this case, the proper encoding can be specified explicitly
    by using the encoding keyword parameter, e.g. ``encoding='utf-8'``.

    When specifying a URL, geopandas will check if the server supports reading
    partial data and in that case pass the URL as is to the underlying engine,
    which will then use the network file system handler of GDAL to read from
    the URL. Otherwise geopandas will download the data from the URL and pass
    all data in-memory to the underlying engine.
    If you need more control over how the URL is read, you can specify the
    GDAL virtual filesystem manually (e.g. ``/vsicurl/https://...``). See the
    GDAL documentation on filesystems for more details
    (https://gdal.org/user/virtual_file_systems.html#vsicurl-http-https-ftp-files-random-access).

    z'read_file' functionFzAccept-RangesbytesTNr   )bboxmaskrowsr   zutf-8unknown engine '')r)   r0   r6   urllibrequesturlopenheadersgetread_read_file_pyogriopdapitypesZis_file_liker+   r   encode_read_file_fiona
ValueError)
filenamer=   r>   r?   r(   kwargs
from_bytesresponsedatapath_or_bytesr   r   r   
_read_file   s0    Z
"rU   c                 K   sp  |d urt std|stt| rtt| }t|tjjrr|j	pHd
d}d|vrjddg| |_	|j} n&t|tjjrt| dsd|j } |rtj}	ntj}	t  |	| fi |t}
|
j}z|
jjdd}|d ur|}W n< ty(   z|
jd	 }W n ttfy"   Y n0 Y n0 |d ur|t|ttfrVt||j}nt|trh|j}t|d
ksJ n6t|ttfrt ||j!}nt|trt |}i }|d ur||d< |d ur||d< |d ur||d< |d ur>t|t"rt#|}nt|t#s td|
j$|j%|j&|j'fi |}n|rV|
j$f i |}n|
}t(|
j)d }dd |
j)d * D }|+ddrt,j-dd |D |d}ntj.|||dg d}|D ]V}t,j/|| dd}|j0dkrt,j/|| ddd}|j0dks|j1j2dd||< q|W  d    W  d    S 1 sB0    Y  W d    n1 sb0    Y  d S )Nzwhere requires fiona 1.9+r   +zipz/vsizzip://d   )Zconfidence_thresholdinit   r=   r>   where%'rows' must be an integer or a slice.
propertiesc                 S   s   g | ]\}}|d kr|qS )datetimer   ).0kvr   r   r   
<listcomp>  s   z$_read_file_fiona.<locals>.<listcomp>ignore_geometryFc                 S   s   g | ]}|d  qS )r]   r   )r_   recordr   r   r   rb         )columnsgeometry)crsrf   ignore)errorsobjectT)rj   utcms)freq)3r   NotImplementedErrorr;   r   r   Z
parse_pathr+   r-   r7   r2   splitjoinnameZUnparsedPath
startswithZBytesCollectionopenr   crs_wktrh   Zto_epsgAttributeError	TypeErrorKeyErrorr   r   tupleZto_crstotal_boundsr   boundslenr   Zunary_unionintslicefilterstartstopsteplistschemaitemsrF   rI   Z	DataFrameZfrom_featuresto_datetimedtypedtround)rT   rQ   r=   r>   r?   r[   rP   r:   schemesreaderfeaturesrh   ZepsgfiltersZf_filtrf   Zdatetime_fieldsdfr`   Zas_dtr   r   r   rM   1  s    







rM   c                 K   s   dd l }|d ur|t|tr$||d< nXt|trt|jd urB|j|d< |jd ur`|j|jpXd |d< |jd ur|tdntd|d urt|t	t
frt|j}nt|tr|j}t|dkrtd|d urtd|d	d
rd
|d< |j| fd|i|S )Nr   Zmax_featuresZskip_featuresz slice with step is not supportedr\   rZ   z"'bbox' should be a length-4 tuple.zZThe 'mask' keyword is not supported with the 'pyogrio' engine. You can use 'bbox' instead.rc   FZread_geometryr=   )r   r+   r}   r~   r   r   r   rN   rw   r   r   ry   rz   r   r{   r|   popZread_dataframe)rT   r=   r>   r?   rP   r   r   r   r   rH     s4    








rH   c                  O   s   t jdtdd t| i |S )Nz{geopandas.io.file.read_file() is intended for internal use only, and will be deprecated. Use geopandas.read_file() instead.   
stacklevel)warningswarnFutureWarningrU   argsrP   r   r   r   	read_file  s    r   c                  O   s   t jdtdd t| i |S )Nzgeopandas.io.file.to_file() is intended for internal use only, and will be deprecated. Use GeoDataFrame.to_file() or GeoSeries.to_file() instead.r   r   )r   r   r   _to_filer   r   r   r   to_file  s    r   c                 C   sL   z
| j } W n ty   Y n0 ztt| j  W S  tyF   Y dS 0 dS )z>
    Attempt to auto-detect driver based on the extension
    r*   N)rr   rv   _EXTENSION_TO_DRIVERr   suffixlowerrx   r/   r   r   r   _detect_driver  s    
r   wc           	      K   s  t |d}t|}|du r:t| jjdgkp8t| jj }|rJ| jdd} |du rZt|}|dkrt	dd | j
 D rtjdd	d
 | jdk dkrtd|dvrtd| d|dkrt| |||||fi | n6|dkrt| |||||fi | ntd| ddS )a  
    Write this GeoDataFrame to an OGR data source

    A dictionary of supported OGR providers is available via:
    >>> import fiona
    >>> fiona.supported_drivers  # doctest: +SKIP

    .. note::

        GeoPandas currently defaults to use Fiona as the engine in ``to_file``.
        However, GeoPandas 1.0 will switch to use pyogrio as the default engine, since
        pyogrio can provide a significant speedup compared to Fiona. We recommend to
        already install pyogrio and specify the engine by using the ``engine`` keyword
        (``df.to_file(..., engine="pyogrio")``), or by setting the default for
        the ``engine`` keyword globally with::

            geopandas.options.io_engine = "pyogrio"

    Parameters
    ----------
    df : GeoDataFrame to be written
    filename : string
        File path or file handle to write to. The path may specify a
        GDAL VSI scheme.
    driver : string, default None
        The OGR format driver used to write the vector file.
        If not specified, it attempts to infer it from the file extension.
        If no extension is specified, it saves ESRI Shapefile to a folder.
    schema : dict, default None
        If specified, the schema dictionary is passed to Fiona to
        better control how the file is written. If None, GeoPandas
        will determine the schema based on each column's dtype.
        Not supported for the "pyogrio" engine.
    index : bool, default None
        If True, write index into one or more columns (for MultiIndex).
        Default None writes the index into one or more columns only if
        the index is named, is a MultiIndex, or has a non-integer data
        type. If False, no index is written.

        .. versionadded:: 0.7
            Previously the index was not written.
    mode : string, default 'w'
        The write mode, 'w' to overwrite the existing file and 'a' to append;
        when using the pyogrio engine, you can also pass ``append=True``.
        Not all drivers support appending. For the fiona engine, the drivers
        that support appending are listed in fiona.supported_drivers or
        https://github.com/Toblerity/Fiona/blob/master/fiona/drvsupport.py.
        For the pyogrio engine, you should be able to use any driver that
        is available in your installation of GDAL that supports append
        capability; see the specific driver entry at
        https://gdal.org/drivers/vector/index.html for more information.
    crs : pyproj.CRS, default None
        If specified, the CRS is passed to Fiona to
        better control how the file is written. If None, GeoPandas
        will determine the crs based on crs df attribute.
        The value can be anything accepted
        by :meth:`pyproj.CRS.from_user_input() <pyproj.crs.CRS.from_user_input>`,
        such as an authority string (eg "EPSG:4326") or a WKT string.
    engine : str, "fiona" or "pyogrio"
        The underlying library that is used to write the file. Currently, the
        supported options are "fiona" and "pyogrio". Defaults to "fiona" if
        installed, otherwise tries "pyogrio".
    **kwargs :
        Keyword args to be passed to the engine, and can be used to write
        to multi-layer data, store data within archives (zip files), etc.
        In case of the "fiona" engine, the keyword arguments are passed to
        fiona.open`. For more information on possible keywords, type:
        ``import fiona; help(fiona.open)``. In case of the "pyogrio" engine,
        the keyword arguments are passed to `pyogrio.write_dataframe`.

    Notes
    -----
    The format drivers will attempt to detect the encoding of your data, but
    may fail. In this case, the proper encoding can be specified explicitly
    by using the encoding keyword parameter, e.g. ``encoding='utf-8'``.
    z'to_file' methodNF)Zdropr*   c                 s   s   | ]}t |d kV  qdS )
   N)r|   )r_   cr   r   r   	<genexpr>L  re   z_to_file.<locals>.<genexpr>zVColumn names longer than 10 characters will be truncated when saved to ESRI Shapefile.   r   rg      a*  GeoDataFrame contains multiple geometry columns but GeoDataFrame.to_file supports only a single geometry column. Use a GeoDataFrame.to_parquet or GeoDataFrame.to_feather, drop additional geometry columns or convert them to a supported format like a well-known text (WKT) using `GeoSeries.to_wkt()`.)r   az)'mode' should be one of 'w' or 'a', got 'z	' insteadr   r   r@   rA   )r)   r0   r   indexnamesr   r   Zreset_indexr   anyrf   tolistr   r   dtypessumrN   _to_file_fiona_to_file_pyogrio)	r   rO   driverr   r   moderh   r(   rP   r   r   r   r     s0    W
  
r   c           
   	   K   s   |d u rt | }|r"tj|}n| j}t  d }ztj }W n t	yX   d}Y n0 t
|t
dkrx|rx| }n|r|d}tj|f||||d|}	|	|   W d    n1 s0    Y  W d    n1 s0    Y  d S )Nz2.0.0z3.0.0Z	WKT1_GDAL)r   r   ru   r   )infer_schemapyprojZCRSZfrom_user_inputrh   r   r   envZget_gdal_release_namerv   r   Zto_wktrt   ZwriterecordsZiterfeatures)
r   rO   r   r   rh   r   rP   ru   Zgdal_versionZcolxnr   r   r   r   g  s0    


r   c                 K   sd   dd l }|d urtd|dkr(d|d< |d ur8td| jjsHtd|j| |fd|i| d S )	Nr   zAThe 'schema' argument is not supported with the 'pyogrio' engine.r   Tappendz9Passing 'crs' it not supported with the 'pyogrio' engine.z4GeoDataFrame cannot contain duplicated column names.r   )r   rN   rf   Z	is_uniqueZwrite_dataframe)r   rO   r   r   rh   r   rP   r   r   r   r   r     s    r   c                    sv   ddl m} ddddddfdd	 | fd
dtjjD }jr`tjdtdd t	}||d}|S )Nr   )OrderedDictint32r}   r   bool)ZInt32r   ZInt64stringbooleanc                    s\   |t krdS |jdrdS t| v r6 t| }nttd| j}|dkrXd}|S )Nr   Z
datetime64r^   r   longr}   )	rk   rr   rs   r   typenpZzerositem__name__)columnZin_typeZout_type)rK   r   r   convert_type  s    z"infer_schema.<locals>.convert_typec                    s(   g | ] \}}|j kr| ||fqS r   )Z_geometry_column_name)r_   col_type)r   r   r   r   rb     s   
z infer_schema.<locals>.<listcomp>zbYou are attempting to write an empty DataFrame to file. For some drivers, this operation may fail.r   r   )rg   r]   )
collectionsr   rW   rf   r   emptyr   r   UserWarning_geometry_types)r   r   r]   
geom_typesr   r   )r   r   rK   r   r     s,    	
r   c                 C   sv   | | j j  j j }dd |D }| | j j j j }dd |D }|| }t|dkr^dS t|dkrr|d }|S )zJ
    Determine the geometry types in the GeoDataFrame for the schema.
    c                 S   s   g | ]}|d ur|qS )Nr   r_   gtyper   r   r   rb     re   z#_geometry_types.<locals>.<listcomp>c                 S   s   g | ]}|d urd| qS )Nz3D r   r   r   r   r   rb     re   r   Unknownr   )rg   Zhas_zZ	geom_typeuniquer|   )r   Zgeom_types_2DZgeom_types_3Dr   r   r   r   r     s    r   )NNNN)NNNN)NNN)NNNr   NN)9r,   Zpackaging.versionr   pathlibr   r   numpyr   ZpandasrI   Zpandas.api.typesr   r   Zshapely.geometryr   Zshapely.geometry.baser   r&   r   r   urllib.parser	   r1   r
   r   r   Zurllib.requestrB   setr3   discardr   r   r   r   r   r   r   r    r$   r%   r)   r   r0   r6   r;   rU   rM   rH   r   r   r   r   r   r   r   r   r   r   r   r   <module>   s   

	#	

} 
k
"      
 3