-
Notifications
You must be signed in to change notification settings - Fork 1
/
Parsivel_Utilities.py
378 lines (303 loc) · 13 KB
/
Parsivel_Utilities.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
import sys, os, glob
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
import itertools
from datetime import datetime, timedelta
from zipfile import ZipFile
import xarray as xr
import time
pd.set_option("display.max_columns", 1100)
np.set_printoptions(linewidth=160)
#############################################################################################
def save_netcdf(DS_1min, site, instrument, syear, smonth, sday):
'''
This function accepts a 1-minute Xarray DataSet containing Parsivel data and writes
it to a NetCDF filee. Note that the data has been masked using Ali's conditional
matrix to mitigate unrealistic data in dropsize/velocity pairs.
It returns the path/name of the written NetCDF file
'''
cdf_dir = Out_Base_Dir + '/NetCDF/' + syear + '/'
os.makedirs(cdf_dir, exist_ok=True)
cdf_file = cdf_dir + site + '_' + instrument + '_' + syear + '_' + smonth + sday + '_1min.cdf'
DS_1min.to_netcdf(cdf_file, mode='w', format='NETCDF4')
print(' --> ' + cdf_file)
return cdf_file
#############################################################################################
def save_dataframes(Parms_DF, PSD_DF, Moments_DF, Out_Base_Dir, site, instrument, syear, smonth, sday):
# /d1/wallops-prf/Disdrometer/Parsivel/apu04/Text/2021/WFF_apu04_2021_0212.txt
txt_dir = Out_Base_Dir + 'Text/' + syear + '/'
os.makedirs(txt_dir, exist_ok=True)
parms_file = txt_dir + site + '_' + instrument + '_' + syear + '_' + smonth + sday + '_parms.csv'
Parms_DF.to_csv(parms_file)
print(' --> ' + parms_file)
psd_file = txt_dir + site + '_' + instrument + '_' + syear + '_' + smonth + sday + '_psd.csv'
PSD_DF.to_csv(psd_file)
print(' --> ' + psd_file)
moms_file = txt_dir + site + '_' + instrument + '_' + syear + '_' + smonth + sday + '_moments.csv'
Moments_DF.to_csv(moms_file)
print(' --> ' + moms_file)
return parms_file, psd_file, moms_file
#############################################################################################
def print_drop_matrix(data):
np.set_printoptions(linewidth=160)
x = data[:,:]
for iv in range(32):
line = x[iv,:].astype(int)
print(line)
return
#############################################################################################
def get_julday_from_datetime(dt):
jday = dt.timetuple().tm_yday
return jday
#############################################################################################
def get_julday_from_ymd(year, month, day):
jday = datetime(year, month, day).timetuple().tm_yday
return jday
#############################################################################################
def unzip_files(zfiles, instrument, syear, smonth, sday):
tmp_dir = 'tmp/' + instrument + '/' + syear + smonth + sday + '/'
os.makedirs(tmp_dir, exist_ok=True)
files = []
for i, zf in enumerate(zfiles):
f = os.path.basename(zf)[:-4]+'.dat'
#print(zf,' --> ',f)
with ZipFile(zf, 'r') as zipObj:
zipObj.extract(f, tmp_dir)
files.append(tmp_dir + f)
return files, tmp_dir
#############################################################################################
def concatenate_csv_files(files):
#tmp_dir = 'tmp/tmp_dir_' + str(os.getpid()) + '/'
tmp_dir = 'tmp/'
os.makedirs(tmp_dir, exist_ok=True)
fileb = os.path.basename(files[0])[:-4]
in_file = tmp_dir + fileb + '.csv'
with open(in_file, 'w') as f:
#display(f)
for fname in files:
with open(fname, 'r', encoding = "UTF-8") as fs:
for line in fs:
f.write(line)
return in_file
#############################################################################################
def concatenate_files(files):
#tmp_dir = 'tmp/tmp_dir_' + str(os.getpid()) + '/'
tmp_dir = 'tmp/'
os.makedirs(tmp_dir, exist_ok=True)
fileb = os.path.basename(files[0])[:-4]
in_file = tmp_dir + fileb + '.csv'
with open(in_file, 'w') as f:
for fname in files:
with open(fname, 'r', encoding = "ISO-8859-1") as fs:
for line in fs:
f.write(line)
return in_file
#############################################################################################
def get_dataset_from_parsivel(file, DVparms, Order='C'):
lines = []
with open(file, 'r') as f:
lines = f.readlines()
dates = []
nr = len(lines)
nd = 32
nv = 32
data1d = np.zeros([nd*nv, nr])
data2d = np.zeros([nd, nv, nr])
datars = np.zeros([nd, nv, nr])
for ir in range(nr):
x = lines[ir]
dates.append(x[0:14])
string_list = x[60:-2]
x = np.array(string_list.split(','))
if(len(x) == 1024):
data1d[:,ir] = x
x2 = np.reshape(x, (32, 32), order=Order)
data2d[:, :, ir] = x2
else:
print('Bad record length: ', ir, len(x))
diam = DVparms['Drop_bin'].values
velo = DVparms['Measured_Vt'].values
DT = pd.to_datetime(dates)
time = DT
DS = xr.Dataset(
data_vars=dict(
drops=(["Diam", "Vel", "time"], data2d),
),
attrs=dict(Description="Parsivel data."),
)
DS = DS.assign_coords(Diam=diam, Vel=velo, time=time)
return DS, data2d
#############################################################################################
def get_dataset_from_csv_parsivel(file, DVparms, Order='C'):
lines = []
with open(file, 'r') as f:
lines = f.readlines()
#os.remove(file)
dates = []
nr = len(lines)
nd = 32
nv = 32
data1d = np.zeros([nd*nv, nr])
data2d = np.zeros([nd, nv, nr])
datars = np.zeros([nd, nv, nr])
for ir in range(nr):
x = lines[ir]
dates.append(x[0:14])
string_list = x[64:-2]
x = np.array(string_list.split(','))
if(len(x) == 1024):
try:
data1d[:,ir] = x
x2 = np.reshape(x, (32, 32), order=Order)
data2d[:, :, ir] = x2
except ValueError:
print(f'\n ***ERROR on line {ir+1} with YYYYMMDDHHMMSS {dates[ir]} in file {file}...skipping')
else:
print('Bad record length: ', ir, len(x))
diam = DVparms['Drop_bin'].values
velo = DVparms['Measured_Vt'].values
DT = pd.to_datetime(dates)
time = DT
DS = xr.Dataset(
data_vars=dict(
drops=(["Diam", "Vel", "time"], data2d),
),
attrs=dict(Description="Parsivel data."),
)
DS = DS.assign_coords(Diam=diam, Vel=velo, time=time)
return DS, data2d
#############################################################################################
def get_integral_parameters(site, inst, DS_1min, DF_Mask, DVparms):
Nsecs = 60
missing = np.nan
pi = np.pi
missing = 0
nd = 32
nv = 32
nrecs = len(DS_1min.time)
# Load Ali's D/V Mask
df_mask = DF_Mask.values[:,:-1]
df1 = np.flip(df_mask, 1)
df_mask = np.rot90(df1, 1)
Total_Drops = np.zeros(nrecs).astype(np.int64)
Conc = np.zeros(nrecs).astype(np.float64)
LWC = np.zeros(nrecs).astype(np.float64)
Z = np.zeros(nrecs).astype(np.float64)
dBZ = np.zeros(nrecs).astype(np.float64)
Rain = np.zeros(nrecs).astype(np.float64)
Dm = np.zeros(nrecs).astype(np.float64)
Accum = np.zeros(nrecs).astype(np.float64)
Dmax = np.zeros(nrecs).astype(np.float64)
Sigma_M = np.zeros(nrecs).astype(np.float64)
Moments = np.zeros([nrecs, 8]).astype(np.float64)
dsd = np.zeros([nrecs, nd]).astype(np.float64)
d_bin = DVparms['Drop_bin'].values
v_bin = DVparms['Theoretical_Vt'].values
delta = DVparms['Delta-D'].values
DT = DS_1min.time.values
for ir in range(nrecs):
Drops = DS_1min['drops'].isel(time=ir).values
# Apply mask
Drops[(df_mask == 0)] = 0
Total_Drops[ir] = Drops.sum()
#print('Total drops for ',DT[ir],'=', Total_Drops[ir])
for idiam in range(nd):
diam = d_bin[idiam]
dt = delta[idiam]
for ivel in range(nv):
vel = v_bin[ivel]
NumDrops = Drops[idiam, ivel]
# Calculate the DSD
cs2 = (180.*(30.-(diam/2.)))/100.
bot2 = Nsecs * cs2 * vel * dt * 100
dsd[ir,idiam] += (1.e6 * NumDrops)/bot2
# Compute integral parameters
cs = (180.*(30.-(diam/2.)))
bot = 60. * cs * vel
vol = np.pi*(diam**3.)/6.
if(NumDrops > 0): Dmax[ir] = diam
Conc[ir] += NumDrops * 1.e6/bot
LWC[ir] += NumDrops * vol *1.e3/bot
Z[ir] += NumDrops * 1.e6 * diam**6. / bot
Rain[ir] += NumDrops * vol * Nsecs / cs
# Calculate eight first moments
for im in range(8):
Moments[ir,im] += (1.e6 * NumDrops * diam**im)/bot
# Calculate mass-weighted mean diameter and reflectivity
Dm[ir] = Moments[ir,4]/Moments[ir,3] # Ratio of 4th to 3rd moment
if( (Dm[ir] < 0) | (Dm[ir] > 20) ): Dm[ir] = missing
# # Calculate sigma_m: Sm^2 = sum((D - Dm)^2 N(D) D^3 dD) / sum(N(D) D^3 dD)
# sig1 = np.double(0) ; sig2 = sig1
# for idiam in range(nd):
# diam = d_bin[idiam]
# cs = 180. * (30. - diam/2.)
# for ivel in range(nv):
# vel = v_bin[ivel]
# NumDrops = Drops[idiam, ivel]
# bot = 60. * cs * vel
# sig = (diam - Dm[ir])**2
# sig1 += sig * (diam**3 * NumDrops * 1.e6)/bot
# sig2 += (diam**3 * NumDrops * 1.e6)/bot
#
# sig0 = (sig1/(sig2 * Dm[ir]**2))**0.5
# sig0 *= Dm[ir]
# Sigma_M[ir] = sig1/sig2
# if( (Sigma_M[ir] < 0) | (Sigma_M[ir] > 20) ): Sigma_M[ir] = missing
# Place Parms into a DataFrame
Parms = {'DateTime': DT, 'Total Drops': Total_Drops, 'Concentration': Conc,
'LWC': LWC, 'Z': Z, 'dBZ': 10*np.log10(Z), 'Rain': Rain, 'Dm': Dm,
'Dmax': Dmax, 'Sigma_M': Sigma_M}
cols = ['Total Drops', 'Concentration', 'LWC', 'Z', 'dBZ', 'Rain', 'Dm', 'Dmax', 'Sigma_M']
Parms_DF = pd.DataFrame(data=Parms, index=DT, columns=cols)
# Place PSD dictionary into a Pandas DataFrame
PSD = {'DateTime': DT, 'DropSize': d_bin, 'DSD': dsd}
PSD_DF = pd.DataFrame(data=PSD['DSD'], index=Parms['DateTime'], columns=PSD['DropSize'])
# Place Moments into a DataFrame
moms = ['M0', 'M1', 'M2', 'M3', 'M4', 'M5', 'M6', 'M7']
Moments = {'DateTime': DT, 'Moments': Moments, 'Mom#': moms}
Moments_DF = pd.DataFrame(data=Moments['Moments'], index=Moments['DateTime'], columns=Moments['Mom#'])
return Parms_DF, PSD_DF, Moments_DF
#############################################################################################
def get_integral_parameters_xarray(site, inst, DS_1min, DF_Mask, DVparms):
nd = 32
nv = 32
nrecs = len(DS_1min.time.values)
DT = DS_1min.time.values
Total_Drops = np.zeros(nrecs).astype(np.int64)
Conc = np.zeros(nrecs).astype(np.float64)
LWC = np.zeros(nrecs).astype(np.float64)
Z = np.zeros(nrecs).astype(np.float64)
dBZ = np.zeros(nrecs).astype(np.float64)
Rain = np.zeros(nrecs).astype(np.float64)
Dm = np.zeros(nrecs).astype(np.float64)
Accum = np.zeros(nrecs).astype(np.float64)
Dmax = np.zeros(nrecs).astype(np.float64)
Sigma_M = np.zeros(nrecs).astype(np.float64)
Moments = np.zeros([nrecs, 8]).astype(np.float64)
dsd = np.zeros([nrecs, nd]).astype(np.float64)
drop_bins = DVparms['Drop_bin'].values
vel_bins = DVparms['Theoretical_Vt'].values
for ir in range(nrecs):
Drops = DS_1min['drops'].isel(time=ir).values
Drops = np.rot90(Drops)
NumDrops = DS_1min['drops'].isel(time=ir).values.sum()
Total_Drops[ir] = NumDrops
Nsecs = 60
cs = (180.*(30.-(drop_bins/2.)))
bot = 60. * cs * vel_bins
vol = np.pi*(drop_bins**3.)/6.
Rain[ir] = np.sum((Drops * vol * Nsecs)/cs)
Conc[ir] = np.sum((Drops * 1.e6)/bot)
LWC[ir] = np.sum((Drops * vol *1.e3)/bot)
Z[ir] = np.sum((Drops * 1.e6 * drop_bins**6)/bot)
dBZ[ir] = 10*np.log10(Z[ir])
# print(ir, Total_Drops[ir], np.round(Conc[ir], 5), np.round(LWC[ir], 5),
# np.round(Z[ir], 5), np.round(dBZ[ir], 5), np.round(Rain[ir], 5))
# Place Parms into a DataFrame
Parms = {'DateTime': DT, 'Total Drops': Total_Drops, 'Concentration': Conc,
'LWC': LWC, 'Z': Z, 'dBZ': 10*np.log10(Z), 'Rain': Rain, 'Dm': Dm,
'Dmax': Dmax, 'Sigma_M': Sigma_M}
cols = ['Total Drops', 'Concentration', 'LWC', 'Z', 'dBZ', 'Rain', 'Dm', 'Dmax', 'Sigma_M']
Parms_DF = pd.DataFrame(data=Parms, index=DT, columns=cols)
return Parms_DF