Skip to content

Commit

Permalink
Merge pull request #1473 from dopplershift/python3-ify
Browse files Browse the repository at this point in the history
Modernize for Python 3 a bit more
  • Loading branch information
dopplershift authored Aug 25, 2020
2 parents a9b5427 + 38c43f5 commit 931c114
Show file tree
Hide file tree
Showing 31 changed files with 95 additions and 106 deletions.
3 changes: 0 additions & 3 deletions docs/override_check.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,6 @@
#
# Verifies that any modules present in the _templates/overrides directory have all of their
# their exported functions included in the doc file.

from __future__ import print_function

import glob
import importlib
import os
Expand Down
2 changes: 1 addition & 1 deletion examples/Four_Panel_Map.py
Original file line number Diff line number Diff line change
Expand Up @@ -107,7 +107,7 @@ def plot_background(ax):
transform=ccrs.PlateCarree(), zorder=0)
axlist[2].set_title('Surface Temperatures', fontsize=16)
cb3 = fig.colorbar(cf3, ax=axlist[2], orientation='horizontal', shrink=0.74, pad=0)
cb3.set_label(u'\N{DEGREE FAHRENHEIT}', size='x-large')
cb3.set_label('\N{DEGREE FAHRENHEIT}', size='x-large')

# Lower right plot - precipitable water entire atmosphere
cf4 = axlist[3].contourf(lon_2d, lat_2d, precip_water, cmap='Greens',
Expand Down
2 changes: 1 addition & 1 deletion examples/formats/NEXRAD_Level_3_File.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@
('NWS8bitVel', -100, 1.0)) # m/s
for v, ctable, ax in zip(('N0Q', 'N0U'), ctables, axes):
# Open the file
name = get_test_data('nids/KOUN_SDUS54_{}TLX_201305202016'.format(v), as_file_obj=False)
name = get_test_data(f'nids/KOUN_SDUS54_{v}TLX_201305202016', as_file_obj=False)
f = Level3File(name)

# Pull the data out of the file object
Expand Down
18 changes: 8 additions & 10 deletions examples/gridding/Inverse_Distance_Verification.py
Original file line number Diff line number Diff line change
Expand Up @@ -101,8 +101,8 @@ def draw_circle(ax, x, y, r, m, label):
draw_circle(ax, sim_gridx[0], sim_gridy[0], m='k-', r=radius, label='grid 0 radius')
draw_circle(ax, sim_gridx[1], sim_gridy[1], m='b-', r=radius, label='grid 1 radius')

ax.annotate('grid 0: cressman {:.3f}'.format(cress_val), xy=(sim_gridx[0] + 2, sim_gridy[0]))
ax.annotate('grid 1: barnes {:.3f}'.format(barnes_val), xy=(sim_gridx[1] + 2, sim_gridy[1]))
ax.annotate(f'grid 0: cressman {cress_val:.3f}', xy=(sim_gridx[0] + 2, sim_gridy[0]))
ax.annotate(f'grid 1: barnes {barnes_val:.3f}', xy=(sim_gridx[1] + 2, sim_gridy[1]))

ax.set_aspect('equal', 'datalim')
ax.legend()
Expand All @@ -114,8 +114,7 @@ def draw_circle(ax, x, y, r, m, label):
# Plot the grid point, observations within radius of the grid point, their locations, and
# their distances from the grid point.
fig, ax = plt.subplots(1, 1, figsize=(15, 10))
ax.annotate('grid 0: ({}, {})'.format(sim_gridx[0], sim_gridy[0]),
xy=(sim_gridx[0] + 2, sim_gridy[0]))
ax.annotate(f'grid 0: ({sim_gridx[0]}, {sim_gridy[0]})', xy=(sim_gridx[0] + 2, sim_gridy[0]))
ax.plot(sim_gridx[0], sim_gridy[0], '+', markersize=10)

