
    EhV                     D   S r SSKJrJrJr  SSKrSSKrSSKrSSK	r	SSK
r
SSKrSSKrSSKrSSKrSSKrSSKrSSKJrJr  SSKJr  SSKJrJr  SSKJr  SSKJr  SS	KJ r   SS
K!J"r"  SSK#J$r$  SSK%J&r&  / SQr'S\RP                  " 5       RR                  -   r*\RV                  " 5       r,\" \,SS9r-S r.S r/\	R`                  " \/5               S"S jr1        S#S jr2S r3S r4S\"Rj                  4S jr6\"Rj                  4S jr7S r8S r9S$S jr:S r;S r<S r=S%S  jr>S! r?g)&z1Tools for downloading map tiles from coordinates.    )absolute_importdivisionprint_functionN)ImageUnidentifiedImageError)Memory)Paralleldelayed)from_origin)
MemoryFile)	WarpedVRT)
Resampling   )	providers)TileProvider)bounds2raster
bounds2img
warp_tileswarp_img_transformhowmanyset_cache_dirzcontextily-)verbosec                 .    U [         R                  l        g)a  
Set a cache directory to use in the current python session.

By default, contextily caches downloaded tiles per python session, but
will afterwards delete the cache directory. By setting it to a custom
path, you can avoid this, and re-use the same cache a next time by
again setting the cache dir to that directory.

Parameters
----------
path : str
    Path to the cache directory.
