U
    Cvfq4                     @  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 d dlmZ d dlmZ d dlmZ e Zd	ZG d
d deZdd ZdddZdS )    )annotationsN)BackendArray)CachingFileManager)SerializableLock)indexing)	DataArray)	is_scalarz~The kind of indexing operation you are trying to do is not valid on rasterio files. Try to load your data with ds.load()first.c                   @  sP   e Zd ZdZdddZedd Zeddd	d
Zdd Zdd Z	dd Z
dS )RasterioArrayWrapperz)A wrapper around rasterio dataset objectsNc                 C  s   ddl m} || _|| _| }|d k	r4||f|}|| _|j|j|jf| _	|j
}tt||d ksrtdt|d | _d S )Nr   	WarpedVRTz$All bands should have the same dtype)rasterio.vrtr   managerlockacquire
vrt_paramscountheightwidth_shapedtypesnpallasarray
ValueErrordtype_dtype)selfr   r   r   r   riodsr    r   =/tmp/pip-unpacked-wheel-h316xyqg/xarray/backends/rasterio_.py__init__   s    zRasterioArrayWrapper.__init__c                 C  s   | j S N)r   r   r   r   r   r   .   s    zRasterioArrayWrapper.dtypeztuple[int, ...])returnc                 C  s   | j S r!   )r   r"   r   r   r   shape2   s    zRasterioArrayWrapper.shapec                 C  s  t |dkstd|d }g }t|trN|| jd \}}}t|||}t|d 	 }t|t
rx|td g }g }tt|dd | jdd D ]\}	\}
}t|
tr|
|\}}}|tdd| nPt|
r|d|	   |
}|
d }n(t|
t|
d  }}||
|  |||f qt|d tjrxt|d tjrxtj|dd  |dd< |t|t|t|fS )a  Get indexer for rasterio array.

        Parameters
        ----------
        key : tuple of int

        Returns
        -------
        band_key: an indexer for the 1st dimension
        window: two tuples. Each consists of (start, stop).
        squeeze_axis: axes to be squeezed
        np_ind: indexer for loaded numpy array

        See Also
        --------
        indexing.decompose_indexer
           z%rasterio datasets should always be 3Dr      N   )lenAssertionError
isinstancesliceindicesr$   r   aranger   tolistlistappend	enumeratezipr   minmaxndarrayZix_tuple)r   keyband_keynp_indsstartstopstepwindowsqueeze_axisiknr   r   r   _get_indexer6   s2    

,


$z!RasterioArrayWrapper._get_indexerc           
   	   C  s   ddl m} | |\}}}}|r4tdd |D rbt|ftdd |D  }tj|| jd}nF| j	: | j
jdd}	| jd k	r||	f| j}	|	j||d	}W 5 Q R X |rtj||d
}|| S )Nr   r
   c                 s  s   | ]\}}||kV  qd S r!   r   .0r;   r<   r   r   r   	<genexpr>t   s     z0RasterioArrayWrapper._getitem.<locals>.<genexpr>c                 s  s   | ]\}}|| V  qd S r!   r   rD   r   r   r   rF   v   s     )r   F)Z
needs_lock)r>   )Zaxis)r   r   rC   anyr)   r7   r   zerosr   r   r   r   r   readZsqueeze)
r   r8   r   r9   r>   r?   r:   r$   outr   r   r   r   _getitemo   s    
zRasterioArrayWrapper._getitemc                 C  s   t || jt jj| jS r!   )r   Zexplicit_indexing_adapterr$   ZIndexingSupportZOUTERrK   )r   r8   r   r   r   __getitem__   s       z RasterioArrayWrapper.__getitem__)N)__name__
__module____qualname____doc__r    propertyr   r$   rC   rK   rL   r   r   r   r   r	      s   

9r	   c                   s6   dd }dd  ||d fdd|   D }|S )a  Parse ENVI metadata into Python data structures.

    See the link for information on the ENVI header file format:
    http://www.harrisgeospatial.com/docs/enviheaderfiles.html

    Parameters
    ----------
    meta : dict
        Dictionary of keys and str values to parse, as returned by the rasterio
        tags(ns='ENVI') call.

    Returns
    -------
    parsed_meta : dict
        Dictionary containing the original keys and the parsed values

    c                 S  s   t j| ddddS )N{}float,)r   sep)r   
fromstringstripsr   r   r   parsevec   s    z_parse_envi.<locals>.parsevecc                 S  s
   |  dS )NrR   )rW   rX   r   r   r   default   s    z_parse_envi.<locals>.default)Z
wavelengthZfwhmc                   s"   i | ]\}}| | |qS r   )get)rE   rA   vr[   parser   r   
<dictcomp>   s      z_parse_envi.<locals>.<dictcomp>)items)metarZ   Zparsed_metar   r^   r   _parse_envi   s
    
rc   c                 K  sR  t jdtdd ddl}ddlm} d}t| |jjr>| j	} nZt| |j
jr| }	|	jj	} t|	j |	j |	j|	j|	j|	j|	j|	j|	j|	j|	j|	jd}|dkrt}t|j| |d|d	}
|
 }|dk	r||f|}|dkr|dk}i }|jd