mx, my = obs_tree.data[indices[0]].T
Expand All @@ -128,8 +127,8 @@ def draw_circle(ax, x, y, r, m, label):
xave = np.mean([sim_gridx[0], x])
yave = np.mean([sim_gridy[0], y])

ax.annotate('distance: {}'.format(d), xy=(xave, yave))
ax.annotate('({}, {}) : {} F'.format(x, y, z), xy=(x, y))
ax.annotate(f'distance: {d}', xy=(xave, yave))
ax.annotate(f'({x}, {y}) : {z} F', xy=(x, y))

ax.set_xlim(0, 80)
ax.set_ylim(0, 80)
Expand All @@ -154,8 +153,7 @@ def draw_circle(ax, x, y, r, m, label):
# Now repeat for grid 1, except use barnes interpolation.

fig, ax = plt.subplots(1, 1, figsize=(15, 10))
ax.annotate('grid 1: ({}, {})'.format(sim_gridx[1], sim_gridy[1]),
xy=(sim_gridx[1] + 2, sim_gridy[1]))
ax.annotate(f'grid 1: ({sim_gridx[1]}, {sim_gridy[1]})', xy=(sim_gridx[1] + 2, sim_gridy[1]))
ax.plot(sim_gridx[1], sim_gridy[1], '+', markersize=10)

mx, my = obs_tree.data[indices[1]].T
Expand All @@ -168,8 +166,8 @@ def draw_circle(ax, x, y, r, m, label):
xave = np.mean([sim_gridx[1], x])
yave = np.mean([sim_gridy[1], y])

ax.annotate('distance: {}'.format(d), xy=(xave, yave))
ax.annotate('({}, {}) : {} F'.format(x, y, z), xy=(x, y))
ax.annotate(f'distance: {d}', xy=(xave, yave))
ax.annotate(f'({x}, {y}) : {z} F', xy=(x, y))

ax.set_xlim(40, 80)
ax.set_ylim(40, 100)
Expand Down
15 changes: 7 additions & 8 deletions examples/gridding/Natural_Neighbor_Verification.py
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@
delaunay_plot_2d(tri, ax=ax)

for i, zval in enumerate(zp):
ax.annotate('{} F'.format(zval), xy=(pts[i, 0] + 2, pts[i, 1]))
ax.annotate(f'{zval} F', xy=(pts[i, 0] + 2, pts[i, 1]))

sim_gridx = [30., 60.]
sim_gridy = [30., 60.]
Expand All @@ -94,11 +94,11 @@

val = natural_neighbor_point(xp, yp, zp, (sim_gridx[0], sim_gridy[0]), tri, members[0],
circumcenters)
ax.annotate('grid 0: {:.3f}'.format(val), xy=(sim_gridx[0] + 2, sim_gridy[0]))
ax.annotate(f'grid 0: {val:.3f}', xy=(sim_gridx[0] + 2, sim_gridy[0]))

val = natural_neighbor_point(xp, yp, zp, (sim_gridx[1], sim_gridy[1]), tri, members[1],
circumcenters)
ax.annotate('grid 1: {:.3f}'.format(val), xy=(sim_gridx[1] + 2, sim_gridy[1]))
ax.annotate(f'grid 1: {val:.3f}', xy=(sim_gridx[1] + 2, sim_gridy[1]))


###########################################
Expand Down Expand Up @@ -173,16 +173,15 @@ def draw_circle(ax, x, y, r, m, label):
y_0 = yp[nn_ind]

for x, y, z in zip(x_0, y_0, z_0):
ax.annotate('{}, {}: {:.3f} F'.format(x, y, z), xy=(x, y))
ax.annotate(f'{x}, {y}: {z:.3f} F', xy=(x, y))

