-
Notifications
You must be signed in to change notification settings - Fork 1
/
gfs_hrly_ar.py
177 lines (145 loc) · 5.57 KB
/
gfs_hrly_ar.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
import cartopy.crs as ccrs
import cartopy.feature as cfeature
import numpy as np
import matplotlib.pyplot as plt
import netCDF4
import xarray as xr
import metpy
from datetime import datetime
import datetime as dt
from metpy.units import units
import scipy.ndimage as ndimage
from metpy.plots import USCOUNTIES
import cartopy
from scipy.ndimage.filters import generic_filter as gf
def mkdir_p(mypath):
'''Creates a directory. equivalent to using mkdir -p on the command line'''
from errno import EEXIST
from os import makedirs,path
try:
makedirs(mypath)
except OSError as exc: # Python >2.5
if exc.errno == EEXIST and path.isdir(mypath):
pass
else: raise
startTime=datetime.now()
m_date='20200903'
m_hour='12'
year = startTime.year
if startTime.month <10:
month = '0'+str(startTime.month)
else:
month = str(startTime.month)
if startTime.day <10:
day = '0'+str(startTime.day)
else:
day = str(startTime.day)
if startTime.hour <10:
hour = '0'+str(startTime.hour)
else:
hour = str(startTime.hour)
mdate = str(year)+str(month)+str(day)
def get_init_hr(hour):
if int(hour) <6:
init_hour = '00'
elif int(hour) <11:
init_hour = '06'
elif int(hour) <17:
init_hour = '12'
elif int(hour) <22:
init_hour = '18'
else:
init_hour = '00'
return(init_hour)
url = 'http://nomads.ncep.noaa.gov:80/dods/gfs_0p25_1hr/gfs'+mdate+'/gfs_0p25_1hr_'+get_init_hr(hour)+'z'
init_hour = get_init_hr(hour)
'''
for i in range(119):
fhr = i+1
'''
# Create new directory
output_dir = str(year)+str(month)+str(day)+'_'+str(init_hour)+'00'
mkdir_p(output_dir)
mkdir_p(output_dir+'/GFS')
#Parse data using MetPy
ds = xr.open_dataset(url)
init_hr = dt.datetime(int(year),int(month),int(day),int(init_hour))
times = ds['tmp2m'].metpy.time
init_time = ds['time'][0]
lats = np.arange(25,55,0.25)
lons = np.arange(260,310,0.25)
for i in range(1,120):
fc_hr = init_hr+dt.timedelta(hours=1*i)
forecast_hour = times[0].values
data = ds.metpy.parse_cf()
data = data.isel(time=i)
#Rename variables to useful things
data = data.rename({
'absvprs':'avort',
'hgtprs':'gph',
'rhprs':'rh',
'tmpprs':'temp',
'ugrdprs':'u',
'vgrdprs': 'v',
'pwatclm':'pwat'
})
vertical, = data['temp'].metpy.coordinates('vertical')
time = data['temp'].metpy.time
zH5_crs = data['temp'].metpy.cartopy_crs
u8 = data['u'].sel(lev=850.0,lat=lats,lon=lons).squeeze()*1.94384449
v8 = data['v'].sel(lev=850.0,lat=lats,lon=lons).squeeze()*1.94384449
h8 = data['gph'].sel(lev=850.0,lat=lats,lon=lons).squeeze()
pwat = data['pwat'].sel(lat=lats,lon=lons).squeeze()*0.0393700787402
x, y = h8.metpy.coordinates('x', 'y')
lat, lon = xr.broadcast(y, x)
wind_slice = slice(5,-5,5)
#wspd = ((u2**2)+(v2**2))**.5
########## SET UP FIGURE ##################################################
fig = plt.figure(figsize=(15,15))
ax1 = fig.add_subplot(111, projection = zH5_crs)
ax1.coastlines(resolution='10m')
ax1.add_feature(cfeature.BORDERS.with_scale('10m'))
ax1.add_feature(cfeature.STATES.with_scale('10m'))
#fig.suptitle("NAM Forecast valid at " + time[0].dt.strftime('%Y-%m-%d %H:%MZ').item(),fontsize=36)
pwlevs = []
for j in range(1,25):
lev = 0.1*j
pwlevs.append(lev)
########## PLOTTING #######################################################
h8c = ax1.contour(x,y,h8,colors='dimgray', levels = range(1100,1600,30),linewidths=1.5)
#t2c = ax1.contour(x,y,t2,colors='r', levels = range(-60,0,5),linestyles='dashed',linewidths=1)
pwc = ax1.contourf(x,y,pwat,cmap='Greens',levels=pwlevs,alpha=0.9)
a5cb = fig.colorbar(pwc, orientation = 'horizontal', aspect = 80, ax = ax1, pad = 0.01,
extendrect=False, ticks = [0.5,1,1.5,2,2.5])
a5cb.set_label('Precipitable Water (in)', fontsize = 12)
ax1.barbs(x[wind_slice],y[wind_slice],u8[wind_slice,wind_slice],v8[wind_slice,wind_slice], length=7)
#h_contour = ax1.contour(x, y, mslpc, colors='dimgray', levels=range(940,1040,4),linewidths=2)
#h_contour.clabel(fontsize=14, colors='dimgray', inline=1, inline_spacing=4, fmt='%i mb', rightside_up=True, use_clabeltext=True)
ax1.set_title('Precipitable Water (in), 850mb Heights (m), and Winds (kts)',fontsize=16)
ax1.set_title('\n Valid: '+time.dt.strftime('%Y-%m-%d %H:%MZ').item(),fontsize=11,loc='right')
ax1.set_title('\n GFS Init: '+init_time.dt.strftime('%Y-%m-%d %H:%MZ').item(),fontsize=11,loc='left')
ax1.set_extent((265, 300, 25, 50))#, crs = zH5_crs) # Set a title and show the plot
plt.savefig(output_dir+'/GFS/gfs_hrly_pwat_v2_'+str(i)+'.png')
fcst_hr = str(0)
print('Hour '+str(i)+' completed!')
plt.close()
timeelapsed = datetime.now()-startTime
print(timeelapsed)
'''
url= 'http://nomads.ncep.noaa.gov:80/dods/gfs_0p25_1hr/gfs20200903/gfs_0p25_1hr_12z'
ds = xr.open_dataset(url)
t2m_ds = ds['tmp2m']
init_hr = t2m_ds['time'][0].values
#fc_hr = t2m.ds['time'][i].values
lats = np.arange(20,50,0.25)
lons = np.arange(240,300,0.25)
t2m = t2m_ds.sel(time = init_hr, lat = lats, lon = lons)
print(t2m)
fig = plt.figure(figsize = (12,12))
fig.clf()
ax = plt.axes(projection=ccrs.PlateCarree())
ax.coastlines()
ax.set_extent((240,300, 20, 50), crs = ccrs.PlateCarree())
t2m_c = ax.contourf(t2m, cmap='RdPu')
plt.savefig('testingnomads6.png')
'''