Skip to content

Commit

Permalink
Merge pull request #357 from lkluft/fix-lazy-imports
Browse files Browse the repository at this point in the history
Use lazy imports for `cartopy`
  • Loading branch information
olemke authored Mar 4, 2020
2 parents 64f20ba + f2e36fa commit 7ebf429
Show file tree
Hide file tree
Showing 3 changed files with 79 additions and 79 deletions.
12 changes: 3 additions & 9 deletions typhon/plots/__init__.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,4 @@
# -*- coding: utf-8 -*-

"""This module provides functions related to plot or to plot data.
"""
"""This module provides functions related to plot or to plot data. """

from typhon.plots import cm # noqa
from typhon.plots.colors import * # noqa
Expand All @@ -10,9 +7,6 @@
from typhon.plots.plots import * # noqa
from typhon.plots.arts_lookup import * # noqa
from typhon.plots.ppath import * # noqa
try:
from typhon.plots.maps import * # noqa
except ImportError:
pass
from typhon.plots.maps import * # noqa

__all__ = [s for s in dir() if not s.startswith('_')]
__all__ = [s for s in dir() if not s.startswith("_")]
143 changes: 75 additions & 68 deletions typhon/plots/maps.py
Original file line number Diff line number Diff line change
@@ -1,26 +1,27 @@
# -*- coding: utf-8 -*-
"""Functions related to plotting maps. """
from collections import namedtuple

try:
import cartopy.crs as ccrs
from cartopy.feature import NaturalEarthFeature, COLORS
except ImportError:
raise ImportError('You have to install `cartopy` to use functions '
'located in `typhon.plots.maps`.')
else:
from matplotlib import pyplot as plt
from matplotlib import pyplot as plt


__all__ = [
'worldmap',
'get_cfeatures_at_scale',
]
_CartopyError = ImportError(
"You have to install `cartopy` to use functions located in `typhon.plots.maps`."
)


def worldmap(lat, lon, var=None, fig=None, ax=None, projection=None,
bg=False, draw_grid=False, draw_coastlines=False,
interpolation=False, **kwargs):
def worldmap(
lat,
lon,
var=None,
fig=None,
ax=None,
projection=None,
bg=False,
draw_grid=False,
draw_coastlines=False,
interpolation=False,
**kwargs,
):
"""Plots the track of a variable on a worldmap.
Args:
Expand All @@ -43,13 +44,18 @@ def worldmap(lat, lon, var=None, fig=None, ax=None, projection=None,
Returns:
Scatter plot objects.
"""
try:
import cartopy.crs as ccrs
except ImportError:
raise _CartopyError

# Default keyword arguments to pass to hist2d().
kwargs_defaults = {
"cmap": "qualitative1",
"s": 1,
# This accelerates the drawing of many points:
"rasterized": lat.size > 100_000,
**kwargs
**kwargs,
}

if fig is None:
Expand Down Expand Up @@ -82,30 +88,26 @@ def worldmap(lat, lon, var=None, fig=None, ax=None, projection=None,
"s": 1,
# This accelerates the drawing of many points:
"rasterized": lat.size > 100_000,
**kwargs
**kwargs,
}
plot = ax.scatter(
lon, lat, c=var, transform=ccrs.PlateCarree(), **kwargs_defaults
)
elif interpolation:
kwargs_defaults = {
**kwargs
}
kwargs_defaults = {**kwargs}
plot = ax.contourf(
lon, lat, var, transform=ccrs.PlateCarree(), **kwargs_defaults
)
else:
kwargs_defaults = {
**kwargs
}
kwargs_defaults = {**kwargs}
plot = ax.pcolormesh(
lon, lat, var, transform=ccrs.PlateCarree(), **kwargs_defaults
)

return plot


def get_cfeatures_at_scale(scale='110m'):
def get_cfeatures_at_scale(scale="110m"):
"""Return a collection of `NaturalEarthFeature` at given scale.
Parameters:
Expand All @@ -123,76 +125,81 @@ def get_cfeatures_at_scale(scale='110m'):
'50m'
"""
try:
from cartopy.feature import NaturalEarthFeature, COLORS
except ImportError:
raise _CartopyError

d = {}

d['BORDERS'] = NaturalEarthFeature(
category='cultural',
name='admin_0_boundary_lines_land',
d["BORDERS"] = NaturalEarthFeature(
category="cultural",
name="admin_0_boundary_lines_land",
scale=scale,
edgecolor='black',
facecolor='none',
edgecolor="black",
facecolor="none",
)

d['STATES'] = NaturalEarthFeature(
category='cultural',
name='admin_1_states_provinces_lakes',
d["STATES"] = NaturalEarthFeature(
category="cultural",
name="admin_1_states_provinces_lakes",
scale=scale,
edgecolor='black',
facecolor='none',
edgecolor="black",
facecolor="none",
)

d['COASTLINE'] = NaturalEarthFeature(
category='physical',
name='coastline',
d["COASTLINE"] = NaturalEarthFeature(
category="physical",
name="coastline",
scale=scale,
edgecolor='black',
facecolor='none',
edgecolor="black",
facecolor="none",
)

d['LAKES'] = NaturalEarthFeature(
category='physical',
name='lakes',
d["LAKES"] = NaturalEarthFeature(
category="physical",
name="lakes",
scale=scale,
edgecolor='face',
facecolor=COLORS['water'],
edgecolor="face",
facecolor=COLORS["water"],
)

d['LAND'] = NaturalEarthFeature(
category='physical',
name='land',
d["LAND"] = NaturalEarthFeature(
category="physical",
name="land",
scale=scale,
edgecolor='face',
facecolor=COLORS['land'],
edgecolor="face",
facecolor=COLORS["land"],
zorder=-1,
)

d['OCEAN'] = NaturalEarthFeature(
category='physical',
name='ocean',
d["OCEAN"] = NaturalEarthFeature(
category="physical",
name="ocean",
scale=scale,
edgecolor='face',
facecolor=COLORS['water'],
edgecolor="face",
facecolor=COLORS["water"],
zorder=-1,
)

d['RIVERS'] = NaturalEarthFeature(
category='physical',
name='rivers_lake_centerlines',
d["RIVERS"] = NaturalEarthFeature(
category="physical",
name="rivers_lake_centerlines",
scale=scale,
edgecolor=COLORS['water'],
facecolor='none',
edgecolor=COLORS["water"],
facecolor="none",
)

NaturalEarthFeatures = namedtuple(
typename='NaturalEarthFeatures',
typename="NaturalEarthFeatures",
field_names=(
'BORDERS',
'STATES',
'COASTLINE',
'LAKES',
'LAND',
'OCEAN',
'RIVERS',
"BORDERS",
"STATES",
"COASTLINE",
"LAKES",
"LAND",
"OCEAN",
"RIVERS",
),
)

Expand Down
3 changes: 1 addition & 2 deletions typhon/retrieval/spareice/common.py
Original file line number Diff line number Diff line change
Expand Up @@ -70,11 +70,10 @@
from sklearn.neural_network import MLPRegressor
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import RobustScaler
from sklearn.ensemble import RandomForestClassifier
from sklearn.tree import DecisionTreeClassifier
from typhon.collocations import collapse, Collocations, Collocator
from typhon.geographical import sea_mask
from typhon.plots import binned_statistic, heatmap, styles, worldmap
from typhon.plots import binned_statistic, heatmap
from typhon.utils import to_array, Timer
import xarray as xr

Expand Down

0 comments on commit 7ebf429

Please sign in to comment.