Skip to content

Commit

Permalink
Reduce plt usage in tests
Browse files Browse the repository at this point in the history
When we already have a Figure or Axes, then use that directly. Also, if
multiple subplots are created, then make a figure (if there wasn't one)
to create those on.
  • Loading branch information
QuLogic committed Sep 23, 2021
1 parent 71c4fba commit 7824dc4
Show file tree
Hide file tree
Showing 9 changed files with 160 additions and 165 deletions.
20 changes: 11 additions & 9 deletions lib/cartopy/tests/mpl/test_caching.py
Original file line number Diff line number Diff line change
Expand Up @@ -81,18 +81,19 @@ def __exit__(self, exc_type, exc_val, exc_tb):
def test_coastline_loading_cache():
# a5caae040ee11e72a62a53100fe5edc355304419 added coastline caching.
# This test ensures it is working.
fig = plt.figure()

# Create coastlines to ensure they are cached.
ax1 = plt.subplot(2, 1, 1, projection=ccrs.PlateCarree())
ax1 = fig.add_subplot(2, 1, 1, projection=ccrs.PlateCarree())
ax1.coastlines()
plt.draw()
fig.canvas.draw()
# Create another instance of the coastlines and count
# the number of times shapereader.Reader is created.
counter = CallCounter(cartopy.io.shapereader.Reader, '__init__')
with counter:
ax2 = plt.subplot(2, 1, 1, projection=ccrs.Robinson())
ax2 = fig.add_subplot(2, 1, 1, projection=ccrs.Robinson())
ax2.coastlines()
plt.draw()
fig.canvas.draw()

assert counter.count == 0, (
f'The shapereader Reader class was created {counter.count} times, '
Expand All @@ -112,6 +113,7 @@ def test_shapefile_transform_cache():
geoms = tuple(geoms)[:10]
n_geom = len(geoms)

fig = plt.figure()
ax = plt.axes(projection=ccrs.Robinson())

# Empty the cache.
Expand All @@ -125,7 +127,7 @@ def test_shapefile_transform_cache():
ax.add_geometries(geoms, ccrs.PlateCarree())
ax.add_geometries(geoms, ccrs.PlateCarree())
ax.add_geometries(geoms[:], ccrs.PlateCarree())
ax.figure.canvas.draw()
fig.canvas.draw()

# Without caching the count would have been
# n_calls * n_geom, but should now be just n_geom.
Expand All @@ -139,7 +141,7 @@ def test_shapefile_transform_cache():

# Check that the cache is empty again once we've dropped all references
# to the source paths.
plt.clf()
fig.clf()
del geoms
gc.collect()
assert len(FeatureArtist._geom_key_to_geometry_cache) == 0
Expand All @@ -158,10 +160,10 @@ def test_contourf_transform_path_counting():
path_to_geos_counter = CallCounter(cartopy.mpl.patch, 'path_to_geos')
with path_to_geos_counter:
x, y, z = sample_data((30, 60))
cs = plt.contourf(x, y, z, 5, transform=ccrs.PlateCarree())
cs = ax.contourf(x, y, z, 5, transform=ccrs.PlateCarree())
n_geom = sum([len(c.get_paths()) for c in cs.collections])
del cs
ax.figure.canvas.draw()
fig.canvas.draw()

# Before the performance enhancement, the count would have been 2 * n_geom,
# but should now be just n_geom.
Expand All @@ -175,7 +177,7 @@ def test_contourf_transform_path_counting():

# Check that the cache is empty again once we've dropped all references
# to the source paths.
plt.clf()
fig.clf()
gc.collect()
assert len(cgeoaxes._PATH_TRANSFORM_CACHE) == initial_cache_size

Expand Down
56 changes: 27 additions & 29 deletions lib/cartopy/tests/mpl/test_gridliner.py
Original file line number Diff line number Diff line change
Expand Up @@ -58,57 +58,57 @@
def test_gridliner():
ny, nx = 2, 4

plt.figure(figsize=(10, 10))
fig = plt.figure(figsize=(10, 10))

ax = plt.subplot(nx, ny, 1, projection=ccrs.PlateCarree())
ax = fig.add_subplot(nx, ny, 1, projection=ccrs.PlateCarree())
ax.set_global()
ax.coastlines(resolution="110m")
ax.gridlines(linestyle=':')

ax = plt.subplot(nx, ny, 2, projection=ccrs.OSGB(approx=False))
ax = fig.add_subplot(nx, ny, 2, projection=ccrs.OSGB(approx=False))
ax.set_global()
ax.coastlines(resolution="110m")
ax.gridlines(linestyle=':')

ax = plt.subplot(nx, ny, 3, projection=ccrs.OSGB(approx=False))
ax = fig.add_subplot(nx, ny, 3, projection=ccrs.OSGB(approx=False))
ax.set_global()
ax.coastlines(resolution="110m")
ax.gridlines(ccrs.PlateCarree(), color='blue', linestyle='-')
ax.gridlines(ccrs.OSGB(approx=False), linestyle=':')

ax = plt.subplot(nx, ny, 4, projection=ccrs.PlateCarree())
ax = fig.add_subplot(nx, ny, 4, projection=ccrs.PlateCarree())
ax.set_global()
ax.coastlines(resolution="110m")
ax.gridlines(ccrs.NorthPolarStereo(), alpha=0.5,
linewidth=1.5, linestyle='-')

ax = plt.subplot(nx, ny, 5, projection=ccrs.PlateCarree())
ax = fig.add_subplot(nx, ny, 5, projection=ccrs.PlateCarree())
ax.set_global()
ax.coastlines(resolution="110m")
osgb = ccrs.OSGB(approx=False)
ax.set_extent(tuple(osgb.x_limits) + tuple(osgb.y_limits), crs=osgb)
ax.gridlines(osgb, linestyle=':')

ax = plt.subplot(nx, ny, 6, projection=ccrs.NorthPolarStereo())
ax = fig.add_subplot(nx, ny, 6, projection=ccrs.NorthPolarStereo())
ax.set_global()
ax.coastlines(resolution="110m")
ax.gridlines(alpha=0.5, linewidth=1.5, linestyle='-')

ax = plt.subplot(nx, ny, 7, projection=ccrs.NorthPolarStereo())
ax = fig.add_subplot(nx, ny, 7, projection=ccrs.NorthPolarStereo())
ax.set_global()
ax.coastlines(resolution="110m")
osgb = ccrs.OSGB(approx=False)
ax.set_extent(tuple(osgb.x_limits) + tuple(osgb.y_limits), crs=osgb)
ax.gridlines(osgb, linestyle=':')

ax = plt.subplot(nx, ny, 8,
projection=ccrs.Robinson(central_longitude=135))
ax = fig.add_subplot(nx, ny, 8,
projection=ccrs.Robinson(central_longitude=135))
ax.set_global()
ax.coastlines(resolution="110m")
ax.gridlines(ccrs.PlateCarree(), alpha=0.5, linewidth=1.5, linestyle='-')

delta = 1.5e-2
plt.subplots_adjust(left=0 + delta, right=1 - delta,
fig.subplots_adjust(left=0 + delta, right=1 - delta,
top=1 - delta, bottom=0 + delta)


Expand Down Expand Up @@ -164,7 +164,7 @@ def test_grid_labels():
gl = ax.gridlines(draw_labels=True)
gl.xlabel_style = gl.ylabel_style = {'size': 9}

ax = plt.subplot(3, 2, 4, projection=crs_pc)
ax = fig.add_subplot(3, 2, 4, projection=crs_pc)
ax.coastlines(resolution="110m")
gl = ax.gridlines(
crs=crs_pc, linewidth=2, color='gray', alpha=0.5, linestyle=':')
Expand Down Expand Up @@ -205,7 +205,7 @@ def test_grid_labels():
gl.xlabel_style = gl.ylabel_style = {'size': 9}

# Increase margins between plots to stop them bumping into one another.
plt.subplots_adjust(wspace=0.25, hspace=0.25)
fig.subplots_adjust(wspace=0.25, hspace=0.25)


@pytest.mark.skipif(geos_version == (3, 9, 0), reason="GEOS intersection bug")
Expand Down Expand Up @@ -253,17 +253,17 @@ def test_grid_labels_tight():
@pytest.mark.natural_earth
@ImageTesting([grid_label_inline_image], tolerance=grid_label_inline_tol)
def test_grid_labels_inline():
plt.figure(figsize=(35, 35))
fig = plt.figure(figsize=(35, 35))
for i, proj in enumerate(TEST_PROJS, 1):
if isinstance(proj, tuple):
proj, kwargs = proj
else:
kwargs = {}
ax = plt.subplot(7, 4, i, projection=proj(**kwargs))
ax = fig.add_subplot(7, 4, i, projection=proj(**kwargs))
ax.gridlines(draw_labels=True, auto_inline=True)
ax.coastlines(resolution="110m")
ax.set_title(proj, y=1.075)
plt.subplots_adjust(wspace=0.35, hspace=0.35)
fig.subplots_adjust(wspace=0.35, hspace=0.35)


@pytest.mark.skipif(geos_version == (3, 9, 0), reason="GEOS intersection bug")
Expand All @@ -275,13 +275,13 @@ def test_grid_labels_inline_usa():
left = -124.7844079 # west long
right = -66.9513812 # east long
bottom = 24.7433195 # south lat
plt.figure(figsize=(35, 35))
fig = plt.figure(figsize=(35, 35))
for i, proj in enumerate(TEST_PROJS, 1):
if isinstance(proj, tuple):
proj, kwargs = proj
else:
kwargs = {}
ax = plt.subplot(7, 4, i, projection=proj(**kwargs))
ax = fig.add_subplot(7, 4, i, projection=proj(**kwargs))
try:
ax.set_extent([left, right, bottom, top],
crs=ccrs.PlateCarree())
Expand All @@ -291,7 +291,7 @@ def test_grid_labels_inline_usa():
ax.gridlines(draw_labels=True, auto_inline=True, clip_on=True)
ax.coastlines(resolution="110m")

plt.subplots_adjust(wspace=0.35, hspace=0.35)
fig.subplots_adjust(wspace=0.35, hspace=0.35)


@pytest.mark.skipif(geos_version == (3, 9, 0), reason="GEOS intersection bug")
Expand All @@ -302,23 +302,21 @@ def test_gridliner_labels_bbox_style():
right = -66.9513812 # east long
bottom = 24.7433195 # south lat

plt.figure(figsize=(6, 3))
ax = plt.subplot(1, 1, 1, projection=ccrs.PlateCarree())
fig = plt.figure(figsize=(6, 3))
ax = fig.add_subplot(1, 1, 1, projection=ccrs.PlateCarree())
ax.coastlines(resolution="110m")
ax.set_extent([left, right, bottom, top],
crs=ccrs.PlateCarree())
gl = ax.gridlines(draw_labels=True)

bbox_style = {
gl.labels_bbox_style = {
"pad": 0,
"visible": True,
"facecolor": "white",
"edgecolor": "black",
"boxstyle": "round, pad=0.2",
}

gl.labels_bbox_style = bbox_style


@pytest.mark.parametrize(
"proj,gcrs,xloc,xfmt,xloc_expected,xfmt_expected",
Expand All @@ -343,16 +341,16 @@ def test_gridliner_labels_bbox_style():
])
def test_gridliner_default_fmtloc(
proj, gcrs, xloc, xfmt, xloc_expected, xfmt_expected):
plt.figure()
ax = plt.subplot(111, projection=proj)
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1, projection=proj)
gl = ax.gridlines(crs=gcrs, draw_labels=False, xlocs=xloc, xformatter=xfmt)
assert isinstance(gl.xlocator, xloc_expected)
assert isinstance(gl.xformatter, xfmt_expected)


def test_gridliner_line_limits():
fig = plt.figure()
ax = plt.subplot(1, 1, 1, projection=ccrs.NorthPolarStereo())
ax = fig.add_subplot(1, 1, 1, projection=ccrs.NorthPolarStereo())
ax.set_global()
# Test a single value passed in which represents (-lim, lim)
xlim, ylim = 125, 75
Expand Down Expand Up @@ -413,7 +411,7 @@ def test_gridliner_line_limits():
def test_gridliner_draw_labels_param(draw_labels, result):
fig = plt.figure()
lambert_crs = ccrs.LambertConformal(central_longitude=105)
ax = plt.axes(projection=lambert_crs)
ax = fig.add_subplot(projection=lambert_crs)
ax.set_extent([75, 130, 18, 54], crs=ccrs.PlateCarree())
gl = ax.gridlines(draw_labels=draw_labels, rotate_labels=False, dms=True,
x_inline=False, y_inline=False)
Expand All @@ -429,7 +427,7 @@ def test_gridliner_draw_labels_param(draw_labels, result):

def test_gridliner_formatter_kwargs():
fig = plt.figure()
ax = plt.subplot(1, 1, 1, projection=ccrs.PlateCarree())
ax = fig.add_subplot(1, 1, 1, projection=ccrs.PlateCarree())
ax.set_extent([-80, -40.0, 10.0, -30.0])
gl = ax.gridlines(draw_labels=True, dms=False,
formatter_kwargs=dict(cardinal_labels={'west': 'O'}))
Expand Down
9 changes: 5 additions & 4 deletions lib/cartopy/tests/mpl/test_images.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,8 +44,9 @@ def test_web_tiles():
[extent[0], extent[3]],
[extent[0], extent[1]]])
map_prj = cimgt.GoogleTiles().crs
fig = plt.figure()

