forked from fabioviola-cmcc/medens-plotter
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmean_spread_currents.py
308 lines (244 loc) · 11.5 KB
/
mean_spread_currents.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
#!/usr/bin/python3
###############################################
#
# global reqs
#
###############################################
from mpl_toolkits.basemap import Basemap
import matplotlib.pyplot as plt
from numpy import meshgrid
from numpy import linspace
import configparser
import numpy as np
import traceback
import datetime
import warnings
import xarray
import numpy
import math
import pdb
import sys
import os
# suppress warnings
warnings.filterwarnings('ignore')
###############################################
#
# initial config
#
###############################################
appname = "Plotcurrents"
###############################################
#
# main
#
###############################################
if __name__ == "__main__":
###############################################
#
# read input parameters
#
###############################################
# read config file name
configFile = None
try:
configFile = sys.argv[1]
except:
print("[ERROR] -- Config file not provided!")
sys.exit(1)
# read date
inputDate = None
try:
inputDate = sys.argv[2]
except:
inputDate = datetime.datetime.today().strftime("%Y%m%d")
# read day index
day_index = None
try:
day_index = int(sys.argv[3])
except:
day_index = 0
###############################################
#
# parse config file
#
###############################################
configParser = configparser.ConfigParser()
configParser.read(configFile)
# paths
basePath = configParser.get("default", "basePath")
baseOutputPath = configParser.get("default", "baseOutputPath")
meanUFile = os.path.join(basePath, inputDate, configParser.get("currents", "meanUFile"))
meanVFile = os.path.join(basePath, inputDate, configParser.get("currents", "meanVFile"))
stdUFile = os.path.join(basePath, inputDate, configParser.get("currents", "stdUFile"))
stdVFile = os.path.join(basePath, inputDate, configParser.get("currents", "stdVFile"))
outputFolder = configParser.get("currents", "outputFolder")
outputFileTemplate = configParser.get("currents", "outputName")
print("[%s] -- Mean U file set to: %s" % (appname, meanUFile))
print("[%s] -- Mean V file set to: %s" % (appname, meanVFile))
print("[%s] -- Std U file set to: %s" % (appname, stdUFile))
print("[%s] -- Std V file set to: %s" % (appname, stdVFile))
# create output folder if needed
dst = os.path.join(baseOutputPath, outputFolder.format(DATE=inputDate))
if not os.path.exists(dst):
os.makedirs(dst, exist_ok=True)
print("[%s] -- Output folder set to: %s" % (appname, dst))
# chart details
meanColorMap = configParser.get("currents", "meanColorMap")
meanMinValue = configParser.getfloat("currents", "meanMinValue")
meanMaxValue = configParser.getfloat("currents", "meanMaxValue")
meanLevels = configParser.getint("currents", "meanLevels")
stdColorMap = configParser.get("currents", "stdColorMap")
stdMinValue = configParser.getfloat("currents", "stdMinValue")
stdMaxValue = configParser.getfloat("currents", "stdMaxValue")
stdLevels = configParser.getint("currents", "stdLevels")
resolution = configParser.get("currents", "resolution")
print("[%s] -- Mean color map set to: %s" % (appname, meanColorMap))
print("[%s] -- Mean min value set to: %s" % (appname, meanMinValue))
print("[%s] -- Mean max value set to: %s" % (appname, meanMaxValue))
print("[%s] -- Std color map set to: %s" % (appname, stdColorMap))
print("[%s] -- Std min value set to: %s" % (appname, stdMinValue))
print("[%s] -- Std max value set to: %s" % (appname, stdMaxValue))
print("[%s] -- Resolution set to: %s" % (appname, resolution))
###############################################
#
# start processing
#
###############################################
# open datasets STD
ds1u = xarray.open_dataset(stdUFile)
ds1v = xarray.open_dataset(stdVFile)
# open datasets MEAN
ds2u = xarray.open_dataset(meanUFile)
ds2v = xarray.open_dataset(meanVFile)
# grid indices
x = ds1u.lon.values
y = ds1u.lat.values
# lats and lons
lats = ds1u.lat.transpose().values
lons = ds1u.lon.values
# central points
clat = (lats[-1] - lats[0]) / 2
clon = (lons[-1] - lons[0]) / 2
# create the grid
xxx, yyy = meshgrid(lons, lats)
# define a timestep index (to keep track of the timesteps) and an index to keep track of the day we are in
timestep_index = 0
day_current_index = 0
old_day = str(ds1u.time[0].values).split("T")[0]
# iterate over the timestamps
for t in ds1u.time.values:
# get the date of the current timestep, and optionally update the variable and index keeping track of the day
d1 = str(t).split("T")[0]
if d1 != old_day:
old_day = d1
day_current_index += 1
# get days string
d1 = str(t).split("T")[0]
hour = str(t).split("T")[1].split(":")[0]
minu = str(t).split("T")[1].split(":")[1]
d2 = "%s:%s" % (hour, minu)
d3 = "%s, %s" % (d1, d2)
d4 = "%s_%s30" % (d1, hour)
# check if it's the desired day, otherwise move on
if day_current_index != day_index:
timestep_index += 1
continue
# iterate over depth
depth_index = 0
for d in ds1u.depth.values:
fig, axes = plt.subplots(nrows=2, ncols=1)
ax_index = 0
for ax in axes.flat:
if ax_index == 1:
############################################
#
# Std
#
############################################
# initialise the map
bmap = Basemap(resolution=resolution,
llcrnrlon=lons[0],llcrnrlat=lats[0],
urcrnrlon=lons[-1],urcrnrlat=lats[-1], ax=ax)
# contourf STD
stdLevelsContourf = linspace(stdMinValue, stdMaxValue, num=stdLevels+1)
std_data_0u = ds1u.vozocrtx[timestep_index,depth_index,:,:].values
std_data_0v = ds1v.vomecrty[timestep_index,depth_index,:,:].values
std_data = numpy.sqrt(std_data_0u ** 2 + std_data_0v ** 2)
# contourf
std_colormesh = ax.contourf(xxx, yyy, std_data, cmap=stdColorMap, linewidths=0.3, levels=stdLevelsContourf, vmin=stdMinValue, vmax=stdMaxValue, extend='both')
# colorbar STD
stdTicks = numpy.arange(stdMinValue, stdMaxValue+0.1, 0.1)
std_cb = bmap.colorbar(std_colormesh, location='right', ticks = stdTicks, ax=ax)
std_cb.set_label("Spread (m/s)", fontsize=5)
for t in std_cb.ax.get_yticklabels():
t.set_fontsize(3)
# draw coastlines, country boundaries, fill continents.
bmap.drawcoastlines(linewidth=0.15)
bmap.fillcontinents()
bmap.drawparallels(range(0, 90, 5), linewidth=0.1, labels=[1,0,0,1], fontsize=2)
bmap.drawmeridians(range(-90, 90, 5), linewidth=0.1, labels=[1,0,0,1], fontsize=2)
# title
finalDate = d1 # "%s:30" % (d3.split(":")[0])
ax.set_title("Ensemble spread for currents.\nDaily mean: %s" % (finalDate), fontsize = 5)
else:
############################################
#
# Mean
#
############################################
# contour MEAN
meanLevelsContour = linspace(meanMinValue, meanMaxValue, num=meanLevels)
# u and v, then norm
mean_data_0u = ds2u.vozocrtx[timestep_index,depth_index,:,:].values
mean_data_0v = ds2v.vomecrty[timestep_index,depth_index,:,:].values
mean_data = numpy.sqrt(mean_data_0u ** 2 + mean_data_0v ** 2)
# initialise the map
bmap = Basemap(resolution=resolution,
llcrnrlon=lons[0],llcrnrlat=lats[0],
urcrnrlon=lons[-1],urcrnrlat=lats[-1], ax=ax)
# contour
mean_colormesh = ax.contourf(xxx, yyy, mean_data, cmap=meanColorMap, levels=meanLevelsContour, linewidths=0.3, vmin=meanMinValue, vmax=meanMaxValue, extend='both')
# colorbar MEAN
meanTicks = numpy.arange(int(meanMinValue), int(meanMaxValue)+1, 0.1)
mean_cb = bmap.colorbar(mean_colormesh, ticks=meanTicks, location="right", ax=ax)
mean_cb.set_label("Mean currents (m/s)", fontsize=5)
for t in mean_cb.ax.get_yticklabels():
t.set_fontsize(3)
# draw coastlines, country boundaries, fill continents.
bmap.drawcoastlines(linewidth=0.25)
bmap.fillcontinents(color='white')
bmap.drawparallels(range(0, 90, 5), linewidth=0.1, labels=[1,0,0,1], fontsize=2)
bmap.drawmeridians(range(-90, 90, 5), linewidth=0.1, labels=[1,0,0,1], fontsize=2)
# title
finalDate = d1 # "%s:30" % (d3.split(":")[0])
ax.set_title("Ensemble mean for currents.\nDaily mean: %s" % (finalDate), fontsize = 5)
# Mean vector
u = ds2u.vozocrtx[timestep_index,depth_index,::,::].values
v = ds2v.vomecrty[timestep_index,depth_index,::,::].values
# Normalize the arrows:
uu = u / np.sqrt(u**2 + v**2)
vv = v / np.sqrt(u**2 + v**2)
xx = xxx[::,::]
yy = yyy[::,::]
# quiver
mean_colormesh = bmap.streamplot(xx, yy, u, v, linewidth=0.3, arrowsize=0.3, density=3, color='k') # , scale=50) # headlength=3, headwidth=1,
ax_index += 1
############################################
#
# general configuration
#
############################################
# draw coastlines, country boundaries, fill continents.
bmap.drawcoastlines(linewidth=0.25)
bmap.fillcontinents(color='white')
# save file
filename = os.path.join(dst, outputFileTemplate.format(DATE=d4, DEPTH=depth_index))
plt.savefig(filename, dpi=300, bbox_inches="tight")
print("File %s generated" % filename)
# clear memory
fig.clear()
plt.close(fig)
# increment depth index
depth_index += 1
# increment timestep index
timestep_index += 1