-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathsounding_procedures.py
3847 lines (3636 loc) · 151 KB
/
sounding_procedures.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
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu May 16 14:24:40 2019
@author: ziskin
"""
# from pathlib import Path
from PW_paths import work_yuval
sound_path = work_yuval / 'sounding'
era5_path = work_yuval / 'ERA5'
edt_path = sound_path / 'edt'
ceil_path = work_yuval / 'ceilometers'
des_path = work_yuval / 'deserve'
def load_field_from_radiosonde(
path=sound_path, field='Tm', data_type='phys', reduce='min',
dim='time', plot=True):
"""data_type: phys for 2008-2013, 10 sec sample rate,
PTU_Wind for 2014-2016 2 sec sample rate,
edt for 2018-2019 1 sec sample rate with gps"""
from aux_gps import plot_tmseries_xarray
from aux_gps import path_glob
import xarray as xr
def reduce_da(da):
if reduce is not None:
if reduce == 'min':
da = da.min(dim)
elif reduce == 'max':
da = da.max(dim)
da = da.reset_coords(drop=True)
return da
if data_type is not None:
file = path_glob(
path, 'bet_dagan_{}_sounding_*.nc'.format(data_type))[-1]
da = xr.open_dataset(file)[field]
da = da.sortby('sound_time')
da = reduce_da(da)
else:
files = path_glob(path, 'bet_dagan_*_sounding_*.nc')
assert len(files) == 3
ds = [xr.open_dataset(x)[field] for x in files]
da = xr.concat(ds, 'sound_time')
da = da.sortby('sound_time')
da = reduce_da(da)
if plot:
plot_tmseries_xarray(da)
return da
def get_field_from_radiosonde(path=sound_path, field='Tm', data_type='phys',
reduce='min', dim='time',
times=['2007', '2019'], plot=True):
"""
old version, to be replaced with load_field_from_radiosonde,
but still useful for ZWD
Parameters
----------
path : TYPE, optional
DESCRIPTION. The default is sound_path.
field : TYPE, optional
DESCRIPTION. The default is 'Tm'.
data_type : TYPE, optional
DESCRIPTION. The default is 'phys'.
reduce : TYPE, optional
DESCRIPTION. The default is 'min'.
dim : TYPE, optional
DESCRIPTION. The default is 'time'.
times : TYPE, optional
DESCRIPTION. The default is ['2007', '2019'].
plot : TYPE, optional
DESCRIPTION. The default is True.
Returns
-------
da : TYPE
DESCRIPTION.
"""
import xarray as xr
from aux_gps import get_unique_index
from aux_gps import keep_iqr
from aux_gps import plot_tmseries_xarray
from aux_gps import path_glob
file = path_glob(path, 'bet_dagan_{}_sounding_*.nc'.format(data_type))[0]
file = path / 'bet_dagan_phys_PW_Tm_Ts_2007-2019.nc'
ds = xr.open_dataset(file)
if field is not None:
da = ds[field]
if reduce is not None:
if reduce == 'min':
da = da.min(dim)
elif reduce == 'max':
da = da.max(dim)
da = da.reset_coords(drop=True)
da = get_unique_index(da, dim='sound_time')
da = keep_iqr(da, k=2.0, dim='sound_time', drop_with_freq='12H')
da = da.sel(sound_time=slice(*times))
if plot:
plot_tmseries_xarray(da)
return da
def calculate_edt_north_east_distance(lat_da, lon_da, method='fast'):
"""fast mode is 11 times faster than slow mode, however fast distance is
larger than slow...solve this mystery"""
from shapely.geometry import Point
from pyproj import Transformer
import geopandas as gpd
import pandas as pd
import numpy as np
def change_sign(x, y, value):
if x <= y:
return -value
else:
return value
if method == 'fast':
# prepare bet dagan coords:
bd_lat = 32.01
bd_lon = 34.81
fixed_lat = np.ones(lat_da.shape) * bd_lat
fixed_lon = np.ones(lon_da.shape) * bd_lon
# define projections:
# wgs84 = pyproj.CRS('EPSG:4326')
# isr_tm = pyproj.CRS('EPSG:2039')
# creare transfrom from wgs84 (lat, lon) to new israel network (meters):
# transformer = Transformer.from_crs(wgs84, isr_tm, always_xy=True)
transformer = Transformer.from_proj(4326, 2039, always_xy=True)
bd_meters = transformer.transform(bd_lat, bd_lon)
bd_point_meters = Point(bd_meters[0], bd_meters[1])
# # create Points from lat_da, lon_da in wgs84:
# dyn_lat = [Point(x, bd_lon) for x in lat_da.values[::2]]
# dyn_lon = [Point(bd_lat, x) for x in lon_da.values[::2]]
# transform to meters:
dyn_lat_meters = transformer.transform(lat_da.values, fixed_lon)
dyn_lon_meters = transformer.transform(fixed_lat, lon_da.values)
# calculate distance in km:
north_distance = [Point(dyn_lat_meters[0][x],dyn_lat_meters[1][x]).distance(bd_point_meters) / 1000 for x in range(lat_da.size)]
east_distance = [Point(dyn_lon_meters[0][x],dyn_lon_meters[1][x]).distance(bd_point_meters) / 1000 for x in range(lon_da.size)]
# sign change:
new_north_distance = [change_sign(lat_da.values[x], bd_lat, north_distance[x]) for x in range(lat_da.size)]
new_east_distance = [change_sign(lon_da.values[x], bd_lon, east_distance[x]) for x in range(lon_da.size)]
north = lat_da.copy(data=new_north_distance)
north.attrs['units'] = 'km'
north.attrs['long_name'] = 'distance north'
east = lon_da.copy(data=new_east_distance)
east.attrs['long_name'] = 'distance east'
east.attrs['units'] = 'km'
return north, east
elif method == 'slow':
bet_dagan = pd.DataFrame(index=[0])
bet_dagan['x'] = 34.81
bet_dagan['y'] = 32.01
bet_dagan_gdf = gpd.GeoDataFrame(
bet_dagan, geometry=gpd.points_from_xy(
bet_dagan['x'], bet_dagan['y']))
bet_dagan_gdf.crs = {'init': 'epsg:4326'}
# transform to israeli meters coords:
bet_dagan_gdf.to_crs(epsg=2039, inplace=True)
bd_as_point = bet_dagan_gdf.geometry[0]
bd_lon = bet_dagan.loc[0, 'x']
bd_lat = bet_dagan.loc[0, 'y']
df = lat_da.reset_coords(drop=True).to_dataframe(name='lat')
df['lon'] = lon_da.reset_coords(drop=True).to_dataframe()
# df = ds.reset_coords(drop=True).to_dataframe()
df['fixed_lon'] = 34.81 * np.ones(df['lon'].shape)
df['fixed_lat'] = 32.01 * np.ones(df['lat'].shape)
gdf_fixed_lon = gpd.GeoDataFrame(df, geometry=gpd.points_from_xy(df['fixed_lon'],
df.lat))
gdf_fixed_lon.crs = {'init': 'epsg:4326'}
gdf_fixed_lon.dropna(inplace=True)
gdf_fixed_lon.to_crs(epsg=2039, inplace=True)
gdf_fixed_lat = gpd.GeoDataFrame(df, geometry=gpd.points_from_xy(df.lon,
df['fixed_lat']))
gdf_fixed_lat.crs = {'init': 'epsg:4326'}
gdf_fixed_lat.dropna(inplace=True)
gdf_fixed_lat.to_crs(epsg=2039, inplace=True)
# calculate distance north from bet dagan coords in km:
df['north_distance'] = gdf_fixed_lon.geometry.distance(
bd_as_point) / 1000.0
# calculate distance east from bet dagan coords in km:
df['east_distance'] = gdf_fixed_lat.geometry.distance(
bd_as_point) / 1000.0
# fix sign to indicate: negtive = south:
df['north_distance'] = df.apply(
lambda x: change_sign(
x.lat, bd_lat, x.north_distance), axis=1)
# fix sign to indicate: negtive = east:
df['east_distance'] = df.apply(
lambda x: change_sign(
x.lon, bd_lon, x.east_distance), axis=1)
return df['north_distance'].to_xarray(), df['east_distance'].to_xarray()
#def produce_radiosonde_edt_north_east_distance(path=sound_path, savepath=None,
# verbose=True):
# from aux_gps import path_glob
# import geopandas as gpd
# import pandas as pd
# import xarray as xr
# import numpy as np
#
# def change_sign(x, y, value):
# if x <= y:
# return -value
# else:
# return value
# file = path_glob(path, 'bet_dagan_edt_sounding_*.nc')
# ds = xr.load_dataset(file[0])
# ds_geo = ds[['lat', 'lon']]
# # prepare bet dagan coords:
# bet_dagan = pd.DataFrame(index=[0])
# bet_dagan['x'] = 34.81
# bet_dagan['y'] = 32.01
# bet_dagan_gdf = gpd.GeoDataFrame(
# bet_dagan, geometry=gpd.points_from_xy(
# bet_dagan['x'], bet_dagan['y']))
# bet_dagan_gdf.crs = {'init': 'epsg:4326'}
# # transform to israeli meters coords:
# bet_dagan_gdf.to_crs(epsg=2039, inplace=True)
# bd_as_point = bet_dagan_gdf.geometry[0]
# bd_lon = bet_dagan.loc[0, 'x']
# bd_lat = bet_dagan.loc[0, 'y']
# ds_list = []
# for i in range(ds['sound_time'].size):
# record = ds['sound_time'].isel({'sound_time': i})
# record = record.dt.strftime('%Y-%m-%d %H:%M').values.item()
# if verbose:
# print('processing {}.'.format(record))
# sounding = ds_geo.isel({'sound_time': i})
# df = sounding.reset_coords(drop=True).to_dataframe()
# df['fixed_lon'] = 34.81 * np.ones(df['lon'].shape)
# df['fixed_lat'] = 32.01 * np.ones(df['lat'].shape)
# gdf_fixed_lon = gpd.GeoDataFrame(df, geometry=gpd.points_from_xy(df['fixed_lon'],
# df.lat))
# gdf_fixed_lon.crs = {'init': 'epsg:4326'}
# gdf_fixed_lon.dropna(inplace=True)
# gdf_fixed_lon.to_crs(epsg=2039, inplace=True)
# gdf_fixed_lat = gpd.GeoDataFrame(df, geometry=gpd.points_from_xy(df.lon,
# df['fixed_lat']))
# gdf_fixed_lat.crs = {'init': 'epsg:4326'}
# gdf_fixed_lat.dropna(inplace=True)
# gdf_fixed_lat.to_crs(epsg=2039, inplace=True)
# # calculate distance north from bet dagan coords in km:
# df['north_distance'] = gdf_fixed_lon.geometry.distance(
# bd_as_point) / 1000.0
# # calculate distance east from bet dagan coords in km:
# df['east_distance'] = gdf_fixed_lat.geometry.distance(
# bd_as_point) / 1000.0
# # fix sign to indicate: negtive = south:
# df['north_distance'] = df.apply(
# lambda x: change_sign(
# x.lat, bd_lat, x.north_distance), axis=1)
# # fix sign to indicate: negtive = east:
# df['east_distance'] = df.apply(
# lambda x: change_sign(
# x.lon, bd_lon, x.east_distance), axis=1)
# # convert to xarray:
# ds_list.append(df[['east_distance', 'north_distance']].to_xarray())
# ds_distance = xr.concat(ds_list, 'sound_time')
# ds_distance['sound_time'] = ds['sound_time']
# ds_distance.to_netcdf(savepath / 'bet_dagan_edt_distance.nc', 'w')
# return ds_distance
def analyse_radiosonde_climatology(path=sound_path, data_type='phys',
field='Rho_wv', month=3, season=None,
times=None, hour=None):
import xarray as xr
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.ticker import ScalarFormatter, LogLocator, NullFormatter
from aux_gps import path_glob
file = path_glob(path, 'bet_dagan_{}_sounding_*.nc'.format(data_type))
da = xr.load_dataset(file[0])[field]
if times is not None:
da = da.sel(sound_time=slice(*times))
if hour is not None:
da = da.sel(sound_time=da['sound_time.hour'] == hour)
try:
name = da.attrs['long_name']
except KeyError:
name = field
units = da.attrs['units']
if season is not None:
clim = da.groupby('sound_time.season').mean('sound_time')
df = clim.to_dataset('season').to_dataframe()
df_copy = df.copy()
seasons = [x for x in df.columns if season not in x]
df.reset_index(inplace=True)
# df.loc[:, season] -= df.loc[:, season]
df.loc[:, seasons[0]] -= df.loc[:, season]
df.loc[:, seasons[1]] -= df.loc[:, season]
df.loc[:, seasons[2]] -= df.loc[:, season]
fig, ax = plt.subplots(figsize=(12, 5))
df.plot(x=seasons[0], y='Height', logy=True, color='r', ax=ax)
df.plot(x=seasons[1], y='Height', logy=True, ax=ax, color='b')
df.plot(x=seasons[2], y='Height', logy=True, ax=ax, color='g')
ax.axvline(x=0, color='k')
# ax.set_xlim(-1, 15)
ax.legend(seasons+[season], loc='best')
else:
clim = da.groupby('sound_time.month').mean('sound_time')
if month == 12:
months = [11, 12, 1]
elif month == 1:
months = [12, 1, 2]
else:
months = [month - 1, month, month + 1]
df_copy = clim.to_dataset('month').to_dataframe()
df = clim.sel(month=months).to_dataset('month').to_dataframe()
month_names = pd.to_datetime(months, format='%m').month_name()
df.reset_index(inplace=True)
df.loc[:, months[0]] -= df.loc[:, month]
df.loc[:, months[2]] -= df.loc[:, month]
df.loc[:, months[1]] -= df.loc[:, month]
ax = df.plot(x=months[0], y='Height', logy=True, color='r')
df.plot(x=months[1], y='Height', logy=True, ax=ax, color='k')
df.plot(x=months[2], y='Height', logy=True, ax=ax, color='b')
ax.legend(month_names)
ax.set_xlabel('{} [{}]'.format(name, units))
ax.set_ylim(100, 10000)
ax.get_yaxis().set_major_formatter(ScalarFormatter())
locmaj = LogLocator(base=10,numticks=12)
ax.yaxis.set_major_locator(locmaj)
locmin = LogLocator(base=10.0,subs=(0.2,0.4,0.6,0.8),numticks=12)
ax.yaxis.set_minor_locator(locmin)
ax.yaxis.set_minor_formatter(NullFormatter())
ax.set_ylabel('height [m]')
if hour is not None:
ax.set_title('hour = {}'.format(hour))
return df_copy
def process_new_field_from_radiosonde_data(phys_ds, dim='sound_time',
field_name='pw', bottom=None,
top=None, verbose=False):
import xarray as xr
from aux_gps import keep_iqr
field_list = []
for i in range(phys_ds[dim].size):
record = phys_ds[dim].isel({dim: i})
if 'time' in dim:
record = record.dt.strftime('%Y-%m-%d %H:%M').values.item()
if verbose:
print('processing {} for {} field.'.format(record, field_name))
if field_name == 'pw':
long_name = 'Precipatiable water'
Dewpt = phys_ds['Dewpt'].isel({dim: i})
P = phys_ds['P'].isel({dim: i})
try:
field, unit = wrap_xr_metpy_pw(Dewpt, P, bottom=bottom, top=top)
except ValueError:
field, unit = wrap_xr_metpy_pw(Dewpt, P, bottom=None, top=None)
elif field_name == 'tm':
long_name = 'Water vapor mean air temperature'
P = phys_ds['P'].isel({dim: i})
T = phys_ds['T'].isel({dim: i})
RH = phys_ds['RH'].isel({dim: i})
if 'VP' not in phys_ds:
if 'MR' not in phys_ds:
MR = wrap_xr_metpy_mixing_ratio(P, T, RH, verbose=False)
VP = wrap_xr_metpy_vapor_pressure(P, MR)
else:
VP = phys_ds['VP'].isel({dim: i})
if 'Rho' not in phys_ds:
Rho = wrap_xr_metpy_density(P, T, MR, verbose=False)
else:
Rho = phys_ds['Rho'].isel({dim: i})
field, unit = calculate_tm_via_pressure_sum(VP, T, Rho, P,
bottom=bottom,
top=top)
elif field_name == 'ts':
long_name = 'Surface temperature'
if 'Height' in phys_ds['T'].dims:
dropped = phys_ds['T'].isel({dim: i}).dropna('Height')
elif 'time' in phys_ds['T'].dims:
dropped = phys_ds['T'].isel({dim: i}).dropna('time')
field = dropped[0].values.item() + 273.15
unit = 'K'
field_list.append(field)
da = xr.DataArray(field_list, dims=[dim])
da[dim] = phys_ds[dim]
da.attrs['units'] = unit
da.attrs['long_name'] = long_name
if top is not None:
da.attrs['top'] = top
if bottom is not None:
da.attrs['bottom'] = top
da = keep_iqr(da, dim=dim, k=1.5)
if verbose:
print('Done!')
return da
def process_radiosonde_data(path=sound_path, savepath=sound_path,
data_type='phys', station='bet_dagan', verbose=False):
import xarray as xr
from aux_gps import path_glob
file = path_glob(path, '{}_{}_sounding_*.nc'.format(data_type, station))
phys_ds = xr.load_dataset(file[0])
ds = xr.Dataset()
ds['PW'] = process_new_field_from_radiosonde_data(phys_ds, dim='sound_time',
field_name='pw',
bottom=None,
top=None, verbose=verbose)
ds['Tm'] = process_new_field_from_radiosonde_data(phys_ds, dim='sound_time',
field_name='tm',
bottom=None,
top=None, verbose=verbose)
ds['Ts'] = process_new_field_from_radiosonde_data(phys_ds, dim='sound_time',
field_name='ts',
bottom=None,
top=None, verbose=verbose)
if data_type == 'phys':
ds['cloud_code'] = phys_ds['cloud_code']
ds['sonde_type'] = phys_ds['sonde_type']
ds['min_time'] = phys_ds['min_time']
ds['max_time'] = phys_ds['max_time']
yr_min = ds['sound_time'].min().dt.year.item()
yr_max = ds['sound_time'].max().dt.year.item()
filename = '{}_{}_PW_Tm_Ts_{}-{}.nc'.format(station, data_type, yr_min, yr_max)
print('saving {} to {}'.format(filename, savepath))
ds.to_netcdf(savepath / filename, 'w')
print('Done!')
return ds
def calculate_tm_via_trapz_height(VP, T, H):
from scipy.integrate import cumtrapz
import numpy as np
# change T units to K:
T_copy = T.copy(deep=True) + 273.15
num = cumtrapz(VP / T_copy, H, initial=np.nan)
denom = cumtrapz(VP / T_copy**2, H, initial=np.nan)
tm = num / denom
return tm
def calculate_tm_via_pressure_sum(VP, T, Rho, P, bottom=None, top=None,
cumulative=False, verbose=False):
import pandas as pd
import numpy as np
def tm_sum(VP, T, Rho, P, bottom=None, top=None):
# slice for top and bottom:
if bottom is not None:
P = P.where(P <= bottom, drop=True)
T = T.where(P <= bottom, drop=True)
Rho = Rho.where(P <= bottom, drop=True)
VP = VP.where(P <= bottom, drop=True)
if top is not None:
P = P.where(P >= top, drop=True)
T = T.where(P >= top, drop=True)
Rho = Rho.where(P >= top, drop=True)
VP = VP.where(P >= top, drop=True)
# convert to Kelvin:
T_values = T.values + 273.15
# other units don't matter since it is weighted temperature:
VP_values = VP.values
P_values = P.values
Rho_values = Rho.values
# now the pressure sum method:
p = pd.Series(P_values)
dp = p.diff(-1).abs()
num = pd.Series(VP_values / (T_values * Rho_values))
num_sum = num.shift(-1) + num
numerator = (num_sum * dp / 2).sum()
denom = pd.Series(VP_values / (T_values**2 * Rho_values))
denom_sum = denom.shift(-1) + denom
denominator = (denom_sum * dp / 2).sum()
tm = numerator / denominator
return tm
try:
T_unit = T.attrs['units']
assert T_unit == 'degC'
except KeyError:
T_unit = 'degC'
if verbose:
print('assuming T units are degC...')
# check that VP and P have the same units:
assert P.attrs['units'] == VP.attrs['units']
P_values = P.values
if cumulative:
tm_list = []
# first value is nan:
tm_list.append(np.nan)
for pre_val in P_values[1:]:
if np.isnan(pre_val):
tm_list.append(np.nan)
continue
tm = tm_sum(VP, T, Rho, P, bottom=None, top=pre_val)
tm_list.append(tm)
tm = np.array(tm_list)
return tm, 'K'
else:
tm = tm_sum(VP, T, Rho, P, bottom=bottom, top=top)
return tm, 'K'
def wrap_xr_metpy_pw(dewpt, pressure, bottom=None, top=None, verbose=False,
cumulative=False):
from metpy.calc import precipitable_water
from metpy.units import units
import numpy as np
try:
T_unit = dewpt.attrs['units']
assert T_unit == 'degC'
except KeyError:
T_unit = 'degC'
if verbose:
print('assuming dewpoint units are degC...')
dew_values = dewpt.values * units(T_unit)
try:
P_unit = pressure.attrs['units']
assert P_unit == 'hPa'
except KeyError:
P_unit = 'hPa'
if verbose:
print('assuming pressure units are hPa...')
if top is not None:
top_with_units = top * units(P_unit)
else:
top_with_units = None
if bottom is not None:
bottom_with_units = bottom * units(P_unit)
else:
bottom_with_units = None
pressure_values = pressure.values * units(P_unit)
if cumulative:
pw_list = []
# first value is nan:
pw_list.append(np.nan)
for pre_val in pressure_values[1:]:
if np.isnan(pre_val):
pw_list.append(np.nan)
continue
pw = precipitable_water(pressure_values, dew_values, bottom=None,
top=pre_val)
pw_units = pw.units.format_babel('~P')
pw_list.append(pw.magnitude)
pw = np.array(pw_list)
return pw, pw_units
else:
pw = precipitable_water(pressure_values, dew_values,
bottom=bottom_with_units, top=top_with_units)
pw_units = pw.units.format_babel('~P')
return pw.magnitude, pw_units
def calculate_absolute_humidity_from_partial_pressure(VP, T, verbose=False):
Rs_v = 461.52 # Specific gas const for water vapour, J kg^{-1} K^{-1}
try:
VP_unit = VP.attrs['units']
assert VP_unit == 'hPa'
except KeyError:
VP_unit = 'hPa'
if verbose:
print('assuming vapor units are hPa...')
# convert to Pa:
VP_values = VP.values * 100.0
try:
T_unit = T.attrs['units']
assert T_unit == 'degC'
except KeyError:
T_unit = 'degC'
if verbose:
print('assuming temperature units are degree celsius...')
# convert to Kelvin:
T_values = T.values + 273.15
Rho_wv = VP_values/(Rs_v * T_values)
# resulting units are kg/m^3, convert to g/m^3':
Rho_wv *= 1000.0
Rho_wv
da = VP.copy(data=Rho_wv)
da.attrs['units'] = 'g/m^3'
da.attrs['long_name'] = 'Absolute humidity'
return da
def wrap_xr_metpy_specific_humidity(MR, verbose=False):
from metpy.calc import specific_humidity_from_mixing_ratio
from metpy.units import units
try:
MR_unit = MR.attrs['units']
assert MR_unit == 'g/kg'
except KeyError:
MR_unit = 'g/kg'
if verbose:
print('assuming mixing ratio units are gr/kg...')
MR_values = MR.values * units(MR_unit)
SH = specific_humidity_from_mixing_ratio(MR_values)
da = MR.copy(data=SH.magnitude)
da.attrs['units'] = MR_unit
da.attrs['long_name'] = 'Specific humidity'
return da
def calculate_atmospheric_refractivity(P, T, RH, verbose=False):
MR = wrap_xr_metpy_mixing_ratio(P, T, RH)
VP = wrap_xr_metpy_vapor_pressure(P, MR)
try:
T_unit = T.attrs['units']
assert T_unit == 'degC'
except KeyError:
T_unit = 'degC'
if verbose:
print('assuming temperature units are degree celsius...')
# convert to Kelvin:
T_k = T + 273.15
N = 77.6 * P / T_k + 3.73e5 * VP / T_k**2
N.attrs['units'] = 'dimensionless'
N.attrs['long_name'] = 'Index of Refractivity'
return N
def convert_wind_speed_direction_to_zonal_meridional(WS, WD, verbose=False):
# make sure it is right!
import numpy as np
# drop nans from WS and WD:
dim = list(set(WS.dims))[0]
assert dim == list(set(WD.dims))[0]
DS = WS.to_dataset(name='WS')
DS['WD'] = WD
# DS = DS.dropna(dim)
WS = DS['WS']
WD = DS['WD']
assert WS.size == WD.size
WD = 270 - WD
try:
WS_unit = WS.attrs['units']
if WS_unit != 'm/s':
if WS_unit == 'knots':
# 1knots= 0.51444445m/s
if verbose:
print('wind speed in knots, converting to m/s')
WS = WS * 0.51444445
WS.attrs.update(units='m/s')
except KeyError:
WS_unit = 'm/s'
if verbose:
print('assuming wind speed units are m/s...')
U = WS * np.cos(np.deg2rad(WD))
V = WS * np.sin(np.deg2rad(WD))
U.attrs['long_name'] = 'zonal_velocity'
U.attrs['units'] = 'm/s'
V.attrs['long_name'] = 'meridional_velocity'
V.attrs['units'] = 'm/s'
U.name = 'u'
V.name = 'v'
return U, V
#def compare_WW2014_to_Rib_all_seasons(path=sound_path, times=None,
# plot_type='hist', bins=25):
# import matplotlib.pyplot as plt
# import seaborn as sns
# if plot_type == 'hist' or plot_type == 'scatter':
# fig_hist, axs = plt.subplots(2, 2, sharex=False, sharey=True,
# figsize=(10, 8))
# seasons = ['DJF', 'MAM', 'JJA', 'SON']
# cmap = sns.color_palette("colorblind", 2)
# for i, ax in enumerate(axs.flatten()):
# ax = compare_WW2014_to_Rib_single_subplot(sound_path=path,
# season=seasons[i],
# times=times, ax=ax,
# colors=[cmap[0],
# cmap[1]],
# plot_type=plot_type,
# bins=bins)
# fig_hist.tight_layout()
# return
#def compare_WW2014_to_Rib_single_subplot(sound_path=sound_path, season=None,
# times=None, bins=None,
# ax=None, colors=None,
# plot_type='hist'):
# from aux_gps import path_glob
# import xarray as xr
# from PW_from_gps_figures import plot_two_histograms_comparison
# ww_file = path_glob(sound_path, 'MLH_WW2014_*.nc')[-1]
# ww = xr.load_dataarray(ww_file)
# rib_file = path_glob(sound_path, 'MLH_Rib_*.nc')[-1]
# rib = xr.load_dataarray(rib_file)
# ds = ww.to_dataset(name='MLH_WW')
# ds['MLH_Rib'] = rib
# if season is not None:
# ds = ds.sel(sound_time=ds['sound_time.season'] == season)
# print('selected {} season'.format(season))
# labels = ['MLH-Rib for {}'.format(season), 'MLH-WW for {}'.format(season)]
# else:
# labels = ['MLH-Rib Annual', 'MLH-WW Annual']
# if times is not None:
# ds = ds.sel(sound_time=slice(*times))
# print('selected {}-{} period'.format(*times))
# title = 'Bet-Dagan radiosonde {}-{} period'.format(*times)
# else:
# times = [ds.sound_time.min().dt.year.item(),
# ds.sound_time.max().dt.year.item()]
# title = 'Bet-Dagan radiosonde {}-{} period'.format(*times)
# if plot_type == 'hist':
# ax = plot_two_histograms_comparison(ds['MLH_Rib'], ds['MLH_WW'],
# ax=ax, labels=labels,
# colors=colors, bins=bins)
# ax.legend()
# ax.set_ylabel('Frequency')
# ax.set_xlabel('MLH [m]')
# ax.set_title(title)
# elif plot_type == 'scatter':
# if ax is None:
# fig, ax = plt.subplots()
# ax.scatter(ds['MLH_Rib'].values, ds['MLH_WW'].values)
# ax.set_xlabel(labels[0].split(' ')[0] + ' [m]')
# ax.set_ylabel(labels[1].split(' ')[0] + ' [m]')
# season_label = labels[0].split(' ')[-1]
# ax.plot(ds['MLH_Rib'], ds['MLH_Rib'], c='r')
# ax.legend(['y = x', season_label], loc='upper right')
# ax.set_title(title)
# return ax
#def calculate_Wang_and_Wang_2014_MLH_all_profiles(sound_path=sound_path,
# data_type='phys',
# hour=12, plot=True,
# savepath=None):
# import xarray as xr
# from aux_gps import smooth_xr
# import matplotlib.pyplot as plt
# import seaborn as sns
# from aux_gps import save_ncfile
# from PW_from_gps_figures import plot_seasonal_histogram
# if data_type == 'phys':
# bd = xr.load_dataset(sound_path / 'bet_dagan_phys_sounding_2007-2019.nc')
# elif data_type == 'edt':
# bd = xr.load_dataset(sound_path / 'bet_dagan_edt_sounding_2016-2019.nc')
# # N = calculate_atmospheric_refractivity(bd['P'], bd['T'], bd['VP'])
# # assemble all WW vars:
# WW = bd['N'].to_dataset(name='N')
# WW['RH'] = bd['RH']
# WW['PT'] = bd['PT']
# WW['MR'] = bd['MR']
# # slice hour:
# WW = WW.sel(sound_time=WW['sound_time.hour'] == hour)
# # produce gradients:
# WW_grad = WW.differentiate('Height', edge_order=2)
# # smooth them with 1-2-1 smoother:
# WW_grad_smoothed = smooth_xr(WW_grad, 'Height')
## return WW_grad_smoothed
# mlhs = []
# for dt in WW_grad_smoothed.sound_time:
# df = WW_grad_smoothed.sel(sound_time=dt).reset_coords(drop=True).to_dataframe()
# mlhs.append(calculate_Wang_and_Wang_2014_MLH_single_profile(df, plot=False))
# mlh = xr.DataArray(mlhs, dims=['sound_time'])
# mlh['sound_time'] = WW_grad_smoothed['sound_time']
# mlh.name = 'MLH'
# mlh.attrs['long_name'] = 'Mixing layer height'
# mlh.attrs['units'] = 'm'
# mlh.attrs['method'] = 'W&W2014 using PT, N, MR and RH'
# if savepath is not None:
# filename = 'MLH_WW2014_{}_{}.nc'.format(data_type, hour)
# save_ncfile(mlh, sound_path, filename)
# if plot:
# cmap = sns.color_palette("colorblind", 5)
# fig, ax = plt.subplots(3, 1, sharex=True, figsize=(12, 9))
# df_mean = mlh.groupby('sound_time.month').mean().to_dataframe('mean_MLH')
# df_mean.plot(color=cmap, ax=ax[0])
# ax[0].grid()
# ax[0].set_ylabel('Mean MLH [m]')
# ax[0].set_title(
# 'Annual mixing layer height from Bet-Dagan radiosonde profiles ({}Z) using W&W2014 method'.format(hour))
# df_std = mlh.groupby('sound_time.month').std().to_dataframe('std_MLH')
# df_std.plot(color=cmap, ax=ax[1])
# ax[1].grid()
# ax[1].set_ylabel('Std MLH [m]')
# df_count = mlh.groupby('sound_time.month').count().to_dataframe('count_MLH')
# df_count.plot(color=cmap, ax=ax[2])
# ax[2].grid()
# ax[2].set_ylabel('Count MLH [#]')
# fig.tight_layout()
# plot_seasonal_histogram(mlh, dim='sound_time', xlim=(-100, 3000),
# xlabel='MLH [m]',
# suptitle='MLH histogram using W&W 2014 method')
# return mlh
#def calculate_Wang_and_Wang_2014_MLH_single_profile(df, alt_cutoff=3000,
# plot=True):
# import pandas as pd
# import numpy as np
# import matplotlib.pyplot as plt
# # first , cutoff:
# df = df.loc[0: alt_cutoff]
# if plot:
## df.plot(subplots=True)
# fig, ax = plt.subplots(1, 4, figsize=(20, 16))
# df.loc[0: 1200, 'PT'].reset_index().plot.line(y='Height', x='PT', ax=ax[0], legend=False)
# df.loc[0: 1200, 'RH'].reset_index().plot.line(y='Height', x='RH', ax=ax[1], legend=False)
# df.loc[0: 1200, 'MR'].reset_index().plot.line(y='Height', x='MR', ax=ax[2], legend=False)
# df.loc[0: 1200, 'N'].reset_index().plot.line(y='Height', x='N', ax=ax[3], legend=False)
# [x.grid() for x in ax]
# ind = np.arange(1, 11)
# pt10 = df['PT'].nlargest(n=10).index.values
# n10 = df['N'].nsmallest(n=10).index.values
# rh10 = df['RH'].nsmallest(n=10).index.values
# mr10 = df['MR'].nsmallest(n=10).index.values
# ten = pd.DataFrame([pt10, n10, rh10, mr10]).T
# ten.columns = ['PT', 'N', 'RH', 'MR']
# ten.index = ind
# for i, vc_df in ten.iterrows():
# mlh_0 = vc_df.value_counts()[vc_df.value_counts() > 2]
# if mlh_0.empty:
# continue
# else:
# mlh = mlh_0.index.item()
# return mlh
# print('MLH Not found using W&W!')
# return np.nan
def plot_pblh_radiosonde(path=sound_path, reduce='median', fontsize=20):
import xarray as xr
import matplotlib.pyplot as plt
import numpy as np
pblh = xr.load_dataset(
sound_path /
'PBLH_classification_bet_dagan_2s_sounding_2014-2019.nc')
if reduce == 'median':
pblh_r = pblh.groupby('sound_time.month').median()
elif reduce == 'mean':
pblh_r = pblh.groupby('sound_time.month').mean()
pblh_c = pblh.groupby('sound_time.month').count()
count_total = pblh_c.sum()
df = pblh_r.to_dataframe()
df[['SBLH_c', 'RBLH_c', 'CBLH_c']] = pblh_c.to_dataframe()
fig, axes = plt.subplots(3, 1, sharex=False, sharey=False, figsize=(10, 10))
line_color = 'black'
bar_color = 'tab:orange'
df['CBLH'].plot(ax=axes[0], linewidth=2, color=line_color, marker='o', label='CBL', legend=True)
tw_0 = axes[0].twinx()
tw_0.bar(x=df.index.values, height=df['CBLH_c'].values, color=bar_color, alpha=0.4)
df['RBLH'].plot(ax=axes[1], linewidth=2, color=line_color, marker='o', label='RBL', legend=True)
tw_1 = axes[1].twinx()
tw_1.bar(x=df.index.values, height=df['RBLH_c'].values, color=bar_color, alpha=0.4)
df['SBLH'].plot(ax=axes[2], linewidth=2, color=line_color, marker='o', label='SBL', legend=True)
tw_2 = axes[2].twinx()
tw_2.bar(x=df.index.values, height=df['SBLH_c'].values, color=bar_color, alpha=0.4)
axes[0].set_ylabel('CBL [m]', fontsize=fontsize)
axes[1].set_ylabel('RBL [m]', fontsize=fontsize)
axes[2].set_ylabel('SBL [m]', fontsize=fontsize)
tw_0.set_ylabel('Launch ({} total)'.format(count_total['CBLH'].values), fontsize=fontsize)
tw_1.set_ylabel('Launch ({} total)'.format(count_total['RBLH'].values), fontsize=fontsize)
tw_2.set_ylabel('Launch ({} total)'.format(count_total['SBLH'].values), fontsize=fontsize)
[ax.set_xticks(np.arange(1,13,1)) for ax in axes]
[ax.grid() for ax in axes]
[ax.tick_params(labelsize=fontsize) for ax in axes]
[ax.tick_params(labelsize=fontsize) for ax in [tw_0, tw_1, tw_2]]
fig.suptitle(
'PBL {} Height from Bet-Dagan radiosonde (2014-2019)'.format(reduce),
fontsize=fontsize)
fig.tight_layout()
return fig
def align_rbl_times_cloud_h1_pwv(rbl_cat, path=work_yuval,
ceil_path=ceil_path, pw_station='tela',
plot_diurnal=True, fontsize=16):
from ceilometers import read_BD_ceilometer_yoav_all_years
import xarray as xr
import matplotlib.pyplot as plt
from aux_gps import anomalize_xr
import numpy as np
# first load cloud_H1 and pwv:
cld = read_BD_ceilometer_yoav_all_years(path=ceil_path)['cloud_H1']
cld[cld==0]=np.nan
ds = cld.to_dataset(name='cloud_H1')
pwv = xr.open_dataset(
path /
'GNSS_PW_thresh_50.nc')[pw_station]
pwv.load()
pw_name = 'pwv_{}'.format(pw_station)
bins_name = '{}'.format(rbl_cat.name)
ds[pw_name] = pwv.sel(time=pwv['time.season']=='JJA')
daily_pwv_total = ds[pw_name].groupby('time.hour').count().sum()
print(daily_pwv_total)
daily_pwv = anomalize_xr(ds[pw_name]).groupby('time.hour').mean()
# now load rbl_cat with attrs:
ds[bins_name] = rbl_cat
ds = ds.dropna('time')
# change dtype of bins to int:
ds[bins_name] = ds[bins_name].astype(int)
# produce pwv anomalies regarding the bins:
pwv_anoms = ds[pw_name].groupby(ds[bins_name]) - ds[pw_name].groupby(ds[bins_name]).mean('time')
counts = ds.groupby('time.hour').count()['cloud_H1']
ds['pwv_{}_anoms'.format(pw_station)] = pwv_anoms.reset_coords(drop=True)
if plot_diurnal:
fig, axes = plt.subplots(figsize=(15, 8))
df_hour = ds['pwv_tela_anoms'].groupby('time.hour').mean().to_dataframe()
df_hour['cloud_H1'] = ds['cloud_H1'].groupby('time.hour').mean()
df_hour['cloud_H1_counts'] = counts
df_hour['pwv_tela_daily_anoms'] = daily_pwv
df_hour['pwv_tela_anoms'].plot(marker='s', ax=axes, linewidth=2)
df_hour['pwv_tela_daily_anoms'].plot(ax=axes, marker='s', color='r', linewidth=2)
# ax2 = df_hour['cloud_H1'].plot(ax=axes[0], secondary_y=True, marker='o')
ax2 = df_hour['cloud_H1_counts'].plot(ax=axes, secondary_y=True, marker='o', linewidth=2)
axes.set_ylabel('PWV TELA anomalies [mm]', fontsize=fontsize)
axes.set_xlabel('Hour of day [UTC]', fontsize=fontsize)
ax2.set_ylabel('Cloud H1 data points', fontsize=fontsize)
axes.set_xticks(np.arange(0, 24, 1))
axes.xaxis.grid()
handles,labels = [],[]
for ax in fig.axes:
for h,l in zip(*ax.get_legend_handles_labels()):
handles.append(h)
labels.append(l)
axes.legend(handles,labels, fontsize=fontsize)
# counts.to_dataframe(name='Count').plot(kind='bar', color='tab:blue', alpha=0.5, ax=axes[1], rot=0)
# axes[1].bar(x=np.arange(0, 24, 1), height=counts.values, color='tab:blue', alpha=0.5)
# axes[1].set_xticks(np.arange(0, 24, 1))
axes.tick_params(labelsize=fontsize)
ax2.tick_params(labelsize=fontsize)
fig.tight_layout()
fig.suptitle('PWV TELA anomalies and Cloud H1 counts for JJA', fontsize=fontsize)
fig.subplots_adjust(top=0.951,
bottom=0.095,
left=0.071,
right=0.936,
hspace=0.2,
wspace=0.2)
return ds
def categorize_da_ts(da_ts, season=None, add_hours_to_dt=None, resample=True,
bins=[0, 200, 400, 800, 1000, 1200, 1400, 1600, 1800, 2000, 2500]):
# import xarray as xr
import numpy as np
import pandas as pd
time_dim = list(set(da_ts.dims))[0]
if season is not None:
da_ts = da_ts.sel(
{time_dim: da_ts['{}.season'.format(time_dim)] == season})
print('{} season selected'.format(season))
# bins = rbl.quantile(
# [0.0, 0.125, 0.25, 0.375, 0.5, 0.625, 0.75, 0.875, 1.0])
if da_ts.name is None:
name = 'MLH'
else:
name = da_ts.name
# rename sound_time to time:
da_ts = da_ts.rename({time_dim: 'time'})
df = da_ts.to_dataframe(name=name)
labels = np.arange(0, len(bins) - 1)
df['{}_bins'.format(name)] = pd.cut(
df['{}'.format(name)], bins=bins, labels=labels, retbins=False)
df_bins = df['{}_bins'.format(name)]
if add_hours_to_dt is not None:
print('adding {} hours to datetimes.'.format(add_hours_to_dt))
df_bins.index += pd.Timedelta(add_hours_to_dt, unit='H')
if resample:
re = []
for row in df_bins.dropna().to_frame().iterrows():
bin1 = row[1].values
new_time = pd.date_range(row[0], periods=288, freq='5T')
new_bins = [bin1 for x in new_time]
re.append(pd.DataFrame(new_bins, index=new_time, columns=['{}_bins'.format(name)]))
# df_bins = df_bins.resample('5T').ffill(limit=576).dropna()
df_bins = pd.concat(re, axis=0)
print('resampling to 5 mins using ffill.')
# result = xr.apply_ufunc(np.digitize, rbl, kwargs={'bins': bins})
# df = result.to_dataframe('bins')
# df['rbl'] = rbl.to_dataframe(name='rbl')
# means = df['rbl'].groupby(df['bins']).mean()
# or just:
# rbl_bins = rbl.to_dataset(name='rbl').groupby_bins(group='rbl',bins=bins, labels=np.arange(1, len(bins))).groups
# grp = df.groupby('{}_bins'.format(name)).groups
print('categorizing to bins: {}'.format(','.join([str(x) for x in bins])))
df_bins.index.name = 'time'
da = df_bins.to_xarray().to_array(name='{}_bins'.format(name)).squeeze(drop=True)
# get the bins borders and insert them as attrs to da:
dumm = pd.cut(df['{}'.format(name)], bins=bins, labels=None, retbins=False)
left = [x.left for x in dumm.dtype.categories]
right = [x.right for x in dumm.dtype.categories]
for i, label in enumerate(labels):
da.attrs[str(label)] = [float(left[i]), float(right[i])]
da.attrs['units'] = da_ts.attrs['units']
return da
def prepare_radiosonde_and_solve_MLH(ds, method='T', max_height=300):
import xarray as xr
import pandas as pd
ds = ds.drop_sel(time=pd.to_timedelta(0, unit='s'))
# nullify the first Height: