Debian Codegraph @

contextily/tile.py

raw symbols SCIP
1 """Tools for downloading map tiles from coordinates."""
2 from __future__ import absolute_import, division, print_function
3
4 import uuid
5
6 import mercantile as mt
7 import requests
8 import atexit
9 import io
10 import os
11 import shutil
12 import tempfile
13 import warnings
14
15 import numpy as np
16 import rasterio as rio
17 from PIL import Image, UnidentifiedImageError
18 from joblib import Memory as _Memory
19 from joblib import Parallel, delayed
20 from rasterio.transform import from_origin
21 from rasterio.io import MemoryFile
22 from rasterio.vrt import WarpedVRT
23 from rasterio.enums import Resampling
24 from . import providers
25 from xyzservices import TileProvider
26
27 __all__ = [
28 "bounds2raster",
29 "bounds2img",
30 "warp_tiles",
31 "warp_img_transform",
32 "howmany",
33 "set_cache_dir",
34 ]
35
36
37 USER_AGENT = "contextily-" + uuid.uuid4().hex
38
39 tmpdir = tempfile.mkdtemp()
40 memory = _Memory(tmpdir, verbose=0)
41
42
43 def set_cache_dir(path):
44 """
45 Set a cache directory to use in the current python session.
46
47 By default, contextily caches downloaded tiles per python session, but
48 will afterwards delete the cache directory. By setting it to a custom
49 path, you can avoid this, and re-use the same cache a next time by
50 again setting the cache dir to that directory.
51
52 Parameters
53 ----------
54 path : str
55 Path to the cache directory.
56 """
57 memory.store_backend.location = path
58
59
60 def _clear_cache():
61 shutil.rmtree(tmpdir)
62
63
64 atexit.register(_clear_cache)
65
66
67 def bounds2raster(
68 w,
69 s,
70 e,
71 n,
72 path,
73 zoom="auto",
74 source=None,
75 ll=False,
76 wait=0,
77 max_retries=2,
78 n_connections=1,
79 use_cache=True,
80 ):
81 """
82 Take bounding box and zoom, and write tiles into a raster file in
83 the Spherical Mercator CRS (EPSG:3857)
84
85 Parameters
86 ----------
87 w : float
88 West edge
89 s : float
90 South edge
91 e : float
92 East edge
93 n : float
94 North edge
95 zoom : int
96 Level of detail
97 path : str
98 Path to raster file to be written
99 source : xyzservices.TileProvider object or str
100 [Optional. Default: OpenStreetMap Humanitarian web tiles]
101 The tile source: web tile provider or path to local file. The web tile
102 provider can be in the form of a :class:`xyzservices.TileProvider` object or a
103 URL. The placeholders for the XYZ in the URL need to be `{x}`, `{y}`,
104 `{z}`, respectively. For local file paths, the file is read with
105 `rasterio` and all bands are loaded into the basemap.
106 IMPORTANT: tiles are assumed to be in the Spherical Mercator
107 projection (EPSG:3857), unless the `crs` keyword is specified.
108 ll : Boolean
109 [Optional. Default: False] If True, `w`, `s`, `e`, `n` are
110 assumed to be lon/lat as opposed to Spherical Mercator.
111 wait : int
112 [Optional. Default: 0]
113 if the tile API is rate-limited, the number of seconds to wait
114 between a failed request and the next try
115 max_retries: int
116 [Optional. Default: 2]
117 total number of rejected requests allowed before contextily
118 will stop trying to fetch more tiles from a rate-limited API.
119 n_connections: int
120 [Optional. Default: 1]
121 Number of connections for downloading tiles in parallel. Be careful not to overload the tile server and to check
122 the tile provider's terms of use before increasing this value. E.g., OpenStreetMap has a max. value of 2
123 (https://operations.osmfoundation.org/policies/tiles/). If allowed to download in parallel, a recommended
124 value for n_connections is 16, and should never be larger than 64.
125 use_cache: bool
126 [Optional. Default: True]
127 If False, caching of the downloaded tiles will be disabled. This can be useful in resource constrained
128 environments, especially when using n_connections > 1, or when a tile provider's terms of use don't allow
129 caching.
130
131 Returns
132 -------
133 img : ndarray
134 Image as a 3D array of RGB values
135 extent : tuple
136 Bounding box [minX, maxX, minY, maxY] of the returned image
137 """
138 if not ll:
139 # Convert w, s, e, n into lon/lat
140 w, s = _sm2ll(w, s)
141 e, n = _sm2ll(e, n)
142 # Download
143 Z, ext = bounds2img(w, s, e, n, zoom=zoom, source=source, ll=True, n_connections=n_connections,
144 use_cache=use_cache)
145
146 # Write
147 # ---
148 h, w, b = Z.shape
149 # --- https://mapbox.github.io/rasterio/quickstart.html#opening-a-dataset-in-writing-mode
150 minX, maxX, minY, maxY = ext
151 x = np.linspace(minX, maxX, w)
152 y = np.linspace(minY, maxY, h)
153 resX = (x[-1] - x[0]) / w
154 resY = (y[-1] - y[0]) / h
155 transform = from_origin(x[0] - resX / 2, y[-1] + resY / 2, resX, resY)
156 # ---
157 with rio.open(
158 path,
159 "w",
160 driver="GTiff",
161 height=h,
162 width=w,
163 count=b,
164 dtype=str(Z.dtype.name),
165 crs="epsg:3857",
166 transform=transform,
167 ) as raster:
168 for band in range(b):
169 raster.write(Z[:, :, band], band + 1)
170 return Z, ext
171
172
173 def bounds2img(
174 w, s, e, n, zoom="auto", source=None, ll=False, wait=0, max_retries=2, n_connections=1, use_cache=True, zoom_adjust=None
175 ):
176 """
177 Take bounding box and zoom and return an image with all the tiles
178 that compose the map and its Spherical Mercator extent.
179
180 Parameters
181 ----------
182 w : float
183 West edge
184 s : float
185 South edge
186 e : float
187 East edge
188 n : float
189 North edge
190 zoom : int
191 Level of detail
192 source : xyzservices.TileProvider object or str
193 [Optional. Default: OpenStreetMap Humanitarian web tiles]
194 The tile source: web tile provider or path to local file. The web tile
195 provider can be in the form of a :class:`xyzservices.TileProvider` object or a
196 URL. The placeholders for the XYZ in the URL need to be `{x}`, `{y}`,
197 `{z}`, respectively. For local file paths, the file is read with
198 `rasterio` and all bands are loaded into the basemap.
199 IMPORTANT: tiles are assumed to be in the Spherical Mercator
200 projection (EPSG:3857), unless the `crs` keyword is specified.
201 ll : Boolean
202 [Optional. Default: False] If True, `w`, `s`, `e`, `n` are
203 assumed to be lon/lat as opposed to Spherical Mercator.
204 wait : int
205 [Optional. Default: 0]
206 if the tile API is rate-limited, the number of seconds to wait
207 between a failed request and the next try
208 max_retries: int
209 [Optional. Default: 2]
210 total number of rejected requests allowed before contextily
211 will stop trying to fetch more tiles from a rate-limited API.
212 n_connections: int
213 [Optional. Default: 1]
214 Number of connections for downloading tiles in parallel. Be careful not to overload the tile server and to check
215 the tile provider's terms of use before increasing this value. E.g., OpenStreetMap has a max. value of 2
216 (https://operations.osmfoundation.org/policies/tiles/). If allowed to download in parallel, a recommended
217 value for n_connections is 16, and should never be larger than 64.
218 use_cache: bool
219 [Optional. Default: True]
220 If False, caching of the downloaded tiles will be disabled. This can be useful in resource constrained
221 environments, especially when using n_connections > 1, or when a tile provider's terms of use don't allow
222 caching.
223 zoom_adjust : int or None
224 [Optional. Default: None]
225 The amount to adjust a chosen zoom level if it is chosen automatically.
226 Values outside of -1 to 1 are not recommended as they can lead to slow execution.
227
228 Returns
229 -------
230 img : ndarray
231 Image as a 3D array of RGB values
232 extent : tuple
233 Bounding box [minX, maxX, minY, maxY] of the returned image
234 """
235 if not ll:
236 # Convert w, s, e, n into lon/lat
237 w, s = _sm2ll(w, s)
238 e, n = _sm2ll(e, n)
239
240 # get provider dict given the url
241 provider = _process_source(source)
242 # calculate and validate zoom level
243 auto_zoom = zoom == "auto"
244 if auto_zoom:
245 zoom = _calculate_zoom(w, s, e, n)
246 if zoom_adjust:
247 zoom += zoom_adjust
248 zoom = _validate_zoom(zoom, provider, auto=auto_zoom)
249 # create list of tiles to download
250 tiles = list(mt.tiles(w, s, e, n, [zoom]))
251 tile_urls = [provider.build_url(x=tile.x, y=tile.y, z=tile.z) for tile in tiles]
252 # download tiles
253 if n_connections < 1 or not isinstance(n_connections, int):
254 raise ValueError(
255 f"n_connections must be a positive integer value."
256 )
257 # Use threads for a single connection to avoid the overhead of spawning a process. Use processes for multiple
258 # connections if caching is enabled, as threads lead to memory issues when used in combination with the joblib
259 # memory caching (used for the _fetch_tile() function).
260 preferred_backend = "threads" if (n_connections == 1 or not use_cache) else "processes"
261 fetch_tile_fn = memory.cache(_fetch_tile) if use_cache else _fetch_tile
262 arrays = Parallel(n_jobs=n_connections, prefer=preferred_backend)(
263 delayed(fetch_tile_fn)(tile_url, wait, max_retries) for tile_url in tile_urls)
264 # merge downloaded tiles
265 merged, extent = _merge_tiles(tiles, arrays)
266 # lon/lat extent --> Spheric Mercator
267 west, south, east, north = extent
268 left, bottom = mt.xy(west, south)
269 right, top = mt.xy(east, north)
270 extent = left, right, bottom, top
271 return merged, extent
272
273
274 def _process_source(source):
275 if source is None:
276 provider = providers.OpenStreetMap.HOT
277 elif isinstance(source, str):
278 provider = TileProvider(url=source, attribution="", name="url")
279 elif not isinstance(source, dict):
280 raise TypeError(
281 "The 'url' needs to be a xyzservices.TileProvider object or string"
282 )
283 elif "url" not in source:
284 raise ValueError("The 'url' dict should at least contain a 'url' key")
285 else:
286 provider = source
287 return provider
288
289
290 def _fetch_tile(tile_url, wait, max_retries):
291 array = _retryer(tile_url, wait, max_retries)
292 return array
293
294
295 def warp_tiles(img, extent, t_crs="EPSG:4326", resampling=Resampling.bilinear):
296 """
297 Reproject (warp) a Web Mercator basemap into any CRS on-the-fly
298
299 NOTE: this method works well with contextily's `bounds2img` approach to
300 raster dimensions (h, w, b)
301
302 Parameters
303 ----------
304 img : ndarray
305 Image as a 3D array (h, w, b) of RGB values (e.g. as
306 returned from `contextily.bounds2img`)
307 extent : tuple
308 Bounding box [minX, maxX, minY, maxY] of the returned image,
309 expressed in Web Mercator (`EPSG:3857`)
310 t_crs : str/CRS
311 [Optional. Default='EPSG:4326'] Target CRS, expressed in any
312 format permitted by rasterio. Defaults to WGS84 (lon/lat)
313 resampling : <enum 'Resampling'>
314 [Optional. Default=Resampling.bilinear] Resampling method for
315 executing warping, expressed as a `rasterio.enums.Resampling`
316 method
317
318 Returns
319 -------
320 img : ndarray
321 Image as a 3D array (h, w, b) of RGB values (e.g. as
322 returned from `contextily.bounds2img`)
323 ext : tuple
324 Bounding box [minX, maxX, minY, maxY] of the returned (warped)
325 image
326 """
327 h, w, b = img.shape
328 # --- https://rasterio.readthedocs.io/en/latest/quickstart.html#opening-a-dataset-in-writing-mode
329 minX, maxX, minY, maxY = extent
330 x = np.linspace(minX, maxX, w)
331 y = np.linspace(minY, maxY, h)
332 resX = (x[-1] - x[0]) / w
333 resY = (y[-1] - y[0]) / h
334 transform = from_origin(x[0] - resX / 2, y[-1] + resY / 2, resX, resY)
335 # ---
336 w_img, bounds, _ = _warper(
337 img.transpose(2, 0, 1), transform, "EPSG:3857", t_crs, resampling
338 )
339 # ---
340 extent = bounds.left, bounds.right, bounds.bottom, bounds.top
341 return w_img.transpose(1, 2, 0), extent
342
343
344 def warp_img_transform(img, transform, s_crs, t_crs, resampling=Resampling.bilinear):
345 """
346 Reproject (warp) an `img` with a given `transform` and `s_crs` into a
347 different `t_crs`
348
349 NOTE: this method works well with rasterio's `.read()` approach to
350 raster's dimensions (b, h, w)
351
352 Parameters
353 ----------
354 img : ndarray
355 Image as a 3D array (b, h, w) of RGB values (e.g. as
356 returned from rasterio's `.read()` method)
357 transform : affine.Affine
358 Transform of the input image as expressed by `rasterio` and
359 the `affine` package
360 s_crs : str/CRS
361 Source CRS in which `img` is passed, expressed in any format
362 permitted by rasterio.
363 t_crs : str/CRS
364 Target CRS, expressed in any format permitted by rasterio.
365 resampling : <enum 'Resampling'>
366 [Optional. Default=Resampling.bilinear] Resampling method for
367 executing warping, expressed as a `rasterio.enums.Resampling`
368 method
369
370 Returns
371 -------
372 w_img : ndarray
373 Warped image as a 3D array (b, h, w) of RGB values (e.g. as
374 returned from rasterio's `.read()` method)
375 w_transform : affine.Affine
376 Transform of the input image as expressed by `rasterio` and
377 the `affine` package
378 """
379 w_img, _, w_transform = _warper(img, transform, s_crs, t_crs, resampling)
380 return w_img, w_transform
381
382
383 def _warper(img, transform, s_crs, t_crs, resampling):
384 """
385 Warp an image. Returns the warped image and updated bounds and transform.
386 """
387 b, h, w = img.shape
388 with MemoryFile() as memfile:
389 with memfile.open(
390 driver="GTiff",
391 height=h,
392 width=w,
393 count=b,
394 dtype=str(img.dtype.name),
395 crs=s_crs,
396 transform=transform,
397 ) as mraster:
398 mraster.write(img)
399
400 with memfile.open() as mraster:
401 with WarpedVRT(mraster, crs=t_crs, resampling=resampling) as vrt:
402 img = vrt.read()
403 bounds = vrt.bounds
404 transform = vrt.transform
405
406 return img, bounds, transform
407
408
409 def _retryer(tile_url, wait, max_retries):
410 """
411 Retry a url many times in attempt to get a tile and read the image
412
413 Arguments
414 ---------
415 tile_url : str
416 string that is the target of the web request. Should be
417 a properly-formatted url for a tile provider.
418 wait : int
419 if the tile API is rate-limited, the number of seconds to wait
420 between a failed request and the next try
421 max_retries : int
422 total number of rejected requests allowed before contextily
423 will stop trying to fetch more tiles from a rate-limited API.
424
425 Returns
426 -------
427 array of the tile
428 """
429 try:
430 request = requests.get(tile_url, headers={"user-agent": USER_AGENT})
431 request.raise_for_status()
432 with io.BytesIO(request.content) as image_stream:
433 image = Image.open(image_stream).convert("RGBA")
434 array = np.asarray(image)
435 image.close()
436
437 return array
438
439 except (requests.HTTPError, UnidentifiedImageError):
440 if request.status_code == 404:
441 raise requests.HTTPError(
442 "Tile URL resulted in a 404 error. "
443 "Double-check your tile url:\n{}".format(tile_url)
444 )
445 elif request.status_code == 104 or request.status_code == 200:
446 if max_retries > 0:
447 os.wait(wait)
448 max_retries -= 1
449 request = _retryer(tile_url, wait, max_retries)
450 else:
451 raise requests.HTTPError("Connection reset by peer too many times.")
452
453
454
455 def howmany(w, s, e, n, zoom, verbose=True, ll=False):
456 """
457 Number of tiles required for a given bounding box and a zoom level
458
459 Parameters
460 ----------
461 w : float
462 West edge
463 s : float
464 South edge
465 e : float
466 East edge
467 n : float
468 North edge
469 zoom : int
470 Level of detail
471 verbose : Boolean
472 [Optional. Default=True] If True, print short message with
473 number of tiles and zoom.
474 ll : Boolean
475 [Optional. Default: False] If True, `w`, `s`, `e`, `n` are
476 assumed to be lon/lat as opposed to Spherical Mercator.
477 """
478 if not ll:
479 # Convert w, s, e, n into lon/lat
480 w, s = _sm2ll(w, s)
481 e, n = _sm2ll(e, n)
482 if zoom == "auto":
483 zoom = _calculate_zoom(w, s, e, n)
484 tiles = len(list(mt.tiles(w, s, e, n, [zoom])))
485 if verbose:
486 print("Using zoom level %i, this will download %i tiles" % (zoom, tiles))
487 return tiles
488
489
490 def bb2wdw(bb, rtr):
491 """
492 Convert XY bounding box into the window of the tile raster
493
494 Parameters
495 ----------
496 bb : tuple
497 (left, bottom, right, top) in the CRS of `rtr`
498 rtr : RasterReader
499 Open rasterio raster from which the window will be extracted
500
501 Returns
502 -------
503 window : tuple
504 ((row_start, row_stop), (col_start, col_stop))
505 """
506 rbb = rtr.bounds
507 xi = np.linspace(rbb.left, rbb.right, rtr.shape[1])
508 yi = np.linspace(rbb.bottom, rbb.top, rtr.shape[0])
509
510 window = (
511 (rtr.shape[0] - yi.searchsorted(bb[3]), rtr.shape[0] - yi.searchsorted(bb[1])),
512 (xi.searchsorted(bb[0]), xi.searchsorted(bb[2])),
513 )
514 return window
515
516
517 def _sm2ll(x, y):
518 """
519 Transform Spherical Mercator coordinates point into lon/lat
520
521 NOTE: Translated from the JS implementation in
522 http://dotnetfollower.com/wordpress/2011/07/javascript-how-to-convert-mercator-sphere-coordinates-to-latitude-and-longitude/
523 ...
524
525 Arguments
526 ---------
527 x : float
528 Easting
529 y : float
530 Northing
531
532 Returns
533 -------
534 ll : tuple
535 lon/lat coordinates
536 """
537 rMajor = 6378137.0 # Equatorial Radius, QGS84
538 shift = np.pi * rMajor
539 lon = x / shift * 180.0
540 lat = y / shift * 180.0
541 lat = 180.0 / np.pi * (2.0 * np.arctan(np.exp(lat * np.pi / 180.0)) - np.pi / 2.0)
542 return lon, lat
543
544
545 def _calculate_zoom(w, s, e, n):
546 """Automatically choose a zoom level given a desired number of tiles.
547
548 .. note:: all values are interpreted as latitude / longitutde.
549
550 Parameters
551 ----------
552 w : float
553 The western bbox edge.
554 s : float
555 The southern bbox edge.
556 e : float
557 The eastern bbox edge.
558 n : float
559 The northern bbox edge.
560
561 Returns
562 -------
563 zoom : int
564 The zoom level to use in order to download this number of tiles.
565 """
566 # Calculate bounds of the bbox
567 lon_range = np.sort([e, w])[::-1]
568 lat_range = np.sort([s, n])[::-1]
569
570 lon_length = np.subtract(*lon_range)
571 lat_length = np.subtract(*lat_range)
572
573 # Calculate the zoom
574 zoom_lon = np.ceil(np.log2(360 * 2.0 / lon_length))
575 zoom_lat = np.ceil(np.log2(360 * 2.0 / lat_length))
576 zoom = np.min([zoom_lon, zoom_lat])
577 return int(zoom)
578
579
580 def _validate_zoom(zoom, provider, auto=True):
581 """
582 Validate the zoom level and if needed raise informative error message.
583 Returns the validated zoom.
584
585 Parameters
586 ----------
587 zoom : int
588 The specified or calculated zoom level
589 provider : dict
590 auto : bool
591 Indicating if zoom was specified or calculated (to have specific
592 error message for each case).
593
594 Returns
595 -------
596 int
597 Validated zoom level.
598
599 """
600 min_zoom = provider.get("min_zoom", 0)
601 if "max_zoom" in provider:
602 max_zoom = provider.get("max_zoom")
603 max_zoom_known = True
604 else:
605 # 22 is known max in existing providers, taking some margin
606 max_zoom = 30
607 max_zoom_known = False
608
609 if min_zoom <= zoom <= max_zoom:
610 return zoom
611
612 mode = "inferred" if auto else "specified"
613 msg = "The {0} zoom level of {1} is not valid for the current tile provider".format(
614 mode, zoom
615 )
616 if max_zoom_known:
617 msg += " (valid zooms: {0} - {1}).".format(min_zoom, max_zoom)
618 else:
619 msg += "."
620 if auto:
621 # automatically inferred zoom: clip to max zoom if that is known ...
622 if zoom > max_zoom and max_zoom_known:
623 warnings.warn(msg)
624 return max_zoom
625 # ... otherwise extend the error message with possible reasons
626 msg += (
627 " This can indicate that the extent of your figure is wrong (e.g. too "
628 "small extent, or in the wrong coordinate reference system)"
629 )
630 raise ValueError(msg)
631
632
633 def _merge_tiles(tiles, arrays):
634 """
635 Merge a set of tiles into a single array.
636
637 Parameters
638 ---------
639 tiles : list of mercantile.Tile objects
640 The tiles to merge.
641 arrays : list of numpy arrays
642 The corresponding arrays (image pixels) of the tiles. This list
643 has the same length and order as the `tiles` argument.
644
645 Returns
646 -------
647 img : np.ndarray
648 Merged arrays.
649 extent : tuple
650 Bounding box [west, south, east, north] of the returned image
651 in long/lat.
652 """
653 # create (n_tiles x 2) array with column for x and y coordinates
654 tile_xys = np.array([(t.x, t.y) for t in tiles])
655
656 # get indices starting at zero
657 indices = tile_xys - tile_xys.min(axis=0)
658
659 # the shape of individual tile images
660 h, w, d = arrays[0].shape
661
662 # number of rows and columns in the merged tile
663 n_x, n_y = (indices + 1).max(axis=0)
664
665 # empty merged tiles array to be filled in
666 img = np.zeros((h * n_y, w * n_x, d), dtype=np.uint8)
667
668 for ind, arr in zip(indices, arrays):
669 x, y = ind
670 img[y * h : (y + 1) * h, x * w : (x + 1) * w, :] = arr
671
672 bounds = np.array([mt.bounds(t) for t in tiles])
673 west, south, east, north = (
674 min(bounds[:, 0]),
675 min(bounds[:, 1]),
676 max(bounds[:, 2]),
677 max(bounds[:, 3]),
678 )
679
680 return img, (west, south, east, north)