ax = plt.subplot(2, 2, 1, projection=map_prj)
ax = fig.add_subplot(2, 2, 1, projection=map_prj)
gt = cimgt.GoogleTiles()
gt._image_url = types.MethodType(ctest_tiles.GOOGLE_IMAGE_URL_REPLACEMENT,
gt)
Expand All @@ -54,14 +55,14 @@ def test_web_tiles():
interpolation='bilinear', origin=origin)
ax.coastlines(color='white')

ax = plt.subplot(2, 2, 2, projection=map_prj)
ax = fig.add_subplot(2, 2, 2, projection=map_prj)
qt = cimgt.QuadtreeTiles()
img, extent, origin = qt.image_for_domain(target_domain, 1)
ax.imshow(np.array(img), extent=extent, transform=qt.crs,
interpolation='bilinear', origin=origin)
ax.coastlines(color='white')

ax = plt.subplot(2, 2, 3, projection=map_prj)
ax = fig.add_subplot(2, 2, 3, projection=map_prj)
osm = cimgt.OSM()
img, extent, origin = osm.image_for_domain(target_domain, 1)
ax.imshow(np.array(img), extent=extent, transform=osm.crs,
Expand Down Expand Up @@ -94,7 +95,7 @@ def test_image_merge():
ax = plt.axes(projection=gt.crs)
ax.set_global()
ax.coastlines()
plt.imshow(img, origin=origin, extent=extent, alpha=0.5)
ax.imshow(img, origin=origin, extent=extent, alpha=0.5)


@ImageTesting(['imshow_natural_earth_ortho'], tolerance=0.7)
Expand Down
14 changes: 7 additions & 7 deletions lib/cartopy/tests/mpl/test_img_transform.py
Original file line number Diff line number Diff line change
Expand Up @@ -106,20 +106,20 @@ def test_regrid_image():
target_proj, target_x, target_y)

# Plot
plt.figure(figsize=(10, 10))
fig = plt.figure(figsize=(10, 10))
gs = mpl.gridspec.GridSpec(nrows=4, ncols=1,
hspace=1.5, wspace=0.5)
# Set up axes and title
ax = plt.subplot(gs[0], projection=target_proj)
plt.imshow(new_array, origin='lower', extent=target_extent)
ax = fig.add_subplot(gs[0], projection=target_proj)
ax.imshow(new_array, origin='lower', extent=target_extent)
ax.coastlines()
# Plot each color slice (tests masking)
cmaps = {'red': 'Reds', 'green': 'Greens', 'blue': 'Blues'}
for i, color in enumerate(['red', 'green', 'blue']):
ax = plt.subplot(gs[i + 1], projection=target_proj)
plt.imshow(new_array[:, :, i], extent=target_extent, origin='lower',
cmap=cmaps[color])
ax = fig.add_subplot(gs[i + 1], projection=target_proj)
ax.imshow(new_array[:, :, i], extent=target_extent, origin='lower',
cmap=cmaps[color])
ax.coastlines()

# Tighten up layout
gs.tight_layout(plt.gcf())
gs.tight_layout(fig)
Loading

0 comments on commit 7824dc4

Please sign in to comment.