ax.plot(sim_gridx[0], sim_gridy[0], 'k+', markersize=10)
ax.annotate('{}, {}'.format(sim_gridx[0], sim_gridy[0]), xy=(sim_gridx[0] + 2, sim_gridy[0]))
ax.annotate(f'{sim_gridx[0]}, {sim_gridy[0]}', xy=(sim_gridx[0] + 2, sim_gridy[0]))
ax.plot(cc[:, 0], cc[:, 1], 'ks', markersize=15, fillstyle='none',
label='natural neighbor\ncircumcenters')

for center in cc:
ax.annotate('{:.3f}, {:.3f}'.format(center[0], center[1]),
xy=(center[0] + 1, center[1] + 1))
ax.annotate(f'{center[0]:.3f}, {center[1]:.3f}', xy=(center[0] + 1, center[1] + 1))

tris = tri.points[tri.simplices[members[0]]]
for triangle in tris:
Expand All @@ -202,7 +201,7 @@ def draw_polygon_with_info(ax, polygon, off_x=0, off_y=0):
[pt[1], pts[(i + 1) % len(pts)][1]], 'k-')

avex, avey = np.mean(pts, axis=0)
ax.annotate('area: {:.3f}'.format(geometry.area(pts)), xy=(avex + off_x, avey + off_y),
ax.annotate(f'area: {geometry.area(pts):.3f}', xy=(avex + off_x, avey + off_y),
fontsize=12)


Expand Down
20 changes: 10 additions & 10 deletions examples/isentropic_example.py
Original file line number Diff line number Diff line change
Expand Up @@ -127,13 +127,13 @@
clevisent = np.arange(0, 1000, 25)
cs = ax.contour(lon, lat, isentprs[level, :, :], clevisent,
colors='k', linewidths=1.0, linestyles='solid', transform=ccrs.PlateCarree())
ax.clabel(cs, fontsize=10, inline=1, inline_spacing=7,
fmt='%i', rightside_up=True, use_clabeltext=True)
cs.clabel(fontsize=10, inline=1, inline_spacing=7, fmt='%i', rightside_up=True,
use_clabeltext=True)

# Plot RH
cf = ax.contourf(lon, lat, isentrh[level, :, :], range(10, 106, 5),
cmap=plt.cm.gist_earth_r, transform=ccrs.PlateCarree())
cb = fig.colorbar(cf, orientation='horizontal', extend='max', aspect=65, shrink=0.5, pad=0.05,
cb = fig.colorbar(cf, orientation='horizontal', aspect=65, shrink=0.5, pad=0.05,
extendrect='True')
cb.set_label('Relative Humidity', size='x-large')

Expand All @@ -142,8 +142,8 @@
regrid_shape=20, transform=ccrs.PlateCarree())

# Make some titles
ax.set_title('{:.0f} K Isentropic Pressure (hPa), Wind (kt), Relative Humidity (percent)'
.format(isentlevs[level].m), loc='left')
ax.set_title(f'{isentlevs[level]:~.0f} Isentropic Pressure (hPa), Wind (kt), '
'Relative Humidity (percent)', loc='left')
add_timestamp(ax, times[0].values.astype('datetime64[ms]').astype('O'),
y=0.02, high_contrast=True)
fig.tight_layout()
Expand Down Expand Up @@ -173,13 +173,13 @@
clevmsf = np.arange(0, 4000, 5)
cs = ax.contour(lon, lat, msf[level, :, :], clevmsf,
colors='k', linewidths=1.0, linestyles='solid', transform=ccrs.PlateCarree())
ax.clabel(cs, fontsize=10, inline=1, inline_spacing=7,
fmt='%i', rightside_up=True, use_clabeltext=True)
cs.clabel(fontsize=10, inline=1, inline_spacing=7, fmt='%i', rightside_up=True,
use_clabeltext=True)

# Plot RH
cf = ax.contourf(lon, lat, isentrh[level, :, :], range(10, 106, 5),
cmap=plt.cm.gist_earth_r, transform=ccrs.PlateCarree())
cb = fig.colorbar(cf, orientation='horizontal', extend='max', aspect=65, shrink=0.5, pad=0.05,
cb = fig.colorbar(cf, orientation='horizontal', aspect=65, shrink=0.5, pad=0.05,
extendrect='True')
cb.set_label('Relative Humidity', size='x-large')

Expand All @@ -188,8 +188,8 @@
regrid_shape=20, transform=ccrs.PlateCarree())

# Make some titles
ax.set_title('{:.0f} K Montgomery Streamfunction '.format(isentlevs[level].m)
+ r'($10^{-2} m^2 s^{-2}$), Wind (kt), Relative Humidity (percent)', loc='left')
ax.set_title(f'{isentlevs[level]:~.0f} Montgomery Streamfunction '
r'($10^{-2} m^2 s^{-2}$), Wind (kt), Relative Humidity (percent)', loc='left')
add_timestamp(ax, times[0].values.astype('datetime64[ms]').astype('O'),
y=0.02, pretext='Valid: ', high_contrast=True)

Expand Down
4 changes: 2 additions & 2 deletions examples/meteogram_metpy.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ def calc_mslp(t, p, h):


# Make meteogram plot
class Meteogram(object):
class Meteogram:
""" Plot a time series of meteorological data from a particular station as a
meteogram with standard variables to visualize, including thermodynamic,
kinematic, and pressure. The functions below control the plotting of each
Expand All @@ -51,7 +51,7 @@ def __init__(self, fig, dates, probeid, time=None, axis=0):
self.axis_num = 0
self.dates = mpl.dates.date2num(dates)
self.time = time.strftime('%Y-%m-%d %H:%M UTC')
self.title = 'Latest Ob Time: {0}\nProbe ID: {1}'.format(self.time, probeid)
self.title = f'Latest Ob Time: {self.time}\nProbe ID: {probeid}'

def plot_winds(self, ws, wd, wsmax, plot_range=None):
"""
Expand Down
13 changes: 6 additions & 7 deletions examples/sigma_to_pressure_interpolation.py
Original file line number Diff line number Diff line change
Expand Up @@ -74,24 +74,23 @@
# Plot the heights
cs = ax.contour(lon, lat, height[FH, 0, :, :], transform=ccrs.PlateCarree(),
colors='k', linewidths=1.0, linestyles='solid')
ax.clabel(cs, fontsize=10, inline=1, inline_spacing=7,
fmt='%i', rightside_up=True, use_clabeltext=True)
cs.clabel(fontsize=10, inline=1, inline_spacing=7, fmt='%i', rightside_up=True,
use_clabeltext=True)

# Contour the temperature
cf = ax.contourf(lon, lat, temp[FH, 0, :, :], range(-20, 20, 1), cmap=plt.cm.RdBu_r,
transform=ccrs.PlateCarree())
cb = fig.colorbar(cf, orientation='horizontal', extend='max', aspect=65, shrink=0.5,
pad=0.05, extendrect='True')
cb = fig.colorbar(cf, orientation='horizontal', aspect=65, shrink=0.5, pad=0.05,
extendrect='True')
cb.set_label('Celsius', size='x-large')

ax.set_extent([-106.5, -90.4, 34.5, 46.75], crs=ccrs.PlateCarree())

# Make the axis title
ax.set_title('{:.0f} hPa Heights (m) and Temperature (C)'.format(plevs[0].m), loc='center',
fontsize=10)
ax.set_title(f'{plevs[0]:~.0f} Heights (m) and Temperature (C)', loc='center', fontsize=10)

# Set the figure title
fig.suptitle('WRF-ARW Forecast VALID: {:s} UTC'.format(str(vtimes[FH])), fontsize=14)
fig.suptitle(f'WRF-ARW Forecast VALID: {vtimes[FH]} UTC', fontsize=14)
add_timestamp(ax, vtimes[FH], y=0.02, high_contrast=True)

plt.show()
2 changes: 1 addition & 1 deletion src/metpy/calc/tools.py
Original file line number Diff line number Diff line change
Expand Up @@ -176,7 +176,7 @@ def find_intersections(x, a, b, direction='all', log_x=False):
elif direction == 'all':
return intersect_x[duplicate_mask], intersect_y[duplicate_mask]
else:
raise ValueError('Unknown option for direction: {0}'.format(str(direction)))
raise ValueError(f'Unknown option for direction: {direction}')

return intersect_x[mask & duplicate_mask], intersect_y[mask & duplicate_mask]

Expand Down
2 changes: 1 addition & 1 deletion src/metpy/cbook.py
Original file line number Diff line number Diff line change
Expand Up @@ -109,7 +109,7 @@ def result_type(value):
elif hasattr(value, 'magnitude'):
return np.result_type(value.magnitude)
else:
raise TypeError('Cannot determine dtype for type {}'.format(type(value)))
raise TypeError(f'Cannot determine dtype for type {type(value)}')


__all__ = ('Registry', 'broadcast_indices', 'get_test_data', 'iterable', 'result_type')
2 changes: 1 addition & 1 deletion src/metpy/deprecation.py
Original file line number Diff line number Diff line change
Expand Up @@ -140,7 +140,7 @@ def _generate_deprecation_message(since, message='', name='',

altmessage = ''
if alternative:
altmessage = ' Use {} instead.'.format(alternative)
altmessage = f' Use {alternative} instead.'

message = message + altmessage

Expand Down
2 changes: 1 addition & 1 deletion src/metpy/interpolate/one_dimension.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ def interpolate_nans_1d(x, y, kind='linear'):
elif kind == 'log':
y[nans] = np.interp(np.log(x[nans]), np.log(x[~nans]), y[~nans])
else:
raise ValueError('Unknown option for kind: {0}'.format(str(kind)))
raise ValueError(f'Unknown option for kind: {kind}')
return y[x_sort_args]


Expand Down
12 changes: 6 additions & 6 deletions src/metpy/io/_tools.py
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,7 @@ def unpack_from(self, buff, offset=0):
return self._create(super().unpack_from(buff, offset))


class Enum(object):
class Enum:
"""Map values to specific strings."""

def __init__(self, *args, **kwargs):
Expand All @@ -114,10 +114,10 @@ def __init__(self, *args, **kwargs):

def __call__(self, val):
"""Map an integer to the string representation."""
return self.val_map.get(val, 'Unknown ({})'.format(val))
return self.val_map.get(val, f'Unknown ({val})')


class Bits(object):
class Bits:
"""Breaks an integer into a specified number of True/False bits."""

def __init__(self, num_bits):
Expand All @@ -129,7 +129,7 @@ def __call__(self, val):
return [bool((val >> i) & 0x1) for i in self._bits]


class BitField(object):
class BitField:
"""Convert an integer to a string for each bit."""

def __init__(self, *names):
Expand All @@ -153,7 +153,7 @@ def __call__(self, val):
return bits[0] if len(bits) == 1 else bits


class Array(object):
class Array:
"""Use a Struct as a callable to unpack a bunch of bytes as a list."""

def __init__(self, fmt):
Expand All @@ -165,7 +165,7 @@ def __call__(self, buf):
return list(self._struct.unpack(buf))


class IOBuffer(object):
class IOBuffer:
"""Holds bytes from a buffer to simplify parsing and random access."""

def __init__(self, source):
Expand Down
2 changes: 1 addition & 1 deletion src/metpy/io/gini.py
Original file line number Diff line number Diff line change
Expand Up @@ -269,7 +269,7 @@ def _make_proj_var(self):
attrs['standard_parallel'] = prod_desc2.lat_in
else:
raise NotImplementedError(
'Unhandled GINI Projection: {}'.format(self.prod_desc.projection))
f'Unhandled GINI Projection: {self.prod_desc.projection}')

return 'projection', Variable((), 0, attrs)

Expand Down
Loading

0 comments on commit 931c114

Please sign in to comment.