Skip to content

Commit 317000a

Browse files
author
Jeff Whitaker
committed
Merge pull request #39 from jswhit/master
python 3 compatibility fixes (mostly for examples)
2 parents 6f9a3ed + 1656f19 commit 317000a

30 files changed

+189
-149
lines changed

Changelog

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
1-
version 1.0.3 (not yet released)
2-
--------------------------------
1+
version 1.0.3 (git tag v1.0.3)
2+
------------------------------
3+
* fix some more python 3 compatibility issues (all examples now
4+
work with python 3.2).
35
* added alpha keyword to fillcontinents (to set transparency).
46
* update geos from 3.3.1 to 3.3.3.
57
* upgrade proj4 source to version 4.8.0, pyproj to version 1.9.2.

examples/allskymap.py

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
from __future__ import unicode_literals
12
"""
23
AllSkyMap is a subclass of Basemap, specialized for handling common plotting
34
tasks for celestial data.
@@ -35,9 +36,9 @@ def angle_symbol(angle, round_to=1.0):
3536
"""
3637
value = np.round(angle / round_to) * round_to
3738
if pl.rcParams['text.usetex'] and not pl.rcParams['text.latex.unicode']:
38-
return r"$%0.0f^\circ$" % value
39+
return r'$%0.0f^\circ$' % value
3940
else:
40-
return u"%0.0f\u00b0" % value
41+
return '%0.0f\N{DEGREE SIGN}' % value
4142

4243

4344
class AllSkyMap(Basemap):
@@ -224,7 +225,7 @@ def geodesic(self, lon1, lat1, lon2, lat2, del_s=.01, clip=True, **kwargs):
224225
# If there are multiple segments and no color args, reconcile the
225226
# colors, which mpl will have autoset to different values.
226227
# *** Does this screw up mpl's color set sequence for later lines?
227-
if not kwargs.has_key('c') or kwargs.has_key('color'):
228+
if 'c' not in kwargs or 'color' in kwargs:
228229
if len(lines) > 1:
229230
c1 = lines[0].get_color()
230231
for line in lines[1:]:

examples/allskymap_cr_example.py

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -10,10 +10,13 @@
1010
Created 2011-02-07 by Tom Loredo
1111
"""
1212

13-
from cStringIO import StringIO
13+
try:
14+
from cStringIO import StringIO
15+
except:
16+
from io import StringIO
1417
import numpy as np
1518
from numpy import cos, sin, arccos, deg2rad, rad2deg
16-
import csv, re
19+
import csv, re, sys
1720

1821
import matplotlib.pyplot as plt
1922
from allskymap import AllSkyMap
@@ -110,7 +113,7 @@ def gcangle(self, src):
110113
# Make an integer ID from Year+Day (presumes none on same day!).
111114
src = Source(id, row[0], row[1], row[7], row[8], E=float(row[4]))
112115
CRs[src.id] = src
113-
print 'Parsed data for', len(CRs), 'UHE CRs...'
116+
sys.stdout.write('Parsed data for %s UHE CRs...\n'%len(CRs))
114117

115118
# Partly fictitious candidate source locations.
116119
# src.id src.l_deg src.b_deg src.xProj src.yProj
@@ -141,7 +144,7 @@ def gcangle(self, src):
141144
for row in CandTable:
142145
src = Source(row[0], 0, 0, row[1], row[2])
143146
cands[src.id] = src
144-
print 'Parsed data for', len(cands), 'candidate sources...'
147+
sys.stdout.write('Parsed data for %s candidate sources...\n' % len(cands))
145148

146149
# Calculate the separation matrix; track the closest candidate to each CR.
147150
sepn = {}

examples/animate.py

Lines changed: 1 addition & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -12,25 +12,20 @@
1212
# times for March 1993 'storm of the century'
1313
date1 = datetime.datetime(1993,3,10,0)
1414
date2 = datetime.datetime(1993,3,17,0)
15-
print date1, date2
1615

1716
# set OpenDAP server URL.
1817
URL="http://nomad2.ncep.noaa.gov:9090/dods/reanalyses/reanalysis-2/6hr/pgb/pgb"
19-
print URL
2018
try:
2119
data = NetCDFFile(URL)
2220
except:
23-
raise IOError, 'opendap server not providing the requested data'
21+
raise IOError('opendap server not providing the requested data')
2422

2523
# read lats,lons,times.
26-
print data.variables.keys()
2724
latitudes = data.variables['lat'][:]
2825
longitudes = data.variables['lon'][:].tolist()
2926
times = data.variables['time']
3027
ntime1 = date2index(date1,times,calendar='standard')
3128
ntime2 = date2index(date2,times,calendar='standard')
32-
print 'ntime1,ntime2:',ntime1,ntime2
33-
print num2date(times[ntime1],times.units,calendar='standard'), num2date(times[ntime2],times.units,calendar='standard')
3429
# get sea level pressure and 10-m wind data.
3530
slpdata = data.variables['presmsl']
3631
udata = data.variables['ugrdprs']
@@ -50,12 +45,6 @@
5045
longitudes.append(360.); longitudes = np.array(longitudes)
5146
# make 2-d grid of lons, lats
5247
lons, lats = np.meshgrid(longitudes,latitudes)
53-
print 'min/max slp,u,v'
54-
print slp.min(), slp.max()
55-
print uin.min(), uin.max()
56-
print vin.min(), vin.max()
57-
print 'dates'
58-
print dates
5948
# make orthographic basemap.
6049
m = Basemap(resolution='c',projection='ortho',lat_0=60.,lon_0=-60.)
6150
uin = udata[ntime1:ntime2+1,0,:,:]

examples/contour_demo.py

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
from mpl_toolkits.basemap import Basemap, shiftgrid
22
import numpy as np
33
import matplotlib.pyplot as plt
4+
import sys
45

56
# examples of filled contour plots on map projections.
67

@@ -34,7 +35,7 @@
3435
meridians = np.arange(-360.,360.,30.)
3536
m.drawmeridians(meridians)
3637
plt.title('Sinusoidal Filled Contour Demo')
37-
print 'plotting with sinusoidal basemap ...'
38+
sys.stdout.write('plotting with sinusoidal basemap ...\n')
3839

3940
# create new figure
4041
fig=plt.figure()
@@ -56,7 +57,7 @@
5657
meridians = np.arange(-360.,360.,30.)
5758
m.drawmeridians(meridians)
5859
plt.title('Mollweide Filled Contour Demo')
59-
print 'plotting with mollweide basemap ...'
60+
sys.stdout.write('plotting with mollweide basemap ...\n')
6061

6162
# create new figure
6263
fig=plt.figure()
@@ -78,7 +79,7 @@
7879
meridians = np.arange(-360.,360.,60.)
7980
m.drawmeridians(meridians,labels=[0,0,0,1])
8081
plt.title('Robinson Filled Contour Demo')
81-
print 'plotting with robinson basemap ...'
82+
sys.stdout.write('plotting with robinson basemap ...\n')
8283

8384
# create new figure
8485
fig=plt.figure()
@@ -100,7 +101,7 @@
100101
meridians = np.arange(10.,360.,20.)
101102
m.drawmeridians(meridians,labels=[1,1,1,1])
102103
plt.title('Azimuthal Equidistant Filled Contour Demo',y=1.075)
103-
print 'plotting with azimuthal equidistant basemap ...'
104+
sys.stdout.write('plotting with azimuthal equidistant basemap ...\n')
104105

105106
# create new figure
106107
fig=plt.figure()
@@ -123,5 +124,5 @@
123124
meridians = np.arange(0.,360.,20.)
124125
m.drawmeridians(meridians)
125126
plt.title('Orthographic Filled Contour Demo')
126-
print 'plotting with orthographic basemap ..'
127+
sys.stdout.write('plotting with orthographic basemap ..\n')
127128
plt.show()

examples/fcstmaps.py

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
from __future__ import print_function
2+
from __future__ import unicode_literals
13
# this example reads today's numerical weather forecasts
24
# from the NOAA OpenDAP servers and makes a multi-panel plot.
35
import numpy as np
@@ -29,12 +31,12 @@
2931
msg = """
3032
opendap server not providing the requested data.
3133
Try another date by providing YYYYMMDD on command line."""
32-
raise IOError, msg
34+
raise IOError(msg)
3335

3436

3537
# read lats,lons,times.
3638

37-
print data.variables.keys()
39+
print(data.variables.keys())
3840
latitudes = data.variables['lat']
3941
longitudes = data.variables['lon']
4042
fcsttimes = data.variables['time']
@@ -49,8 +51,8 @@
4951
for fdate in fdates:
5052
fdiff = fdate-fdates[0]
5153
fcsthrs.append(fdiff.days*24. + fdiff.seconds/3600.)
52-
print fcsthrs
53-
print verifdates
54+
print(fcsthrs)
55+
print(verifdates)
5456
lats = latitudes[:]
5557
nlats = len(lats)
5658
lons1 = longitudes[:]
@@ -85,7 +87,7 @@
8587
plt.title('%d-h forecast valid '%fcsthr+verifdates[nt],fontsize=9)
8688
# figure title
8789
plt.figtext(0.5,0.95,
88-
u"2-m temp (\N{DEGREE SIGN}C) forecasts from %s"%verifdates[0],
90+
"2-m temp (\N{DEGREE SIGN}C) forecasts from %s"%verifdates[0],
8991
horizontalalignment='center',fontsize=14)
9092
# a single colorbar.
9193
cax = plt.axes([0.1, 0.05, 0.8, 0.025])

examples/fcstmaps_axesgrid.py

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
from __future__ import print_function
12
# this example reads today's numerical weather forecasts
23
# from the NOAA OpenDAP servers and makes a multi-panel plot.
34
# This version demonstrates the use of the AxesGrid toolkit.
@@ -31,12 +32,12 @@
3132
msg = """
3233
opendap server not providing the requested data.
3334
Try another date by providing YYYYMMDD on command line."""
34-
raise IOError, msg
35+
raise IOError(msg)
3536

3637

3738
# read lats,lons,times.
3839

39-
print data.variables.keys()
40+
print(data.variables.keys())
4041
latitudes = data.variables['lat']
4142
longitudes = data.variables['lon']
4243
fcsttimes = data.variables['time']
@@ -51,8 +52,8 @@
5152
for fdate in fdates:
5253
fdiff = fdate-fdates[0]
5354
fcsthrs.append(fdiff.days*24. + fdiff.seconds/3600.)
54-
print fcsthrs
55-
print verifdates
55+
print(fcsthrs)
56+
print(verifdates)
5657
lats = latitudes[:]
5758
nlats = len(lats)
5859
lons1 = longitudes[:]
@@ -99,7 +100,7 @@
99100
ax.set_title('%d-h forecast valid '%fcsthr+verifdates[nt],fontsize=9)
100101
# figure title
101102
plt.figtext(0.5,0.95,
102-
u"2-m temp (\N{DEGREE SIGN}C) forecasts from %s"%verifdates[0],
103+
"2-m temp (\N{DEGREE SIGN}C) forecasts from %s"%verifdates[0],
103104
horizontalalignment='center',fontsize=14)
104105
# a single colorbar.
105106
cbar = fig.colorbar(cs, cax=grid.cbar_axes[0], orientation='horizontal')

examples/fillstates.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
from __future__ import print_function
12
import numpy as np
23
import matplotlib.pyplot as plt
34
from mpl_toolkits.basemap import Basemap as Basemap
@@ -64,13 +65,13 @@
6465
'Montana': 2.39,
6566
'Wyoming': 1.96,
6667
'Alaska': 0.42}
67-
print shp_info
68+
print(shp_info)
6869
# choose a color for each state based on population density.
6970
colors={}
7071
statenames=[]
7172
cmap = plt.cm.hot # use 'hot' colormap
7273
vmin = 0; vmax = 450 # set range.
73-
print m.states_info[0].keys()
74+
print(m.states_info[0].keys())
7475
for shapedict in m.states_info:
7576
statename = shapedict['NAME']
7677
# skip DC and Puerto Rico.

examples/garp.py

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,13 @@
11
from mpl_toolkits.basemap import Basemap
22
import numpy as np
33
import matplotlib.pyplot as plt
4+
import sys
5+
6+
def get_input(prompt):
7+
if sys.hexversion > 0x03000000:
8+
return input(prompt)
9+
else:
10+
return raw_input(prompt)
411

512
# the shortest route from the center of the map
613
# to any other point is a straight line in the azimuthal
@@ -12,9 +19,9 @@
1219
# The specified point shows up as a red dot in the center of the map.
1320

1421
# user enters the lon/lat of the point, and it's name
15-
lon_0 = float(raw_input('input reference lon (degrees):'))
16-
lat_0 = float(raw_input('input reference lat (degrees):'))
17-
location = raw_input('name of location:')
22+
lon_0 = float(get_input('input reference lon (degrees):'))
23+
lat_0 = float(get_input('input reference lat (degrees):'))
24+
location = get_input('name of location:')
1825

1926
# no width/height or lat/lon corners specified, so whole world
2027
# is plotted in a circle.

examples/geos_demo.py

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,16 @@
11
from mpl_toolkits.basemap import Basemap
22
import numpy as np
33
import matplotlib.pyplot as plt
4+
import sys
5+
6+
def get_input(prompt):
7+
if sys.hexversion > 0x03000000:
8+
return input(prompt)
9+
else:
10+
return raw_input(prompt)
411

512
# create Basemap instance for Geostationary (satellite view) projection.
6-
lon_0 = float(raw_input('enter reference longitude (lon_0):'))
13+
lon_0 = float(get_input('enter reference longitude (lon_0):'))
714

815
# map with land/sea mask plotted
916
fig=plt.figure()

0 commit comments

Comments
 (0)