-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathplot_tile_orograph.py
299 lines (232 loc) · 8.12 KB
/
plot_tile_orograph.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
#########################################################################
#$Id: bld.py 28 2021-01-21 15:10:31Z whuang $
#$Revision: 28 $
#$HeadURL: file:///Users/whuang/.wei_svn_repository/trunk/jedi-build-tools/bld.py $
#$Date: 2021-01-21 08:10:31 -0700 (Thu, 21 Jan 2021) $
#$Author: whuang $
#########################################################################
import getopt
import os, sys
import types
import time
import datetime
import subprocess
import netCDF4
import matplotlib.pyplot as plt
import numpy as np
import matplotlib
import matplotlib.pyplot
from matplotlib import cm
from mpl_toolkits.basemap import Basemap
def cmdout(command):
result = run(command, stdout=PIPE, stderr=PIPE, universal_newlines=True, shell=True)
ostr = result.stdout
return ostr.strip()
#=========================================================================
class GeneratePlot():
def __init__(self, debug=0, output=0):
self.debug = debug
self.output = output
self.set_default()
self.precision = 1
def set_precision(self, precision=1):
self.precision = precision
def set_grid(self, lat, lon):
self.lat = np.array(lat)
self.lon = np.array(lon)
def set_default(self):
self.image_name = 'sample.png'
#cmapname = coolwarm, bwr, rainbow, jet, seismic
#self.cmapname = 'bwr'
#self.cmapname = 'coolwarm'
#self.cmapname = 'rainbow'
self.cmapname = 'jet'
self.obslat = []
self.obslon = []
#self.clevs = np.arange(-0.2, 0.21, 0.01)
#self.cblevs = np.arange(-0.2, 0.3, 0.1)
self.extend = 'both'
self.alpha = 0.5
self.pad = 0.1
self.orientation = 'horizontal'
self.size = 'large'
self.weight = 'bold'
self.labelsize = 'medium'
self.label = 'Time (sec)'
self.title = 'Time (sec)'
def set_clevs(self, clevs=[]):
self.clevs = clevs
def set_cblevs(self, cblevs=[]):
self.cblevs = cblevs
def set_imagename(self, imagename):
self.image_name = imagename
def set_cmapname(self, cmapname):
self.cmapname = cmapname
def set_label(self, label):
self.label = label
def set_title(self, title):
self.title = title
def build_basemap(self):
basemap_dict = {'resolution': 'c', 'projection': 'cyl',
'llcrnrlat': -90.0, 'llcrnrlon': 0.0,
'urcrnrlat': 90.0, 'urcrnrlon': 360.0}
basemap_dict['lat_0'] = 0.0
basemap_dict['lon_0'] = 180.0
basemap = Basemap(**basemap_dict)
return basemap
def create_image(self, plt_obj, savename):
msg = ('Saving image as %s.' % savename)
print(msg)
kwargs = {'transparent': True, 'dpi': 500}
plt_obj.savefig(savename, **kwargs)
def display(self, output=False, image_name=None):
if(output):
if(image_name is None):
image_name=self.image_name
self.plt.tight_layout()
kwargs = {'plt_obj': self.plt, 'savename': image_name}
self.create_image(**kwargs)
else:
self.plt.show()
def plot(self, pvar):
self.basemap = self.build_basemap()
self.plt = matplotlib.pyplot
try:
self.plt.close('all')
self.plt.clf()
except Exception:
pass
self.fig = self.plt.figure()
self.ax = self.plt.subplot()
msg = ('plot variable min: %s, max: %s' % (np.min(pvar), np.max(pvar)))
print(msg)
(self.x, self.y) = self.basemap(self.lon, self.lat)
v1d = np.array(pvar)
print('self.x.shape = ', self.x.shape)
print('self.y.shape = ', self.y.shape)
print('v1d.shape = ', v1d.shape)
#contfill = self.basemap.contourf(self.x, self.y, v1d, tri=True,
# levels=self.clevs, extend=self.extend,
# alpha=self.alpha, cmap=self.cmapname)
contfill = self.plt.tricontourf(self.x, self.y, v1d,
alpha=self.alpha, cmap=self.cmapname)
cb = self.fig.colorbar(contfill, orientation=self.orientation,
pad=self.pad)
cb.set_label(label=self.label, size=self.size, weight=self.weight)
cb.ax.tick_params(labelsize=self.labelsize)
#if(self.precision == 0):
# cb.ax.set_xticklabels(['{:.0f}'.format(x) for x in self.cblevs], minor=False)
#elif(self.precision == 1):
# cb.ax.set_xticklabels(['{:.1f}'.format(x) for x in self.cblevs], minor=False)
#elif(self.precision == 2):
# cb.ax.set_xticklabels(['{:.2f}'.format(x) for x in self.cblevs], minor=False)
#else:
# cb.ax.set_xticklabels(['{:.3f}'.format(x) for x in self.cblevs], minor=False)
self.ax.set_title(self.title)
self.plot_coast_lat_lon_line()
self.display(output=self.output, image_name=self.image_name)
def plot_coast_lat_lon_line(self):
#https://matplotlib.org/basemap/users/geography.html
#map.drawmapboundary(fill_color='aqua')
#map.fillcontinents(color='#cc9955', lake_color='aqua')
#map.drawcounties()
#map.drawstates(color='0.5')
#draw coastlines
color = 'black'
linewidth = 0.5
self.basemap.drawcoastlines(color=color, linewidth=linewidth)
#draw parallels
color = 'green'
linewidth = 0.5
fontsize = 8
dashes = [10, 10]
circles = np.arange(-90,90,30)
self.basemap.drawparallels(np.arange(-90,90,30),labels=[1,1,0,1],
color=color, linewidth=linewidth,
dashes=dashes, fontsize=fontsize)
#draw meridians
color = 'green'
linewidth = 0.5
fontsize = 8
dashes = [10, 10]
meridians = np.arange(0,360,30)
self.basemap.drawmeridians(np.arange(0,360,30),labels=[1,1,0,1],
color=color, linewidth=linewidth,
dashes=dashes, fontsize=fontsize)
#------------------------------------------------------------------
""" TileData """
class TileData:
""" Constructor """
def __init__(self, debug=0, output=0, griddir=None, gridtype='C48'):
""" Initialize class attributes """
self.debug = debug
self.output = output
self.griddir = griddir
self.gridtype = gridtype
if(griddir is None):
print('griddir not defined. Exit.')
sys.exit(-1)
self.datalist = []
self.lon = []
self.lat = []
for n in range(6):
nt = n + 1
datafile = '%s/%s/%s_oro_data.tile%d.nc' %(griddir, gridtype, gridtype, nt)
if(os.path.exists(datafile)):
print('File No %d: %s' %(nt, datafile))
self.datalist.append(datafile)
ncf = netCDF4.Dataset(datafile)
lon = ncf.variables['geolon'][:,:]
lat = ncf.variables['geolat'][:,:]
print('lon.ndim=', lon.ndim)
print('lon.shape=', lon.shape)
print('lon.size=', lon.size)
ny, nx = lon.shape
lonc1d = np.reshape(lon, (nx*ny,))
latc1d = np.reshape(lat, (nx*ny,))
self.lon.extend(lonc1d)
self.lat.extend(latc1d)
ncf.close()
print('len(self.lon) = ', len(self.lon))
print('len(self.lat) = ', len(self.lat))
def get_latlon(self):
return np.array(self.lat), np.array(self.lon)
def get_var(self, varname):
data = []
for datafile in self.datalist:
ncf = netCDF4.Dataset(datafile)
var = ncf.variables[varname][:,:]
ny, nx = var.shape
var1d = np.reshape(var, (nx*ny,))
data.extend(var1d)
ncf.close()
print('len(data) = ', len(data))
return np.array(data)
#--------------------------------------------------------------------------------
if __name__== '__main__':
debug = 1
output = 0
gridtype = 'C96'
griddir = '/work/noaa/gsienkf/weihuang/UFS-RNR-tools/JEDI.FV3-increments/grid'
opts, args = getopt.getopt(sys.argv[1:], '', ['debug=', 'output=', 'gridtype=', 'griddir='])
for o, a in opts:
if o in ('--debug'):
debug = int(a)
elif o in ('--output'):
output = int(a)
elif o in ('--griddir'):
griddir = a
elif o in ('--gridtype'):
gridtype = a
else:
assert False, 'unhandled option'
td = TileData(debug=debug, griddir=griddir, gridtype=gridtype)
lat, lon = td.get_latlon()
orog = td.get_var('orog_filt')
gp = GeneratePlot(debug=debug, output=output)
gp.set_grid(lat, lon)
imgname = 'direct_tile_orog.png'
gp.set_imagename(imgname)
title = 'Orograph (Unit: m)'
gp.set_title(title)
gp.plot(orog)