N)memorystore_backendlocation)paths    bC:\Users\julio\OneDrive\Documentos\Trabajo\Ideas Frescas\venv\Lib\site-packages\contextily/tile.pyr   r   ,   s     %)F!    c                  6    [         R                  " [        SS9  g )NT)ignore_errors)shutilrmtreetmpdir r   r   _clear_cacher&   =   s    
MM&-r   c                    U(       d  [        X5      u  p[        X#5      u  p#[        U UUUUUSU
US9	u  pUR                  u  pnUu  nnnn[        R                  " UUU 5      n[        R                  " UUU5      nUS   US   -
  U -  nUS   US   -
  U-  n[        US   US-  -
  US   US-  -   UU5      n[        R                  " USSUU U[        UR                  R                  5      SUS	9	 n[        U5       H"  nUR                  US
S
2S
S
2U4   US-   5        M$     S
S
S
5        X4$ ! , (       d  f       X4$ = f)a  
Take bounding box and zoom, and write tiles into a raster file in
the Spherical Mercator CRS (EPSG:3857)

Parameters
----------
w : float
    West edge
s : float
    South edge
e : float
    East edge
n : float
    North edge
zoom : int
    Level of detail
path : str
    Path to raster file to be written
source : xyzservices.TileProvider object or str
    [Optional. Default: OpenStreetMap Humanitarian web tiles]
    The tile source: web tile provider or path to local file. The web tile
    provider can be in the form of a :class:`xyzservices.TileProvider` object or a
    URL. The placeholders for the XYZ in the URL need to be `{x}`, `{y}`,
    `{z}`, respectively. For local file paths, the file is read with
    `rasterio` and all bands are loaded into the basemap.
    IMPORTANT: tiles are assumed to be in the Spherical Mercator
    projection (EPSG:3857), unless the `crs` keyword is specified.
ll : Boolean
    [Optional. Default: False] If True, `w`, `s`, `e`, `n` are
    assumed to be lon/lat as opposed to Spherical Mercator.
wait : int
    [Optional. Default: 0]
    if the tile API is rate-limited, the number of seconds to wait
    between a failed request and the next try
max_retries: int
    [Optional. Default: 2]
    total number of rejected requests allowed before contextily
    will stop trying to fetch more tiles from a rate-limited API.
n_connections: int
    [Optional. Default: 1]
    Number of connections for downloading tiles in parallel. Be careful not to overload the tile server and to check
    the tile provider's terms of use before increasing this value. E.g., OpenStreetMap has a max. value of 2
    (https://operations.osmfoundation.org/policies/tiles/). If allowed to download in parallel, a recommended
    value for n_connections is 16, and should never be larger than 64.
use_cache: bool
    [Optional. Default: True]
    If False, caching of the downloaded tiles will be disabled. This can be useful in resource constrained
    environments, especially when using n_connections > 1, or when a tile provider's terms of use don't allow
    caching.

Returns
-------
img : ndarray
    Image as a 3D array of RGB values
extent : tuple
    Bounding box [minX, maxX, minY, maxY] of the returned image
T)zoomsourcelln_connections	use_cacher      wGTiffz	epsg:3857driverheightwidthcountdtypecrs	transformNr   )_sm2llr   shapenplinspacer   rioopenstrr6   namerangewrite)r/   senr   r(   r)   r*   waitmax_retriesr+   r,   ZexthbminXmaxXminYmaxYxyresXresYr8   rasterbands                              r   r   r   D   s`   N a|a|				#
FA ggGA! D$d
D$"A
D$"AbEAaDLADbEAaDLADAaD4!8OQrUTAX-=tTJI	!'',,

 
!HDLL1a:q1 

 6M

 

 6Ms   02D--
D=c           	        ^^^ U(       d  [        X5      u  p[        X#5      u  p#[        U5      nUS:H  nU(       a  [        XX#5      nU(       a  XK-  n[        XLUS9n[	        [
        R                  " XX#U/5      5      nU Vs/ s H1  oR                  UR                  UR                  UR                  S9PM3     nnU	S:  d  [        U	[        5      (       d  [        S5      eU	S:X  d  U
(       d  SOSnU
(       a  [        R                  [         5      O[         m[#        U	US9" UUU4S	 jU 5       5      n[%        UU5      u  nnUu  nnnn[
        R&                  " UU5      u  nn[
        R&                  " UU5      u  nnUUUU4nUU4$ s  snf )
a	  
Take bounding box and zoom and return an image with all the tiles
that compose the map and its Spherical Mercator extent.

Parameters
----------
w : float
    West edge
s : float
    South edge
e : float
    East edge
n : float
    North edge
zoom : int
    Level of detail
source : xyzservices.TileProvider object or str
    [Optional. Default: OpenStreetMap Humanitarian web tiles]
    The tile source: web tile provider or path to local file. The web tile
    provider can be in the form of a :class:`xyzservices.TileProvider` object or a
    URL. The placeholders for the XYZ in the URL need to be `{x}`, `{y}`,
    `{z}`, respectively. For local file paths, the file is read with
    `rasterio` and all bands are loaded into the basemap.
    IMPORTANT: tiles are assumed to be in the Spherical Mercator
    projection (EPSG:3857), unless the `crs` keyword is specified.
ll : Boolean
    [Optional. Default: False] If True, `w`, `s`, `e`, `n` are
    assumed to be lon/lat as opposed to Spherical Mercator.
wait : int
    [Optional. Default: 0]
    if the tile API is rate-limited, the number of seconds to wait
    between a failed request and the next try
max_retries: int
    [Optional. Default: 2]
    total number of rejected requests allowed before contextily
    will stop trying to fetch more tiles from a rate-limited API.
n_connections: int
    [Optional. Default: 1]
    Number of connections for downloading tiles in parallel. Be careful not to overload the tile server and to check
    the tile provider's terms of use before increasing this value. E.g., OpenStreetMap has a max. value of 2
    (https://operations.osmfoundation.org/policies/tiles/). If allowed to download in parallel, a recommended
    value for n_connections is 16, and should never be larger than 64.
use_cache: bool
    [Optional. Default: True]
    If False, caching of the downloaded tiles will be disabled. This can be useful in resource constrained
    environments, especially when using n_connections > 1, or when a tile provider's terms of use don't allow
    caching.
zoom_adjust : int or None
    [Optional. Default: None]
    The amount to adjust a chosen zoom level if it is chosen automatically.
    Values outside of -1 to 1 are not recommended as they can lead to slow execution.

Returns
-------
img : ndarray
    Image as a 3D array of RGB values
extent : tuple
    Bounding box [minX, maxX, minY, maxY] of the returned image
auto)rW   )rP   rQ   zr   z/n_connections must be a positive integer value.threads	processes)n_jobspreferc              3   J   >#    U  H  n[        T5      " UTT5      v   M     g 7fN)r
   ).0tile_urlfetch_tile_fnrG   rF   s     r   	<genexpr>bounds2img.<locals>.<genexpr>  s&      FLUx{;;Is    #)r9   _process_source_calculate_zoom_validate_zoomlistmttiles	build_urlrP   rQ   rX   
isinstanceint
ValueErrorr   cache_fetch_tiler	   _merge_tilesxy)r/   rC   rD   rE   r(   r)   r*   rF   rG   r+   r,   zoom_adjustprovider	auto_zoomri   tile	tile_urlspreferred_backendarraysmergedextentwestsoutheastnorthleftbottomrighttopra   s          ``                    @r   r   r      ss   R a|a| v&HIqQ*$y9D!tf-.ENSTed##dff$&&#AeITq
=# > >JLL
 $q(		  2;FLL-M]3DE FLUF F "%0NFF%D%u55u%LD&tU#JE35&#%F6>+ Us   8F
c                     U c  [         R                  R                  nU$ [        U [        5      (       a  [        U SSS9nU$ [        U [        5      (       d  [        S5      eSU ;  a  [        S5      eU nU$ )N url)r   attributionr@   zAThe 'url' needs to be a xyzservices.TileProvider object or stringz2The 'url' dict should at least contain a 'url' key)	r   OpenStreetMapHOTrk   r?   r   dict	TypeErrorrm   )r)   rs   s     r   rd   rd   (  s    ~**.. O 
FC	 	 FG O %%O
 	
 
f	MNNOr   c                     [        XU5      nU$ r^   )_retryer)r`   rF   rG   arrays       r   ro   ro   8  s    X[1ELr   z	EPSG:4326c                    U R                   u  pEnUu  pxp[        R                  " XxU5      n[        R                  " XU5      nUS   US   -
  U-  nUS   US   -
  U-  n[        US   US-  -
  US   US-  -   X5      n[	        U R                  SSS5      USX#5      u  nnnUR                  UR                  UR                  UR                  4nUR                  SSS5      U4$ )a  
Reproject (warp) a Web Mercator basemap into any CRS on-the-fly

NOTE: this method works well with contextily's `bounds2img` approach to
      raster dimensions (h, w, b)

Parameters
----------
img : ndarray
    Image as a 3D array (h, w, b) of RGB values (e.g. as
    returned from `contextily.bounds2img`)
extent : tuple
    Bounding box [minX, maxX, minY, maxY] of the returned image,
    expressed in Web Mercator (`EPSG:3857`)
t_crs : str/CRS
    [Optional. Default='EPSG:4326'] Target CRS, expressed in any
    format permitted by rasterio. Defaults to WGS84 (lon/lat)
resampling : <enum 'Resampling'>
    [Optional. Default=Resampling.bilinear] Resampling method for
    executing warping, expressed as a `rasterio.enums.Resampling`
    method

Returns
-------
img : ndarray
    Image as a 3D array (h, w, b) of RGB values (e.g. as
    returned from `contextily.bounds2img`)
ext : tuple
    Bounding box [minX, maxX, minY, maxY] of the returned (warped)
    image
r-   r   r.   r   z	EPSG:3857)
r:   r;   r<   r   _warper	transposer   r   r   r   )imgrz   t_crs
resamplingrJ   r/   rK   rL   rM   rN   rO   rP   rQ   rR   rS   r8   w_imgbounds_s                      r   r   r   =  s    @ iiGA!#D
D"A
D"AbEAaDLADbEAaDLADAaD4!8OQrUTAX-=tJIaA	;E61 [[&,,vzzAF??1a#V++r   c                 (    [        XX#U5      u  pVnXW4$ )a+  
Reproject (warp) an `img` with a given `transform` and `s_crs` into a
different `t_crs`

NOTE: this method works well with rasterio's `.read()` approach to
raster's dimensions (b, h, w)

Parameters
----------
img : ndarray
    Image as a 3D array (b, h, w) of RGB values (e.g. as
    returned from rasterio's `.read()` method)
transform : affine.Affine
    Transform of the input image as expressed by `rasterio` and
    the `affine` package
s_crs : str/CRS
    Source CRS in which `img` is passed, expressed in any format
    permitted by rasterio.
t_crs : str/CRS
    Target CRS, expressed in any format permitted by rasterio.
resampling : <enum 'Resampling'>
    [Optional. Default=Resampling.bilinear] Resampling method for
    executing warping, expressed as a `rasterio.enums.Resampling`
    method

Returns
-------
w_img : ndarray
    Warped image as a 3D array (b, h, w) of RGB values (e.g. as
    returned from rasterio's `.read()` method)
w_transform : affine.Affine
    Transform of the input image as expressed by `rasterio` and
    the `affine` package
)r   )r   r8   s_crsr   r   r   r   w_transforms           r   r   r   n  s!    F $CE*MEkr   c                    U R                   u  pVn[        5        nUR                  SUUU[        U R                  R
                  5      UUS9 n	U	R                  U 5        SSS5        UR                  5        n	[        XUS9 n
U
R                  5       n U
R                  nU
R                  nSSS5        SSS5        SSS5        U WU4$ ! , (       d  f       No= f! , (       d  f       N4= f! , (       d  f       N== f! , (       d  f       NF= f)zK
Warp an image. Returns the warped image and updated bounds and transform.
r0   r1   N)r7   r   )r:   r   r>   r?   r6   r@   rB   r   readr   r8   )r   r8   r   r   r   rK   rJ   r/   memfilemrastervrtr   s               r   r   r     s     iiGA!	\\ciinn%  
 MM#
 \\^w7*EhhjMM	 F  
$ 	!!#
 
 FE ^ 
sS   3C;CC;7C*)C+C*3C;
C	C;
C'#C**
C8	4C;;
D	c           	          [         R                  " U S[        0S9nUR                  5         [        R
                  " UR                  5       n[        R                  " U5      R                  S5      n[        R                  " U5      nUR                  5         UsSSS5        $ ! , (       d  f       g= f! [         R                  [        4 a    WR                  S:X  a%  [         R                  " SR!                  U 5      5      eUS:  a)  ["        R$                  " U5        US-  n['        XU5      n g[         R                  " S	UR                   S
UR(                   SUR*                   35      ef = f)a	  
Retry a url many times in attempt to get a tile and read the image

Arguments
---------
tile_url : str
    string that is the target of the web request. Should be
    a properly-formatted url for a tile provider.
wait : int
    if the tile API is rate-limited, the number of seconds to wait
    between a failed request and the next try
max_retries : int
    total number of rejected requests allowed before contextily
    will stop trying to fetch more tiles from a rate-limited API.

Returns
-------
array of the tile
z
user-agent)headersRGBANi  z@Tile URL resulted in a 404 error. Double-check your tile url:
{}r   r   z;Connection reset by peer too many times. Last message was: z Error: z
 for url: )requestsget
USER_AGENTraise_for_statusioBytesIOcontentr   r>   convertr;   asarrayclose	HTTPErrorr   status_codeformattimesleepr   reasonr   )r`   rF   rG   requestimage_streamimager   s          r   r   r     s9   (\,,x,
1KL  "ZZ(LJJ|,44V<EJJu%EKKM )((  67 \#%$$228&2B 
 Q

4 q "8;?(( *>>E>Q>Q=R S33:>>2B*W[[M*[ \ \\s2   AB5 AB$	B5 $
B2.B5 2B5 5A<E13>E1c                     U(       d  [        X5      u  p[        X#5      u  p#US:X  a  [        XX#5      n[        [        [        R
                  " XX#U/5      5      5      nU(       a  [        SXG4-  5        U$ )a  
Number of tiles required for a given bounding box and a zoom level

Parameters
----------
w : float
    West edge
s : float
    South edge
e : float
    East edge
n : float
    North edge
zoom : int
    Level of detail
verbose : Boolean
    [Optional. Default=True] If True, print short message with
    number of tiles and zoom.
ll : Boolean
    [Optional. Default: False] If True, `w`, `s`, `e`, `n` are
    assumed to be lon/lat as opposed to Spherical Mercator.
rW   z0Using zoom level %i, this will download %i tiles)r9   re   lenrg   rh   ri   print)r/   rC   rD   rE   r(   r   r*   ri   s           r   r   r     sf    . a|a|v~qQ*RXXaA4&123E@D=PQLr   c                    UR                   n[        R                  " UR                  UR                  UR
                  S   5      n[        R                  " UR                  UR                  UR
                  S   5      nUR
                  S   UR                  U S   5      -
  UR
                  S   UR                  U S   5      -
  4UR                  U S   5      UR                  U S   5      44nU$ )a8  
Convert XY bounding box into the window of the tile raster

Parameters
----------
bb : tuple
    (left, bottom, right, top) in the CRS of `rtr`
rtr : RasterReader
    Open rasterio raster from which the window will be extracted

Returns
-------
window : tuple
    ((row_start, row_stop), (col_start, col_stop))
r   r      r.   )	r   r;   r<   r   r   r:   r   r   searchsorted)bbrtrrbbxiyiwindows         r   bb2wdwr      s      **C	SXXsyy#))A,	7B	SZZ#))A,	7B 
11.	.		!rrRSu?U0UV	A	A!78F Mr   c                     Sn[         R                  U-  nX-  S-  nX-  S-  nS[         R                  -  S[         R                  " [         R                  " U[         R                  -  S-  5      5      -  [         R                  S-  -
  -  nXE4$ )ad  
Transform Spherical Mercator coordinates point into lon/lat

NOTE: Translated from the JS implementation in
http://dotnetfollower.com/wordpress/2011/07/javascript-how-to-convert-mercator-sphere-coordinates-to-latitude-and-longitude/
...

Arguments
---------
x : float
    Easting
y : float
    Northing

Returns
-------
ll : tuple
    lon/lat coordinates
g   @TXAg     f@g       @)r;   piarctanexp)rP   rQ   rMajorshiftlonlats         r   r9   r9     sy    ( FEEFNE
)e
C
)e
C
"%%-3266#+2E+F!GG"%%RU+U
VC8Or   c                    [         R                  " X /5      SSS2   n[         R                  " X/5      SSS2   n[         R                  " U6 n[         R                  " U6 n[         R                  " [         R                  " SU-  5      5      n[         R                  " [         R                  " SU-  5      5      n	[         R
                  " X/5      n
[        U
5      $ )a  Automatically choose a zoom level given a desired number of tiles.

.. note:: all values are interpreted as latitude / longitutde.

Parameters
----------
w : float
    The western bbox edge.
s : float
    The southern bbox edge.
e : float
    The eastern bbox edge.
n : float
    The northern bbox edge.

Returns
-------
zoom : int
    The zoom level to use in order to download this number of tiles.
Nr-   g     @)r;   sortsubtractceillog2minrl   )r/   rC   rD   rE   	lon_range	lat_range
lon_length
lat_lengthzoom_lonzoom_latr(   s              r   re   re   7  s    , "%I"%Ii(Ji(J wwrwwy:567Hwwrwwy:567H668&'Dt9r   c                 r   UR                  SS5      nSU;   a  UR                  S5      nSnOSnSnX0s=::  a  U::  a   U $   U(       a  SOSnS	R                  X`5      nU(       a  US
R                  X45      -  nOUS-  nU(       a)  X:  a  U(       a  [        R                  " U5        U$ US-  n[	        U5      e)ad  
Validate the zoom level and if needed raise informative error message.
Returns the validated zoom.

Parameters
----------
zoom : int
    The specified or calculated zoom level
provider : dict
auto : bool
    Indicating if zoom was specified or calculated (to have specific
    error message for each case).

Returns
-------
int
    Validated zoom level.

min_zoomr   max_zoomT   Finferred	specifiedzDThe {0} zoom level of {1} is not valid for the current tile providerz (valid zooms: {0} - {1})..z This can indicate that the extent of your figure is wrong (e.g. too small extent, or in the wrong coordinate reference system))r   r   warningswarnrm   )r(   rs   rW   r   r   max_zoom_knownmodemsgs           r   rf   rf   Z  s    ( ||J*HX<<
+ #8# $ :;D
P
W
WC +228FFs
?~MM#OI	
 S/r   c                    [         R                  " U  Vs/ s H  o"R                  UR                  4PM     sn5      nX3R	                  SS9-
  nUS   R
                  u  pVnUS-   R                  SS9u  p[         R                  " XY-  Xh-  U4[         R                  S9n
[        XA5       H&  u  pUu  pXX-  US-   U-  2X-  US-   U-  2SS24'   M(     [         R                  " U  Vs/ s H  n[        R                  " U5      PM     sn5      n[	        USS2S4   5      [	        USS2S4   5      [        USS2S4   5      [        USS2S4   5      4u  nnnnU
UUUU44$ s  snf s  snf )a  
Merge a set of tiles into a single array.

Parameters
---------
tiles : list of mercantile.Tile objects
    The tiles to merge.
arrays : list of numpy arrays
    The corresponding arrays (image pixels) of the tiles. This list
    has the same length and order as the `tiles` argument.

Returns
-------
img : np.ndarray
    Merged arrays.
extent : tuple
    Bounding box [west, south, east, north] of the returned image
    in long/lat.
r   )axisr   )r6   Nr.   r   )r;   r   rP   rQ   r   r:   maxzerosuint8ziprh   r   )ri   rx   ttile_xysindicesrJ   r/   dn_xn_yr   indarrrP   rQ   r   r{   r|   r}   r~   s                       r   rp   rp     sk   * xxU3U##qssU34H 1--G QiooGA! !  a (HC ((AGQWa(
9C(;>AEQUaK!a%1!4a78 ) XXU3Uryy|U34FF1a4LF1a4LF1a4LF1a4L	 D%u udE***5 4$ 4s   !E!' E&)rW   NFr   r.   r   T)rW   NFr   r.   r   TN)TF)T)@__doc__
__future__r   r   r   uuid
mercantilerh   r   atexitr   r   r"   tempfiler   numpyr;   rasterior=   PILr   r   joblibr   _Memoryr	   r
   rasterio.transformr   rasterio.ior   rasterio.vrtr   rasterio.enumsr   r   r   xyzservicesr   __all__uuid4hexr   mkdtempr$   r   r   r&   registerr   r   rd   ro   bilinearr   r   r   r   r   r   r9   re   rf   rp   r%   r   r   <module>r     s7   7 @ @     	       - $ $ * " " %  $ TZZ\---
						#)".   
	
pp 
	
nb 
 #.*:M:M .,b AK@S@S $N"4,\\ F68 F2j/+r   