k rtdt !|j"|d< |jj#r|dkr"dn|}|r|j|j }}|jt $|d t %|d f \}}|jt %|d t $|d f \}}||d< ||d< n(|dkrdn|}|rt jdt&dd i }t'|jdd |d< t(|dr&|jr&z|j) |d< W n$ t*k
r$   |j |d< Y nX t(|dr<|j+|d< t(|drXt ,|j-|d< t(|dr|t'dd |j.D |d< t(|dr|j/|d< t(|dr|j0|d< t(|drt1|j2r|j2|d< t(|drt1|j3r|j3|d< t4d d! d"}|j5}||kr|d#kr&|| |6 }n|| |j6|d$}|7 D ]H\}}t|t8t j9frt:||jkrdt !|f||< n|||< qBt;<t=|
||}t;>|}|r|dkrt;?|}t@|d%||d&}|dk	rBdd'lAmB} ztCjDEtCjDF| }W n tGk
r   d}Y nX || ||}d(| }|jH|||d)}|I|
jJ |S )*a8  Open a file with rasterio.

    .. deprecated:: 0.20.0

        Deprecated in favor of rioxarray.
        For information about transitioning, see:
        https://corteva.github.io/rioxarray/stable/getting_started/getting_started.html

    This should work with any file that rasterio can open (most often:
    geoTIFF). The x and y coordinates are generated automatically from the
    file's geoinformation, shifted to the center of each pixel (see
    `"PixelIsArea" Raster Space
    <http://web.archive.org/web/20160326194152/http://remotesensing.org/geotiff/spec/geotiff2.5.html#2.5.2>`_
    for more information).

    Parameters
    ----------
    filename : str, rasterio.DatasetReader, or rasterio.WarpedVRT
        Path to the file to open. Or already open rasterio dataset.
    parse_coordinates : bool, optional
        Whether to parse the x and y coordinates out of the file's
        ``transform`` attribute or not. The default is to automatically
        parse the coordinates only if they are rectilinear (1D).
        It can be useful to set ``parse_coordinates=False``
        if your files are very large or if you don't need the coordinates.
    chunks : int, tuple or dict, optional
        Chunk sizes along each dimension, e.g., ``5``, ``(5, 5)`` or
        ``{'x': 5, 'y': 5}``. If chunks is provided, it used to load the new
        DataArray into a dask array.
    cache : bool, optional
        If True, cache data loaded from the underlying datastore in memory as
        NumPy arrays when accessed to avoid reading from the underlying data-
        store multiple times. Defaults to True unless you specify the `chunks`
        argument to use dask, in which case it defaults to False.
    lock : False, True or threading.Lock, optional
        If chunks is provided, this argument is passed on to
        :py:func:`dask.array.from_array`. By default, a global lock is
        used to avoid issues with concurrent access to the same file when using
        dask's multithreaded backend.

    Returns
    -------
    data : DataArray
        The newly created DataArray.
    zopen_rasterio is Deprecated in favor of rioxarray. For information about transitioning, see: https://corteva.github.io/rioxarray/stable/getting_started/getting_started.htmlr'   )
stacklevelr   Nr
   )src_crscrs
resampling	tolerance
src_nodatanodatar   r   src_transform	transformr   warp_extrasr)r   modekwargsr&   zUnknown dimsbandTg      ?yxFzThe file coordinates' transformation isn't rectilinear: xarray won't parse the coordinates in this case. Set `parse_coordinates=False` to suppress this warning.r%      rl   rf   resis_tiled
nodatavalsc                 s  s    | ]}|d krt jn|V  qd S r!   )r   nan)rE   Z	nodatavalr   r   r   rF   D  s    z open_rasterio.<locals>.<genexpr>scalesoffsetsdescriptionsunitsc                 S  s   | S r!   r   )mr   r   r   <lambda>U      zopen_rasterio.<locals>.<lambda>)ZENVIGTiffr   )ns)rq   rr   rs   )dataZdimscoordsattrs)tokenizezopen_rasterio-)name_prefixtoken)KwarningswarnDeprecationWarningrasterior   r   r+   ioZDatasetReadernamevrtZsrc_datasetdictre   Z	to_stringrf   rg   rh   ri   rj   r   r   rk   rl   Zworking_dtyperm   RASTERIO_LOCKr   openr   r   r   r   r   ZindexesZis_rectilinearr.   rH   RuntimeWarningr7   hasattrZto_proj4AttributeErrorru   Zuint8rv   rw   ry   rz   rG   r{   r|   rc   drivertagsra   r0   r6   r)   r   ZLazilyIndexedArrayr	   ZCopyOnWriteArrayZMemoryCachedArrayr   Z	dask.baser   ospathgetmtime
expanduserOSErrorchunkZ	set_closeclose)filenameZparse_coordinateschunkscacher   rp   r   r   r   r   r   r   r   r_   Znxnyrs   _rr   r   parsersr   rb   rA   r]   r   resultr   mtimer   r   r   r   r   open_rasterio   s    5

&&








"




r   )NNNN)
__future__r   r   r   Znumpyr   Zxarray.backends.commonr   Zxarray.backends.file_managerr   Zxarray.backends.locksr   Zxarray.corer   Zxarray.core.dataarrayr   Zxarray.core.utilsr   r   Z
_ERROR_MSGr	   rc   r   r   r   r   r   <module>   s&   p     