-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathplot_landda_sfc_tile.py
executable file
·496 lines (423 loc) · 17.6 KB
/
plot_landda_sfc_tile.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
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
#!/usr/bin/env python3
###################################################################### CHJ #####
## Name : plot_landda_sfc_tile.py
## Language : Python 3.7
## Usage : Plot sfc output of land-DA workflow analysis task
## Input files : sfc_data.tile#.nc
## NOAA/EPIC
## History ===============================
## V000: 2024/06/14: Chan-Hoo Jeon : Preliminary version
## V001: 2024/07/15: Chan-Hoo Jeon : add comparison plot
###################################################################### CHJ #####
import os, sys
import numpy as np
import netCDF4 as nc
import cartopy
import cartopy.crs as ccrs
import cartopy.feature as cfeature
import xarray as xr
from scipy.stats import norm
import matplotlib.pyplot as plt
import matplotlib.colors as colors
import matplotlib.ticker
import matplotlib as mpl
from matplotlib.colors import ListedColormap
from mpl_toolkits.axes_grid1 import make_axes_locatable
# HPC machine ('hera','orion')
machine='hera'
print(' You are on', machine)
#### Machine-specific input data ===================================== CHJ =====
# cartopy.config: Natural Earth data for background
# out_fig_dir: directory where the output files are created
if machine=='hera':
cartopy.config['data_dir']='/scratch2/NAGAPE/epic/UFS_Land-DA_Dev/inputs/NaturalEarth'
path_orog="/scratch2/NAGAPE/epic/UFS_Land-DA_Dev/inputs/FV3_fix_tiled/C96"
out_fig_dir="/scratch2/NCEPDEV/fv3-cam/Chan-hoo.Jeon/tools/fv3sar_pre_plot/Fig"
elif machine=='orion' or machine=='hercules':
cartopy.config['data_dir']='/work/noaa/epic/UFS_Land-DA_Dev/inputs/NaturalEarth'
path_orog="/work/noaa/epic/UFS_Land-DA_Dev/inputs/FV3_fix_tiled/C96"
out_fig_dir="/work/noaa/fv3-cam/chjeon/tools/Fig"
else:
sys.exit('ERROR: Required input data are NOT set in this machine !!!')
# Case-dependent input ============================================== CHJ =====
opt_analysis='gsi' # jedi, gdas, gsi
if opt_analysis == 'jedi':
# SFC_1 data:
path_sfc1='/scratch2/NAGAPE/epic/Chan-hoo.Jeon/landda_test/ptmp/test/tmp/DATA_SHARE/20000103'
fn_sfc1_base='20000103.000000.sfc_data.tile'
fn_sfc1_ext='.nc'
# SFC_2 data:
path_sfc2='/scratch2/NAGAPE/epic/Chan-hoo.Jeon/landda_test/ptmp/test/com/landda/v1.2.1/landda.20000103'
fn_sfc2_base='20000103.000000.sfc_data.tile'
fn_sfc2_ext='.nc'
# increment:
path_xainc=path_sfc2
fn_xainc_base='20000103.000000.xainc.sfc_data.tile'
fn_xainc_ext='.nc'
# variable
sfc_var_nm='snwdph' # land-DA (jedi)
elif opt_analysis == 'gdas':
# SFC_1 data:
path_sfc1='/scratch2/NAGAPE/epic/Chan-hoo.Jeon/global-workflow_test/comroot/snow_gdas/gdas.20211220/12/model_data/atmos/restart'
fn_sfc1_base='20211220.180000.sfc_data.tile'
fn_sfc1_ext='.nc'
# SFC_2 data:
path_sfc2='/scratch2/NAGAPE/epic/Chan-hoo.Jeon/global-workflow_test/comroot/snow_gdas/gdas.20211220/18/analysis/snow'
fn_sfc2_base='20211220.180000.sfc_data.tile'
fn_sfc2_ext='.nc'
# increment:
path_xainc=path_sfc2
fn_xainc_base='snowinc.20211220.180000.sfc_data.tile'
fn_xainc_ext='.nc'
# variable
sfc_var_nm='snodl' # global-wflow (gdas)
elif opt_analysis == 'gsi':
# SFC_1 data:
path_sfc1='/scratch2/NAGAPE/epic/Chan-hoo.Jeon/global-workflow_test/stmp/RUNDIRS/snow_gsi/gdasfcst.2021122018/fcst.1233933/INPUT'
fn_sfc1_base='sfc_data.tile'
fn_sfc1_ext='.nc'
# SFC_2 data:
path_sfc2='/scratch2/NAGAPE/epic/Chan-hoo.Jeon/global-workflow_test/comroot/snow_gsi/gdas.20211220/18/model_data/atmos/restart'
fn_sfc2_base='20211220.210000.sfc_data.tile'
fn_sfc2_ext='.nc'
# variable
sfc_var_nm='snodl'
#sfc_var_nm='stc'
#sfc_var_nm='smc'
#sfc_var_nm='slc'
else:
# SFC_1 data:
path_sfc1=''
fn_sfc1_base=''
fn_sfc1_ext=''
# SFC_2 data:
path_sfc2=''
path_sfc2=''
fn_sfc2_base=''
fn_sfc2_ext=''
# increment:
path_xainc=path_sfc2
fn_xainc_base=''
fn_xainc_ext=''
# variable
sfc_var_nm='snodl'
sfc1_out_txt='before'
sfc2_out_txt='after'
# Vertical layer number
zlyr_num=2
# basic forms of title and file name
out_title_base='Land-DA::SFC::'+opt_analysis+'::'
out_fn_base='landda_out_sfc_'+opt_analysis+'_'
# Geo files
fn_orog_base='oro_C96.mx100.tile'
# Number of tiles
num_tiles=6
# Resolution of background natural earth data ('50m' or '110m')
back_res='50m'
# center of map
c_lon=-77.0369
# Main part (will be called at the end) ============================= CHJ =====
def main():
# =================================================================== CHJ =====
# get lon, lat from orography
get_geo()
# get sfc data from dir1
sfc1_data=get_sfc(path_sfc1,fn_sfc1_base,fn_sfc1_ext,sfc_var_nm,sfc1_out_txt,0)
print('data 1: ',sfc1_data.shape)
# get sfc data from dir2
sfc2_data=get_sfc(path_sfc2,fn_sfc2_base,fn_sfc2_ext,sfc_var_nm,sfc2_out_txt,0)
print('data 2: ',sfc2_data.shape)
(ntile,ny,nx)=sfc1_data.shape
sfc_xainc_data=np.zeros([ntile,ny,nx])
print('zero array: ',sfc_xainc_data.shape)
opt_inc=0
# get sfc increment data from dir2
if sfc_var_nm == 'snodl' or sfc_var_nm == 'snwdph':
if opt_analysis == 'jedi' or opt_analysis == 'gdas':
sfc_xainc_data=get_sfc(path_xainc,fn_xainc_base,fn_xainc_ext,sfc_var_nm,'xainc',0)
print('inc: ',sfc_xainc_data.shape)
opt_inc=1
# compare sfc1 and sfc2
compare_sfc(sfc1_data,sfc2_data,sfc_xainc_data,opt_inc)
# geo lon/lat from orography ======================================== CHJ =====
def get_geo():
# =================================================================== CHJ =====
global glon,glat
print(' ===== geo data files ====================================')
# open the data file
glon_all=[]
glat_all=[]
for it in range(num_tiles):
itp=it+1
fn_orog=fn_orog_base+str(itp)+'.nc'
fp_orog=os.path.join(path_orog,fn_orog)
try: orog=xr.open_dataset(fp_orog)
except: raise Exception('Could NOT find the file',fp_orog)
# print(orog)
# Extract longitudes, and latitudes
geolon=np.ma.masked_invalid(orog['geolon'].data)
geolat=np.ma.masked_invalid(orog['geolat'].data)
glon_all.append(geolon[None,:])
glat_all.append(geolat[None,:])
glon=np.vstack(glon_all)
glat=np.vstack(glat_all)
# Highest and lowest longitudes and latitudes for plot extent
lon_min=np.min(glon)
lon_max=np.max(glon)
lat_min=np.min(glat)
lat_max=np.max(glat)
out_title=out_title_base+'GEO'
out_fn=out_fn_base+'geo'
fig,ax=plt.subplots(1,1,subplot_kw=dict(projection=ccrs.Robinson(c_lon)))
ax.set_title(out_title, fontsize=6)
# Call background plot
back_plot(ax)
# Scatter plot (zorder: lowest-plot on bottom, highest-plot on top)
s_scale=0.05
s_color=["r", "b", "c", "g", "y", "m"]
# orography grid
for it in range(num_tiles):
ax.scatter(glon[it,:,:],glat[it,:,:],transform=ccrs.PlateCarree(),marker='o',facecolors=s_color[it],s=s_scale,zorder=1)
# Output figure
ndpi=300
out_file(out_fn,ndpi)
# Get sfc_data from files and plot ================================== CHJ =====
def get_sfc(path_sfc,fn_sfc_base,fn_sfc_ext,sfc_var_nm,sfc_out_txt,ref_opt):
# =================================================================== CHJ =====
print(' ===== sfc files: '+sfc_var_nm+' :: '+sfc_out_txt+' ========================')
# open the data file
sfc_data_all=[]
if ref_opt == 1:
snowxy_all=[]
slmsk_all=[]
for it in range(num_tiles):
itp=it+1
fn_sfc=fn_sfc_base+str(itp)+fn_sfc_ext
fp_sfc=os.path.join(path_sfc,fn_sfc)
try: sfc=xr.open_dataset(fp_sfc)
except: raise Exception('Could NOT find the file',fp_sfc)
# if it == 1:
# print(sfc)
# Extract variable
sfc_data=np.ma.masked_invalid(sfc[sfc_var_nm].data)
if sfc_out_txt == 'xainc':
sfc_data2d=np.squeeze(sfc_data,axis=(0,1))
else:
if sfc_var_nm == 'stc' or sfc_var_nm == 'smc' or sfc_var_nm == 'slc':
sfc_data3d=np.squeeze(sfc_data,axis=0)
sfc_data2d=sfc_data3d[zlyr_num,:,:]
else:
sfc_data2d=np.squeeze(sfc_data,axis=0)
sfc_data_all.append(sfc_data2d[None,:])
if ref_opt == 1:
# Number of snow layers
snowxy_orig=np.ma.masked_invalid(sfc['snowxy'].data)
snowxy2d=np.squeeze(snowxy_orig,axis=0)
snowxy_all.append(snowxy2d[None,:])
# sea-land mask
slmsk_orig=np.ma.masked_invalid(sfc['slmsk'].data)
slmsk2d=np.squeeze(slmsk_orig,axis=0)
slmsk_all.append(slmsk2d[None,:])
sfc_var=np.vstack(sfc_data_all)
if sfc_out_txt == 'xainc':
plot_increment(sfc_var,sfc_var_nm,sfc_out_txt)
else:
plot_data(sfc_var,sfc_var_nm,sfc_out_txt)
if ref_opt == 1:
snowxy=np.vstack(snowxy_all)
snowxy_max=np.max(snowxy)
snowxy_min=np.min(snowxy)
print('snowxy_max=',snowxy_max)
print('snowxy_min=',snowxy_min)
slmsk=np.vstack(slmsk_all)
slmsk_max=np.max(slmsk)
slmsk_min=np.min(slmsk)
print('slmsk_max=',slmsk_max)
print('slmsk_min=',slmsk_min)
for it in range(num_tiles):
glon_tile=np.squeeze(glon[it,:,:])
if it == 0:
glon_tile=(glon_tile+180)%360-180
glat_tile=np.squeeze(glat[it,:,:])
c_glon=np.round(np.mean(glon_tile),decimals=2)
c_glat=np.round(np.mean(glat_tile),decimals=2)
print(glon_tile.shape)
print(glat_tile.shape)
print("c_glon, c_glat for tile",str(it+1),"=",c_glon,c_glat)
snowxy_tile=np.squeeze(snowxy[it,:,:])
slmsk_tile=np.squeeze(slmsk[it,:,:])
print(snowxy_tile.shape)
print(slmsk_tile.shape)
print("glon: max=",np.max(glon_tile)," min=",np.min(glon_tile))
print("glat: max=",np.max(glat_tile)," min=",np.min(glat_tile))
print("snowxy:max=",np.max(snowxy_tile)," min=",np.min(snowxy_tile))
print("slmsk: max=",np.max(slmsk_tile), " min=",np.min(slmsk_tile))
# plot snow layers
out_title=out_title_base+'snowxy::Tile '+str(it+1)
out_fn=out_fn_base+'snowxy_tile'+str(it+1)
fig,ax=plt.subplots(1,1,subplot_kw=dict(projection=ccrs.Orthographic(c_glon,c_glat)))
ax.set_title(out_title, fontsize=6)
back_plot(ax)
cs=ax.pcolormesh(glon_tile,glat_tile,snowxy_tile,cmap=plt.cm.get_cmap('Set1',3),
rasterized=True,vmin=-2,vmax=0,transform=ccrs.PlateCarree())
divider=make_axes_locatable(ax)
ax_cb=divider.new_horizontal(size="3%",pad=0.1,axes_class=plt.Axes)
fig.add_axes(ax_cb)
cbar=plt.colorbar(cs,cax=ax_cb,extend='neither')
cbar.ax.tick_params(labelsize=6)
cbar.set_label('snowxy',fontsize=6)
out_file(out_fn,300)
# plot sea-land mask
out_title=out_title_base+'slmsk::Tile '+str(it+1)
out_fn=out_fn_base+'slmsk_tile'+str(it+1)
fig,ax=plt.subplots(1,1,subplot_kw=dict(projection=ccrs.Orthographic(c_glon,c_glat)))
ax.set_title(out_title, fontsize=6)
back_plot(ax)
cs=ax.pcolormesh(glon[it,:,:],glat[it,:,:],slmsk_tile,cmap=plt.cm.get_cmap('Paired',2),
rasterized=True,vmin=0,vmax=1,transform=ccrs.PlateCarree())
divider=make_axes_locatable(ax)
ax_cb=divider.new_horizontal(size="3%",pad=0.1,axes_class=plt.Axes)
fig.add_axes(ax_cb)
cbar=plt.colorbar(cs,cax=ax_cb,extend='neither')
cbar.ax.tick_params(labelsize=6)
cbar.set_label('slmsk',fontsize=6)
out_file(out_fn,300)
return sfc_var
# Compare two data set and plot ===================================== CHJ =====
def compare_sfc(sfc_data1,sfc_data2,inc_data,opt_inc):
# =================================================================== CHJ =====
print(' ===== compare files =============================================')
print(' data 1: ',sfc_data1.shape)
print(' data 2: ',sfc_data2.shape)
diff_data=sfc_data2-sfc_data1
print(' diff. data: ',diff_data.shape)
plot_increment(diff_data,sfc_var_nm,'diff_sfc')
if opt_inc == 1:
diff_inc=diff_data-inc_data
plt_var_nm=sfc_var_nm+'_xainc'
plot_increment(diff_inc,plt_var_nm,'diff_inc')
# increment/difference plot ========================================== CHJ =====
def plot_increment(plt_var,plt_var_nm,plt_out_txt):
# ==================================================================== CHJ =====
var_max=np.max(plt_var)
var_min=np.min(plt_var)
print(plt_var_nm,': diff : var_max=',var_max)
print(plt_var_nm,': diff : var_min=',var_min)
var_max08=var_max*0.8
var_min08=var_min*0.8
print(plt_var_nm,': diff : var_max08=',var_max08)
print(plt_var_nm,': diff : var_min08=',var_min08)
cs_max=max(abs(var_max08),abs(var_min08))
cs_min=cs_max*-1.0
cs_cmap='seismic'
nm_svar='\u0394'+plt_var_nm
n_rnd=0
cbar_extend='both'
out_title=out_title_base+plt_var_nm+'::'+plt_out_txt
out_fn=out_fn_base+plt_var_nm+'_'+plt_out_txt
fig,ax=plt.subplots(1,1,subplot_kw=dict(projection=ccrs.Robinson(c_lon)))
ax.set_title(out_title, fontsize=6)
# Call background plot
back_plot(ax)
for it in range(num_tiles):
cs=ax.pcolormesh(glon[it,:,:],glat[it,:,:],plt_var[it,:,:],cmap=cs_cmap,rasterized=True,
vmin=cs_min,vmax=cs_max,transform=ccrs.PlateCarree())
divider=make_axes_locatable(ax)
ax_cb=divider.new_horizontal(size="3%",pad=0.1,axes_class=plt.Axes)
fig.add_axes(ax_cb)
cbar=plt.colorbar(cs,cax=ax_cb,extend=cbar_extend)
cbar.ax.tick_params(labelsize=6)
cbar.set_label(nm_svar,fontsize=6)
# Output figure
ndpi=300
out_file(out_fn,ndpi)
# data plot ========================================================== CHJ =====
def plot_data(plt_var,plt_var_nm,plt_out_txt):
# ==================================================================== CHJ =====
var_max=np.max(plt_var)
var_min=np.min(plt_var)
print('var_max=',var_max)
print('var_min=',var_min)
var_max08=var_max*0.8
var_min08=var_min*0.8
print('var_max08=',var_max08)
print('var_min08=',var_min08)
cmap_range_opt='real'
cs_cmap='gist_ncar_r'
if cmap_range_opt=='symmetry':
n_rnd=0
tmp_cmp=max(abs(var_max08),abs(var_min08))
cs_min=round(-tmp_cmp,n_rnd)
cs_max=round(tmp_cmp,n_rnd)
cbar_extend='both'
elif cmap_range_opt=='round':
n_rnd=0
cs_min=round(var_min08,n_rnd)
cs_max=round(var_max08,n_rnd)
cbar_extend='both'
elif cmap_range_opt=='real':
cs_min=var_min
cs_max=var_max
cbar_extend='neither'
elif cmap_range_opt=='fixed':
cs_min=0.0
cs_max=150.0
cbar_extend='both'
else:
sys.exit('ERROR: wrong colormap-range flag !!!')
print('cs_max=',cs_max)
print('cs_min=',cs_min)
out_title=out_title_base+plt_var_nm+'::'+plt_out_txt
out_fn=out_fn_base+plt_var_nm+'_'+plt_out_txt
fig,ax=plt.subplots(1,1,subplot_kw=dict(projection=ccrs.Robinson(c_lon)))
ax.set_title(out_title, fontsize=6)
# Call background plot
back_plot(ax)
for it in range(num_tiles):
cs=ax.pcolormesh(glon[it,:,:],glat[it,:,:],plt_var[it,:,:],cmap=cs_cmap,rasterized=True,
vmin=cs_min,vmax=cs_max,transform=ccrs.PlateCarree())
divider=make_axes_locatable(ax)
ax_cb=divider.new_horizontal(size="3%",pad=0.1,axes_class=plt.Axes)
fig.add_axes(ax_cb)
cbar=plt.colorbar(cs,cax=ax_cb,extend=cbar_extend)
cbar.ax.tick_params(labelsize=6)
cbar.set_label(plt_var_nm,fontsize=6)
# Output figure
ndpi=300
out_file(out_fn,ndpi)
# Background plot ==================================================== CHJ =====
def back_plot(ax):
# ==================================================================== CHJ =====
fline_wd=0.5 # line width
falpha=0.7 # transparency
# natural_earth
land=cfeature.NaturalEarthFeature('physical','land',back_res,
edgecolor='face',facecolor=cfeature.COLORS['land'],
alpha=falpha)
lakes=cfeature.NaturalEarthFeature('physical','lakes',back_res,
edgecolor='blue',facecolor='none',
linewidth=fline_wd,alpha=falpha)
coastline=cfeature.NaturalEarthFeature('physical','coastline',
back_res,edgecolor='black',facecolor='none',
linewidth=fline_wd,alpha=falpha)
states=cfeature.NaturalEarthFeature('cultural','admin_1_states_provinces',
back_res,edgecolor='green',facecolor='none',
linewidth=fline_wd,linestyle=':',alpha=falpha)
borders=cfeature.NaturalEarthFeature('cultural','admin_0_countries',
back_res,edgecolor='red',facecolor='none',
linewidth=fline_wd,alpha=falpha)
# ax.add_feature(land)
# ax.add_feature(lakes)
# ax.add_feature(states)
# ax.add_feature(borders)
ax.add_feature(coastline)
# Output file ======================================================= CHJ =====
def out_file(out_file,ndpi):
# =================================================================== CHJ =====
# Output figure
fp_out=os.path.join(out_fig_dir,out_file)
plt.savefig(fp_out+'.png',dpi=ndpi,bbox_inches='tight')
plt.close('all')
# Main call ========================================================= CHJ =====
if __name__=='__main__':
main()