Skip to content

Commit

Permalink
Merge pull request geopandas#87 from jorisvandenbossche/blacken
Browse files Browse the repository at this point in the history
STYLE: blacken the codebase
  • Loading branch information
darribas committed Aug 1, 2019
2 parents dcb3854 + 6e12d62 commit 9f67221
Show file tree
Hide file tree
Showing 9 changed files with 403 additions and 281 deletions.
2 changes: 1 addition & 1 deletion contextily/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,4 +7,4 @@
from .tile import *
from .plotting import add_basemap, add_attribution

__version__ = '0.99.0.dev'
__version__ = "0.99.0.dev"
70 changes: 47 additions & 23 deletions contextily/place.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
from .tile import howmany, bounds2raster, bounds2img, _sm2ll, _calculate_zoom
from .plotting import ATTRIBUTION, INTERPOLATION, ZOOM, add_attribution


class Place(object):
"""Geocode a place by name and get its map.
Expand Down Expand Up @@ -58,12 +59,12 @@ def __init__(self, search, zoom=None, path=None, zoom_adjust=None, url=None):

# Get geocoded values
resp = gp.geocoders.Nominatim().geocode(search)
bbox = np.array([float(ii) for ii in resp.raw['boundingbox']])
bbox = np.array([float(ii) for ii in resp.raw["boundingbox"]])

if 'display_name' in resp.raw.keys():
place = resp.raw['display_name']
elif 'address' in resp.raw.keys():
place = resp.raw['address']
if "display_name" in resp.raw.keys():
place = resp.raw["display_name"]
elif "address" in resp.raw.keys():
place = resp.raw["address"]
else:
place = search
self.place = place
Expand All @@ -75,7 +76,9 @@ def __init__(self, search, zoom=None, path=None, zoom_adjust=None, url=None):
self.geocode = resp

# Get map params
self.zoom = _calculate_zoom(self.w, self.s, self.e, self.n) if zoom is None else zoom
self.zoom = (
_calculate_zoom(self.w, self.s, self.e, self.n) if zoom is None else zoom
)
self.zoom = int(self.zoom)
if self.zoom_adjust is not None:
self.zoom += zoom_adjust
Expand All @@ -84,27 +87,34 @@ def __init__(self, search, zoom=None, path=None, zoom_adjust=None, url=None):
# Get the map
self._get_map()


def _get_map(self):
kwargs = {'ll': True}
kwargs = {"ll": True}
if self.url is not None:
kwargs['url'] = self.url
kwargs["url"] = self.url

try:
if isinstance(self.path, str):
im, bbox = bounds2raster(self.w, self.s, self.e, self.n, self.path, zoom=self.zoom, **kwargs)
im, bbox = bounds2raster(
self.w, self.s, self.e, self.n, self.path, zoom=self.zoom, **kwargs
)
else:
im, bbox = bounds2img(self.w, self.s, self.e, self.n, self.zoom, **kwargs)
im, bbox = bounds2img(
self.w, self.s, self.e, self.n, self.zoom, **kwargs
)
except Exception as err:
raise ValueError('Could not retrieve map with parameters: {}, {}, {}, {}, zoom={}\n{}\nError: {}'.format(
self.w, self.s, self.e, self.n, self.zoom, kwargs, err))
raise ValueError(
"Could not retrieve map with parameters: {}, {}, {}, {}, zoom={}\n{}\nError: {}".format(
self.w, self.s, self.e, self.n, self.zoom, kwargs, err
)
)

self.im = im
self.bbox_map = bbox
return im, bbox

def plot(self, ax=None, zoom=ZOOM, interpolation=INTERPOLATION,
attribution = ATTRIBUTION):
def plot(
self, ax=None, zoom=ZOOM, interpolation=INTERPOLATION, attribution=ATTRIBUTION
):
"""
Plot a `Place` object
...
Expand Down Expand Up @@ -148,7 +158,7 @@ def plot(self, ax=None, zoom=ZOOM, interpolation=INTERPOLATION,
axisoff = False
if ax is None:
fig, ax = plt.subplots(figsize=(12, 12))
title = self.place
title = self.place
axisoff = True
ax.imshow(im, extent=bbox, interpolation=interpolation)
ax.set(xlabel="X", ylabel="Y")
Expand All @@ -161,12 +171,21 @@ def plot(self, ax=None, zoom=ZOOM, interpolation=INTERPOLATION,
return ax

def __repr__(self):
s = 'Place : {} | n_tiles: {} | zoom : {} | im : {}'.format(
self.place, self.n_tiles, self.zoom, self.im.shape[:2])
s = "Place : {} | n_tiles: {} | zoom : {} | im : {}".format(
self.place, self.n_tiles, self.zoom, self.im.shape[:2]
)
return s

def plot_map(place, bbox=None, title=None, ax=None, axis_off=True,
latlon=True, attribution = ATTRIBUTION):

def plot_map(
place,
bbox=None,
title=None,
ax=None,
axis_off=True,
latlon=True,
attribution=ATTRIBUTION,
):
"""Plot a map of the given place.
Parameters
Expand All @@ -188,9 +207,14 @@ def plot_map(place, bbox=None, title=None, ax=None, axis_off=True,
ax : instance of matplotlib Axes object | None
The axis on the map is plotted.
"""
warn( ("The method `plot_map` is deprecated and will be removed from the"
" library in future versions. Please use either `add_basemap` or"
" the internal method `Place.plot`"), DeprecationWarning)
warn(
(
"The method `plot_map` is deprecated and will be removed from the"
" library in future versions. Please use either `add_basemap` or"
" the internal method `Place.plot`"
),
DeprecationWarning,
)
if not isinstance(place, Place):
im = place
bbox = bbox
Expand Down
80 changes: 45 additions & 35 deletions contextily/plotting.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,17 +7,26 @@
from rasterio.warp import transform_bounds
from matplotlib import patheffects

INTERPOLATION = 'bilinear'
ZOOM = 'auto'
ATTRIBUTION = ("Map tiles by Stamen Design, under CC BY 3.0. "\
"Data by OpenStreetMap, under ODbL.")
INTERPOLATION = "bilinear"
ZOOM = "auto"
ATTRIBUTION = (
"Map tiles by Stamen Design, under CC BY 3.0. " "Data by OpenStreetMap, under ODbL."
)
ATTRIBUTION_SIZE = 8

def add_basemap(ax, zoom=ZOOM, url=sources.ST_TERRAIN,
interpolation=INTERPOLATION, attribution = ATTRIBUTION,
attribution_size = ATTRIBUTION_SIZE, reset_extent=True,
crs=None, resampling=Resampling.bilinear,
**extra_imshow_args):

def add_basemap(
ax,
zoom=ZOOM,
url=sources.ST_TERRAIN,
interpolation=INTERPOLATION,
attribution=ATTRIBUTION,
attribution_size=ATTRIBUTION_SIZE,
reset_extent=True,
crs=None,
resampling=Resampling.bilinear,
**extra_imshow_args
):
"""
Add a (web/local) basemap to `ax`
...
Expand Down Expand Up @@ -93,42 +102,42 @@ def add_basemap(ax, zoom=ZOOM, url=sources.ST_TERRAIN,
"""
xmin, xmax, ymin, ymax = ax.axis()
# If web source
if url[:4] == 'http':
if url[:4] == "http":
# Extent
left, right, bottom, top = xmin, xmax, ymin, ymax
# Convert extent from `crs` into WM for tile query
if crs is not None:
left, right, bottom, top = _reproj_bb(left, right, bottom, top,
crs, {'init' :'epsg:3857'})
left, right, bottom, top = _reproj_bb(
left, right, bottom, top, crs, {"init": "epsg:3857"}
)
# Zoom
if isinstance(zoom, str) and (zoom.lower() == 'auto'):
if isinstance(zoom, str) and (zoom.lower() == "auto"):
min_ll = _sm2ll(left, bottom)
max_ll = _sm2ll(right, top)
zoom = _calculate_zoom(*min_ll, *max_ll)
image, extent = bounds2img(left, bottom, right, top,
zoom=zoom, url=url, ll=False)
image, extent = bounds2img(
left, bottom, right, top, zoom=zoom, url=url, ll=False
)
# Warping
if crs is not None:
image, extent = warp_tiles(image, extent, t_crs=crs,
resampling=resampling)
image, extent = warp_tiles(image, extent, t_crs=crs, resampling=resampling)
# If local source
else:
import rasterio as rio

# Read file
raster = rio.open(url)
image = np.array([ band for band in raster.read() ])
image = np.array([band for band in raster.read()])
# Warp
if (crs is not None) and (raster.crs != crs):
image, raster = _warper(image,
raster.transform,
raster.crs, crs,
resampling)
image, raster = _warper(
image, raster.transform, raster.crs, crs, resampling
)
image = image.transpose(1, 2, 0)
bb = raster.bounds
extent = bb.left, bb.right, bb.bottom, bb.top
# Plotting
ax.imshow(image, extent=extent,
interpolation=interpolation, **extra_imshow_args)
ax.imshow(image, extent=extent, interpolation=interpolation, **extra_imshow_args)

if reset_extent:
ax.axis((xmin, xmax, ymin, ymax))
Expand All @@ -139,14 +148,13 @@ def add_basemap(ax, zoom=ZOOM, url=sources.ST_TERRAIN,
return ax


def _reproj_bb(left, right, bottom, top,
s_crs, t_crs):
n_l, n_b, n_r, n_t = transform_bounds(s_crs, t_crs,
left, bottom, right, top)
def _reproj_bb(left, right, bottom, top, s_crs, t_crs):
n_l, n_b, n_r, n_t = transform_bounds(s_crs, t_crs, left, bottom, right, top)
return n_l, n_r, n_b, n_t


def add_attribution(ax, att=ATTRIBUTION, font_size=ATTRIBUTION_SIZE):
'''
"""
Utility to add attribution text
...
Expand All @@ -166,12 +174,14 @@ def add_attribution(ax, att=ATTRIBUTION, font_size=ATTRIBUTION_SIZE):
ax : AxesSubplot
Matplotlib axis with `x_lim` and `y_lim` set in Web
Mercator (EPSG=3857) and attribution text added
'''
"""
minX, maxX = ax.get_xlim()
minY, maxY = ax.get_ylim()
ax.text(minX + (maxX - minX) * 0.005,
minY + (maxY - minY) * 0.005,
att, size=font_size,
path_effects=[patheffects.withStroke(linewidth=2,
foreground="w")])
ax.text(
minX + (maxX - minX) * 0.005,
minY + (maxY - minY) * 0.005,
att,
size=font_size,
path_effects=[patheffects.withStroke(linewidth=2, foreground="w")],
)
return ax

0 comments on commit 9f67221

Please sign in to comment.