-
Notifications
You must be signed in to change notification settings - Fork 13
/
ims_procedures.py
2190 lines (2093 loc) · 92.8 KB
/
ims_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 Mon Jun 10 17:22:51 2019
Work flow: to obtain the TD products for use with ZWD (after download):
1)use fill_fix_all_10mins_IMS_stations() after copying the downloaded TD
2)use IMS_interpolating_to_GNSS_stations_israel(dt=None, start_year=2019(latest))
3)use resample_GNSS_TD(path=ims_path) to resample all TD
@author: ziskin
"""
from PW_paths import work_yuval
from pathlib import Path
ims_path = work_yuval / 'IMS_T'
gis_path = work_yuval / 'gis'
ims_10mins_path = ims_path / '10mins'
awd_path = work_yuval/'AW3D30'
axis_path = work_yuval/'axis'
cwd = Path().cwd()
# fill missing data:
#some_missing = ds.tmin.sel(time=ds['time.day'] > 15).reindex_like(ds)
#
#In [20]: filled = some_missing.groupby('time.month').fillna(climatology.tmin)
#
#In [21]: both = xr.Dataset({'some_missing': some_missing, 'filled': filled})
# kabr, nzrt, katz, elro, klhv, yrcm, slom have ims stations not close to them!
gnss_ims_dict = {
'alon': 'ASHQELON-PORT', 'bshm': 'HAIFA-TECHNION', 'csar': 'HADERA-PORT',
'tela': 'TEL-AVIV-COAST', 'slom': 'BESOR-FARM', 'kabr': 'SHAVE-ZIYYON',
'nzrt': 'DEIR-HANNA', 'katz': 'GAMLA', 'elro': 'MEROM-GOLAN-PICMAN',
'mrav': 'MAALE-GILBOA', 'yosh': 'ARIEL', 'jslm': 'JERUSALEM-GIVAT-RAM',
'drag': 'METZOKE-DRAGOT', 'dsea': 'SEDOM', 'ramo': 'MIZPE-RAMON-20120927',
'nrif': 'NEOT-SMADAR', 'elat': 'ELAT', 'klhv': 'SHANI',
'yrcm': 'ZOMET-HANEGEV', 'spir': 'PARAN-20060124', 'nizn': 'EZUZ'}
ims_units_dict = {
'BP': 'hPa',
'NIP': 'W/m^2',
'Rain': 'mm',
'TD': 'deg_C',
'WD': 'deg',
'WS': 'm/s',
'U': 'm/s',
'V': 'm/s',
'G': ''}
def save_IMS_long_term_time_series_station_stats(path=ims_10mins_path, min_year='1996',
channel_name='TD', time_dim='time'):
from aux_gps import path_glob
import xarray as xr
from aux_gps import save_ncfile
files = path_glob(path, '*_{}_10mins.nc'.format(channel_name))
dsl = [xr.open_dataarray(x) for x in files]
das = []
for ds in dsl:
df = ds.to_dataframe()
station = ds.name
df['month'] = df.index.month
df['hour'] = df.index.hour
da = df.groupby(['month', 'hour']).mean().to_xarray()
# dff = df.groupby(['month', 'hour']).transform('mean')
# dff = dff.loc[min_year:]
# if dff.empty:
# continue
# da = dff.to_xarray()
da[station].attrs = ds.attrs
das.append(da)
ds = xr.merge(das, compat='override')
ds = ds.expand_dims('agg')
ds['agg'] = ['mean']
save_ncfile(ds, path, 'IMS_{}_month_hour_stats.nc'.format(channel_name))
return ds
def save_daily_IMS_params_at_GNSS_loc(ims_path=ims_path,
param_name='WS', stations=[x for x in gnss_ims_dict.keys()]):
import xarray as xr
from aux_gps import save_ncfile
param = xr.open_dataset(
ims_path / 'IMS_{}_israeli_10mins.nc'.format(param_name))
ims_stns = [gnss_ims_dict.get(x) for x in stations]
param = param[ims_stns]
param = param.resample(time='D', keep_attrs=True).mean(keep_attrs=True)
inv_dict = {v: k for k, v in gnss_ims_dict.items()}
for da in param:
param = param.rename({da: inv_dict.get(da)})
filename = 'GNSS_{}_daily.nc'.format(param_name)
save_ncfile(param, ims_path, filename)
return param
def produce_bet_dagan_long_term_pressure(path=ims_path, rate='1H',
savepath=None, fill_from_jerusalem=True):
import xarray as xr
from aux_gps import xr_reindex_with_date_range
from aux_gps import get_unique_index
from aux_gps import save_ncfile
from aux_gps import anomalize_xr
# load manual old measurements and new 3 hr ones:
bd_man = xr.open_dataset(
path / 'IMS_hourly_03hr.nc')['BET-DAGAN-MAN_2520_ps']
bd_auto = xr.open_dataset(path / 'IMS_hourly_03hr.nc')['BET-DAGAN_2523_ps']
bd = xr.concat(
[bd_man.dropna('time'), bd_auto.dropna('time')], 'time', join='inner')
bd = get_unique_index(bd)
bd = bd.sortby('time')
bd = xr_reindex_with_date_range(bd, freq='1H')
# remove dayofyear mean, interpolate and reconstruct signal to fill it with climatology:
climatology = bd.groupby('time.dayofyear').mean(keep_attrs=True)
bd_anoms = anomalize_xr(bd, freq='DOY')
bd_inter = bd_anoms.interpolate_na(
'time', method='cubic', max_gap='24H', keep_attrs=True)
# bd_inter = bd.interpolate_na('time', max_gap='3H', method='cubic')
bd_inter = bd_inter.groupby('time.dayofyear') + climatology
bd_inter = bd_inter.reset_coords(drop=True)
# load 10-mins new measurements:
bd_10 = xr.open_dataset(path / 'IMS_BP_israeli_hourly.nc')['BET-DAGAN']
bd_10 = bd_10.dropna('time').sel(
time=slice(
'2019-06-30T00:00:00',
None)).resample(
time='1H').mean()
bd_inter = xr.concat([bd_inter, bd_10], 'time', join='inner')
bd_inter = get_unique_index(bd_inter)
bd_inter = bd_inter.sortby('time')
bd_inter.name = 'bet-dagan'
bd_inter.attrs['action'] = 'interpolated from 3H'
if fill_from_jerusalem:
print('filling missing gaps from 2018 with jerusalem')
jr_10 = xr.load_dataset(
path / 'IMS_BP_israeli_hourly.nc')['JERUSALEM-CENTRE']
climatology = bd_inter.groupby('time.dayofyear').mean(keep_attrs=True)
jr_10_anoms = anomalize_xr(jr_10, 'DOY')
bd_anoms = anomalize_xr(bd_inter, 'DOY')
bd_anoms = xr.concat(
[bd_anoms.dropna('time'), jr_10_anoms.dropna('time')], 'time', join='inner')
bd_anoms = get_unique_index(bd_anoms)
bd_anoms = bd_anoms.sortby('time')
bd_anoms = xr_reindex_with_date_range(bd_anoms, freq='5T')
bd_anoms = bd_anoms.interpolate_na(
'time', method='cubic', max_gap='2H')
bd_anoms.name = 'bet-dagan'
bd_anoms.attrs['action'] = 'interpolated from 3H'
bd_anoms.attrs['filled'] = 'using Jerusalem-centre'
bd_anoms.attrs['long_name'] = 'Pressure Anomalies'
bd_anoms.attrs['units'] = 'hPa'
bd_inter = bd_anoms.groupby('time.dayofyear') + climatology
bd_inter = bd_inter.resample(
time='1H', keep_attrs=True).mean(keep_attrs=True)
# if savepath is not None:
# yr_min = bd_anoms.time.min().dt.year.item()
# yr_max = bd_anoms.time.max().dt.year.item()
# filename = 'IMS_BD_anoms_5min_ps_{}-{}.nc'.format(
# yr_min, yr_max)
# save_ncfile(bd_anoms, savepath, filename)
# return bd_anoms
if savepath is not None:
# filename = 'IMS_BD_hourly_ps.nc'
yr_min = bd_inter.time.min().dt.year.item()
yr_max = bd_inter.time.max().dt.year.item()
filename = 'IMS_BD_hourly_ps_{}-{}.nc'.format(yr_min, yr_max)
save_ncfile(bd_inter, savepath, filename)
bd_anoms = anomalize_xr(bd_inter, 'DOY', units='std')
filename = 'IMS_BD_hourly_anoms_std_ps_{}-{}.nc'.format(yr_min, yr_max)
save_ncfile(bd_anoms, savepath, filename)
bd_anoms = anomalize_xr(bd_inter, 'DOY')
filename = 'IMS_BD_hourly_anoms_ps_{}-{}.nc'.format(yr_min, yr_max)
save_ncfile(bd_anoms, savepath, filename)
return bd_inter
def transform_wind_speed_direction_to_u_v(path=ims_path, savepath=ims_path):
import xarray as xr
import numpy as np
WS = xr.load_dataset(path / 'IMS_WS_israeli_10mins.nc')
WD = xr.load_dataset(path / 'IMS_WD_israeli_10mins.nc')
# change angles to math:
WD = 270 - WD
U = WS * np.cos(np.deg2rad(WD))
V = WS * np.sin(np.deg2rad(WD))
print('updating attrs...')
for station in WS:
attrs = WS[station].attrs
attrs.update(channel_name='U')
attrs.update(units='m/s')
attrs.update(field_name='zonal velocity')
U[station].attrs = attrs
attrs.update(channel_name='V')
attrs.update(field_name='meridional velocity')
V[station].attrs = attrs
if savepath is not None:
filename = 'IMS_U_israeli_10mins.nc'
comp = dict(zlib=True, complevel=9) # best compression
encoding = {var: comp for var in U.data_vars}
U.to_netcdf(savepath / filename, 'w', encoding=encoding)
filename = 'IMS_V_israeli_10mins.nc'
comp = dict(zlib=True, complevel=9) # best compression
encoding = {var: comp for var in V.data_vars}
V.to_netcdf(savepath / filename, 'w', encoding=encoding)
print('Done!')
return
def perform_harmonic_analysis_all_IMS(path=ims_path, var='BP', n=4,
savepath=ims_path):
import xarray as xr
from aux_gps import harmonic_analysis_xr
from aux_gps import keep_iqr
ims = xr.load_dataset(path / 'IMS_{}_israeli_10mins.nc'.format(var))
sites = [x for x in gnss_ims_dict.values()]
ims_actual_sites = [x for x in ims if x in sites]
ims = ims[ims_actual_sites]
if var == 'NIP':
ims = xr.merge([keep_iqr(ims[x]) for x in ims])
max_nip = ims.to_array('site').max()
ims /= max_nip
dss_list = []
for site in ims:
da = ims[site]
da = keep_iqr(da)
print('performing harmonic analysis for IMS {} field at {} site:'.format(var, site))
dss = harmonic_analysis_xr(da, n=n, anomalize=True, normalize=False)
dss_list.append(dss)
dss_all = xr.merge(dss_list)
dss_all.attrs['field'] = var
dss_all.attrs['units'] = ims_units_dict[var]
if savepath is not None:
filename = 'IMS_{}_harmonics_diurnal.nc'.format(var)
comp = dict(zlib=True, complevel=9) # best compression
encoding = {var: comp for var in dss_all.data_vars}
dss_all.to_netcdf(savepath / filename, 'w', encoding=encoding)
print('Done!')
return dss_all
def align_10mins_ims_to_gnss_and_save(ims_path=ims_path, field='G7',
gnss_ims_dict=gnss_ims_dict,
savepath=work_yuval):
import xarray as xr
d = dict(zip(gnss_ims_dict.values(), gnss_ims_dict.keys()))
gnss_list = []
for station, gnss_site in d.items():
print('loading IMS station {}'.format(station))
ims_field = xr.load_dataset(
ims_path / 'IMS_{}_israeli_10mins.nc'.format(field))[station]
gnss = ims_field.load()
gnss.name = gnss_site
gnss.attrs['IMS_station'] = station
gnss_list.append(gnss)
gnss_sites = xr.merge(gnss_list)
if savepath is not None:
filename = 'GNSS_IMS_{}_israeli_10mins.nc'.format(field)
print('saving {} to {}'.format(filename, savepath))
comp = dict(zlib=True, complevel=9) # best compression
encoding = {var: comp for var in gnss_sites.data_vars}
gnss_sites.to_netcdf(savepath / filename, 'w', encoding=encoding)
print('Done!')
return gnss_sites
def produce_10mins_gustiness(path=ims_path, rolling=5):
import xarray as xr
from aux_gps import keep_iqr
from aux_gps import xr_reindex_with_date_range
ws = xr.load_dataset(path / 'IMS_WS_israeli_10mins.nc')
stations = [x for x in ws.data_vars]
g_list = []
for station in stations:
print('proccesing station {}'.format(station))
attrs = ws[station].attrs
g = ws[station].rolling(time=rolling, center=True).std(
) / ws[station].rolling(time=rolling, center=True).mean()
g = keep_iqr(g)
g = xr_reindex_with_date_range(g, freq='10min')
g.name = station
g.attrs = attrs
g_list.append(g)
G = xr.merge(g_list)
filename = 'IMS_G{}_israeli_10mins.nc'.format(rolling)
print('saving {} to {}'.format(filename, path))
comp = dict(zlib=True, complevel=9) # best compression
encoding = {var: comp for var in G.data_vars}
G.to_netcdf(path / filename, 'w', encoding=encoding)
print('Done resampling!')
return G
def produce_10mins_absolute_humidity(path=ims_path):
from sounding_procedures import wrap_xr_metpy_mixing_ratio
from aux_gps import dim_intersection
import xarray as xr
P = xr.load_dataset(path / 'IMS_BP_israeli_10mins.nc')
stations = [x for x in P.data_vars]
T = xr.open_dataset(path / 'IMS_TD_israeli_10mins.nc')
T = T[stations].load()
RH = xr.open_dataset(path / 'IMS_RH_israeli_10mins.nc')
RH = RH[stations].load()
mr_list = []
for station in stations:
print('proccesing station {}'.format(station))
p = P[station]
t = T[station]
rh = RH[station]
new_time = dim_intersection([p, t, rh])
p = p.sel(time=new_time)
rh = rh.sel(time=new_time)
t = t.sel(time=new_time)
mr = wrap_xr_metpy_mixing_ratio(p, t, rh, verbose=True)
mr_list.append(mr)
MR = xr.merge(mr_list)
filename = 'IMS_MR_israeli_10mins.nc'
print('saving {} to {}'.format(filename, path))
comp = dict(zlib=True, complevel=9) # best compression
encoding = {var: comp for var in MR.data_vars}
MR.to_netcdf(path / filename, 'w', encoding=encoding)
print('Done resampling!')
return MR
def produce_wind_frequency_gustiness(path=ims_path,
station='TEL-AVIV-COAST',
season='DJF', plot=True):
import xarray as xr
import matplotlib.pyplot as plt
import numpy as np
from aux_gps import keep_iqr
ws = xr.open_dataset(path / 'IMS_WS_israeli_10mins.nc')[station]
ws.load()
ws = ws.sel(time=ws['time.season'] == season)
gustiness = ws.rolling(time=5).std() / ws.rolling(time=5).mean()
gustiness = keep_iqr(gustiness)
gustiness_anoms = gustiness.groupby(
'time.month') - gustiness.groupby('time.month').mean('time')
gustiness_anoms = gustiness_anoms.reset_coords(drop=True)
G = gustiness_anoms.groupby('time.hour').mean('time')
wd = xr.open_dataset(path / 'IMS_WD_israeli_10mins.nc')[station]
wd.load()
wd.name = 'WD'
wd = wd.sel(time=wd['time.season'] == season)
all_Q = wd.groupby('time.hour').count()
Q1 = wd.where((wd >= 0) & (wd < 90)).dropna('time')
Q2 = wd.where((wd >= 90) & (wd < 180)).dropna('time')
Q3 = wd.where((wd >= 180.1) & (wd < 270)).dropna('time')
Q4 = wd.where((wd >= 270) & (wd < 360)).dropna('time')
Q = xr.concat([Q1, Q2, Q3, Q4], 'Q')
Q['Q'] = [x + 1 for x in range(4)]
Q_freq = 100.0 * (Q.groupby('time.hour').count() / all_Q)
if plot:
fig, ax = plt.subplots(figsize=(16, 8))
for q in Q_freq['Q']:
Q_freq.sel(Q=q).plot(ax=ax)
ax.set_title(
'Relative wind direction frequency in {} IMS station in {} season'.format(
station, season))
ax.set_ylabel('Relative frequency [%]')
ax.set_xlabel('Time of day [UTC]')
ax.set_xticks(np.arange(0, 24, step=1))
ax.legend([r'0$\degree$-90$\degree$', r'90$\degree$-180$\degree$',
r'180$\degree$-270$\degree$', r'270$\degree$-360$\degree$'], loc='upper left')
ax.grid()
ax2 = ax.twinx()
G.plot.line(ax=ax2, color='k', marker='o')
ax2.axhline(0, color='k', linestyle='--')
ax2.legend(['{} Gustiness anomalies'.format(station)],
loc='upper right')
ax2.set_ylabel('Gustiness anomalies')
return
def produce_gustiness(path=ims_path,
station='TEL-AVIV-COAST',
season='DJF', pw_station='tela', temp=False,
ax=None):
import xarray as xr
import matplotlib.pyplot as plt
import numpy as np
from aux_gps import keep_iqr
from aux_gps import groupby_date_xr
from matplotlib.ticker import FixedLocator
def align_yaxis(ax1, v1, ax2, v2):
"""adjust ax2 ylimit so that v2 in ax2 is aligned to v1 in ax1"""
_, y1 = ax1.transData.transform((0, v1))
_, y2 = ax2.transData.transform((0, v2))
adjust_yaxis(ax2, (y1-y2)/2, v2)
adjust_yaxis(ax1, (y2-y1)/2, v1)
def adjust_yaxis(ax, ydif, v):
"""shift axis ax by ydiff, maintaining point v at the same location"""
inv = ax.transData.inverted()
_, dy = inv.transform((0, 0)) - inv.transform((0, ydif))
miny, maxy = ax.get_ylim()
miny, maxy = miny - v, maxy - v
if -miny > maxy or (-miny == maxy and dy > 0):
nminy = miny
nmaxy = miny*(maxy+dy)/(miny+dy)
else:
nmaxy = maxy
nminy = maxy*(miny+dy)/(maxy+dy)
ax.set_ylim(nminy+v, nmaxy+v)
def make_patch_spines_invisible(ax):
ax.set_frame_on(True)
ax.patch.set_visible(False)
for sp in ax.spines.values():
sp.set_visible(False)
print('loading {} IMS station...'.format(station))
g = xr.open_dataset(path / 'IMS_G_israeli_10mins.nc')[station]
g.load()
g = g.sel(time=g['time.season'] == season)
date = groupby_date_xr(g)
# g_anoms = g.groupby('time.month') - g.groupby('time.month').mean('time')
g_anoms = g.groupby(date) - g.groupby(date).mean('time')
g_anoms = g_anoms.reset_coords(drop=True)
G = g_anoms.groupby('time.hour').mean('time')
if ax is None:
fig, ax = plt.subplots(figsize=(16, 8))
G.plot(ax=ax, color='b', marker='o')
ax.set_title(
'Gustiness {} IMS station in {} season'.format(
station, season))
ax.axhline(0, color='b', linestyle='--')
ax.set_ylabel('Gustiness anomalies [dimensionless]', color='b')
ax.set_xlabel('Time of day [UTC]')
ax.set_xticks(np.arange(0, 24, step=1))
ax.yaxis.label.set_color('b')
ax.tick_params(axis='y', colors='b')
ax.grid()
if pw_station is not None:
pw = xr.open_dataset(
work_yuval /
'GNSS_PW_thresh_50_homogenized.nc')[pw_station]
pw.load().dropna('time')
pw = pw.sel(time=pw['time.season'] == season)
date = groupby_date_xr(pw)
pw = pw.groupby(date) - pw.groupby(date).mean('time')
pw = pw.reset_coords(drop=True)
pw = pw.groupby('time.hour').mean()
axpw = ax.twinx()
pw.plot.line(ax=axpw, color='k', marker='o')
axpw.axhline(0, color='k', linestyle='--')
axpw.legend(['{} PW anomalies'.format(
pw_station.upper())], loc='upper right')
axpw.set_ylabel('PW anomalies [mm]')
align_yaxis(ax, 0, axpw, 0)
if temp:
axt = ax.twinx()
axt.spines["right"].set_position(("axes", 1.05))
# Having been created by twinx, par2 has its frame off, so the line of its
# detached spine is invisible. First, activate the frame but make the patch
# and spines invisible.
make_patch_spines_invisible(axt)
# Second, show the right spine.
axt.spines["right"].set_visible(True)
p3, = T.plot.line(ax=axt, marker='s', color='m',
label="Temperature")
axt.yaxis.label.set_color(p3.get_color())
axt.tick_params(axis='y', colors=p3.get_color())
axt.set_ylabel('Temperature anomalies [$C\degree$]')
return G
def produce_relative_frequency_wind_direction(path=ims_path,
station='TEL-AVIV-COAST',
season='DJF', with_weights=False,
pw_station='tela', temp=False,
plot=True):
import xarray as xr
import matplotlib.pyplot as plt
import numpy as np
def make_patch_spines_invisible(ax):
ax.set_frame_on(True)
ax.patch.set_visible(False)
for sp in ax.spines.values():
sp.set_visible(False)
wd = xr.open_dataset(path / 'IMS_WD_israeli_10mins.nc')[station]
wd.load()
wd.name = 'WD'
wd = wd.sel(time=wd['time.season'] == season)
all_Q = wd.groupby('time.hour').count()
Q1 = wd.where((wd >= 0) & (wd < 90)).dropna('time')
Q2 = wd.where((wd >= 90) & (wd < 180)).dropna('time')
Q3 = wd.where((wd >= 180.1) & (wd < 270)).dropna('time')
Q4 = wd.where((wd >= 270) & (wd < 360)).dropna('time')
Q = xr.concat([Q1, Q2, Q3, Q4], 'Q')
Q['Q'] = [x + 1 for x in range(4)]
Q_freq = 100.0 * (Q.groupby('time.hour').count() / all_Q)
T = xr.open_dataset(path / 'IMS_TD_israeli_10mins.nc')[station]
T.load()
T = T.groupby('time.month') - T.groupby('time.month').mean('time')
T = T.reset_coords(drop=True)
T = T.sel(time=T['time.season'] == season)
T = T.groupby('time.hour').mean('time')
if with_weights:
ws = xr.open_dataset(path / 'IMS_WS_israeli_10mins.nc')[station]
ws.load()
ws = ws.sel(time=ws['time.season'] == season)
ws.name = 'WS'
wind = xr.merge([ws, wd])
wind = wind.dropna('time')
all_Q = wind['WD'].groupby('time.hour').count()
Q1 = wind['WS'].where(
(wind['WD'] >= 0) & (wind['WD'] < 90)).dropna('time')
Q2 = wind['WS'].where(
(wind['WD'] >= 90) & (wind['WD'] < 180)).dropna('time')
Q3 = wind['WS'].where(
(wind['WD'] >= 180) & (wind['WD'] < 270)).dropna('time')
Q4 = wind['WS'].where(
(wind['WD'] >= 270) & (wind['WD'] < 360)).dropna('time')
Q = xr.concat([Q1, Q2, Q3, Q4], 'Q')
Q['Q'] = [x + 1 for x in range(4)]
Q_ratio = (Q.groupby('time.hour').count() / all_Q)
Q_mean = Q.groupby('time.hour').mean() / Q.groupby('time.hour').max()
Q_freq = 100 * ((Q_mean * Q_ratio) / (Q_mean * Q_ratio).sum('Q'))
if plot:
fig, ax = plt.subplots(figsize=(16, 8))
for q in Q_freq['Q']:
Q_freq.sel(Q=q).plot(ax=ax)
ax.set_title(
'Relative wind direction frequency in {} IMS station in {} season'.format(
station, season))
ax.set_ylabel('Relative frequency [%]')
ax.set_xlabel('Time of day [UTC]')
ax.legend([r'0$\degree$-90$\degree$', r'90$\degree$-180$\degree$',
r'180$\degree$-270$\degree$', r'270$\degree$-360$\degree$'], loc='upper left')
ax.set_xticks(np.arange(0, 24, step=1))
ax.grid()
if pw_station is not None:
pw = xr.open_dataset(
work_yuval /
'GNSS_PW_thresh_50_homogenized.nc')[pw_station]
pw.load().dropna('time')
pw = pw.groupby('time.month') - \
pw.groupby('time.month').mean('time')
pw = pw.reset_coords(drop=True)
pw = pw.sel(time=pw['time.season'] == season)
pw = pw.groupby('time.hour').mean()
axpw = ax.twinx()
pw.plot.line(ax=axpw, color='k', marker='o')
axpw.axhline(0, color='k', linestyle='--')
axpw.legend(['{} PW anomalies'.format(
pw_station.upper())], loc='upper right')
axpw.set_ylabel('PW anomalies [mm]')
if temp:
axt = ax.twinx()
axt.spines["right"].set_position(("axes", 1.05))
# Having been created by twinx, par2 has its frame off, so the line of its
# detached spine is invisible. First, activate the frame but make the patch
# and spines invisible.
make_patch_spines_invisible(axt)
# Second, show the right spine.
axt.spines["right"].set_visible(True)
p3, = T.plot.line(ax=axt, marker='s',
color='m', label="Temperature")
axt.yaxis.label.set_color(p3.get_color())
axt.tick_params(axis='y', colors=p3.get_color())
axt.set_ylabel('Temperature anomalies [$C\degree$]')
return Q_freq
def plot_closest_line_from_point_to_israeli_coast(point, ax=None, epsg=None,
path=gis_path, color='k',
ls='-', lw=1.0):
import matplotlib.pyplot as plt
from shapely.geometry import LineString
from pyproj import Geod
"""returns the distance in kms"""
coast_gdf = get_israeli_coast_line(path=path, epsg=epsg)
coast_pts = coast_gdf.geometry.unary_union
point_in_coast = get_closest_point_from_a_line_to_a_point(point, coast_pts)
AB = LineString([point_in_coast, point])
if ax is None:
fig, ax = plt.subplots()
ax.plot(*AB.xy, color='k', linestyle=ls, linewidth=lw)
geod = Geod(ellps="WGS84")
distance = geod.geometry_length(AB) / 1000.0
return distance
def get_closest_point_from_a_line_to_a_point(point, line):
from shapely.ops import nearest_points
p1, p2 = nearest_points(point, line)
return p2
def get_israeli_coast_line(path=gis_path, minx=34.0, miny=30.0, maxx=36.0,
maxy=34.0, epsg=None):
"""use epsg=2039 to return in meters"""
from shapely.geometry import box
import geopandas as gpd
# create bounding box using shapely:
bbox = box(minx, miny, maxx, maxy)
# read world coast lines:
coast = gpd.read_file(gis_path / 'ne_10m_coastline.shp')
# clip:
gdf = gpd.clip(coast, bbox)
if epsg is not None:
gdf = gdf.to_crs('epsg:{}'.format(epsg))
return gdf
def clip_raster(fp=awd_path/'Israel_Area.tif',
out_tif=awd_path/'israel_dem.tif',
minx=34.0, miny=29.0, maxx=36.5, maxy=34.0):
def getFeatures(gdf):
"""Function to parse features from GeoDataFrame in such a manner that
rasterio wants them"""
import json
return [json.loads(gdf.to_json())['features'][0]['geometry']]
import rasterio
from rasterio.plot import show
from rasterio.plot import show_hist
from rasterio.mask import mask
from shapely.geometry import box
import geopandas as gpd
from fiona.crs import from_epsg
import pycrs
print('reading {}'.format(fp))
data = rasterio.open(fp)
# create bounding box using shapely:
bbox = box(minx, miny, maxx, maxy)
# insert the bbox into a geodataframe:
geo = gpd.GeoDataFrame({'geometry': bbox}, index=[0], crs=from_epsg(4326))
# re-project with the same projection as the data:
geo = geo.to_crs(crs=data.crs.data)
# get the geometry coords:
coords = getFeatures(geo)
# clipping is done with mask:
out_img, out_transform = mask(dataset=data, shapes=coords, crop=True)
# copy meta data:
out_meta = data.meta.copy()
# parse the epsg code:
epsg_code = int(data.crs.data['init'][5:])
# update the meta data:
out_meta.update({"driver": "GTiff",
"height": out_img.shape[1],
"width": out_img.shape[2],
"transform": out_transform,
"crs": pycrs.parse.from_epsg_code(epsg_code).to_proj4()})
# save to disk:
print('saving {} to disk.'.format(out_tif))
with rasterio.open(out_tif, "w", **out_meta) as dest:
dest.write(out_img)
print('Done!')
return
def create_israel_area_dem(path):
"""merge the raw DSM tif files from AW3D30 model of Israel area togather"""
from aux_gps import path_glob
import rasterio
from rasterio.merge import merge
src_files_to_mosaic = []
files = path_glob(path, '*DSM*.tif')
for fp in files:
src = rasterio.open(fp)
src_files_to_mosaic.append(src)
mosaic, out_trans = merge(src_files_to_mosaic)
out_meta = src.meta.copy()
out_meta.update({"driver": "GTiff",
"height": mosaic.shape[1],
"width": mosaic.shape[2],
"transform": out_trans,
"crs": src.crs
}
)
with rasterio.open(path/'Israel_Area.tif', "w", **out_meta) as dest:
dest.write(mosaic)
return
def parse_cv_results(grid_search_cv):
from aux_gps import process_gridsearch_results
"""parse cv_results from GridsearchCV object"""
# only supports neg-abs-mean-error with leaveoneout
from sklearn.model_selection import LeaveOneOut
if (isinstance(grid_search_cv.cv, LeaveOneOut)
and grid_search_cv.scoring == 'neg_mean_absolute_error'):
cds = process_gridsearch_results(grid_search_cv)
cds = - cds
return cds
def IMS_interpolating_to_GNSS_stations_israel(dt='2013-10-19T22:00:00',
stations=None,
lapse_rate='auto',
method='okrig',
variogram='spherical',
n_neighbors=3,
start_year='1996',
cut_days_ago=3,
plot=False,
verbose=False,
savepath=ims_path,
network='soi-apn',
axis_path=axis_path,
ds_td=None,
concat_all_TD=True,
soi_path=cwd):
"""interpolate the IMS 10 mins field(e.g., TD) to the location
of the GNSS sites in ISRAEL(use dt=None for this). other dt is treated
as datetime str and will give the "snapshot" for the field for just this
datetime"""
from pykrige.rk import Krige
import pandas as pd
from aux_gps import path_glob
import xarray as xr
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
import geopandas as gpd
from sklearn.neighbors import KNeighborsRegressor
from axis_process import read_axis_stations
# import time
def pick_model(method, variogram, n_neighbors):
if method == 'okrig':
if variogram is not None:
model = Krige(method='ordinary', variogram_model=variogram,
verbose=False)
else:
model = Krige(method='ordinary', variogram_model='linear',
verbose=False)
elif method == 'knn':
if n_neighbors is None:
model = KNeighborsRegressor(n_neighbors=5, weights='distance')
else:
model = KNeighborsRegressor(
n_neighbors=n_neighbors, weights='distance')
else:
raise Exception('{} is not supported yet...'.format(method))
return model
def prepare_Xy(ts_lr_neutral, T_lats, T_lons):
import numpy as np
df = ts_lr_neutral.to_frame()
df['lat'] = T_lats
df['lon'] = T_lons
# df = df.dropna(axis=0)
c = np.linspace(
df['lat'].min(),
df['lat'].max(),
df['lat'].shape[0])
r = np.linspace(
df['lon'].min(),
df['lon'].max(),
df['lon'].shape[0])
rr, cc = np.meshgrid(r, c)
vals = ~np.isnan(ts_lr_neutral)
X = np.column_stack([rr[vals, vals], cc[vals, vals]])
# rr_cc_as_cols = np.column_stack([rr.flatten(), cc.flatten()])
# y = da_scaled/home/shlomi/geo_ariel_home/Python_Projects/PW_from_GPS/*.*.values[vals]
y = ts_lr_neutral[vals]
return X, y
def neutrilize_t(ts_vs_alt, lapse_rate):
ts_lr_neutral = (ts_vs_alt +
lapse_rate *
ts_vs_alt.index /
1000.0)
return ts_lr_neutral
def choose_dt_and_lapse_rate(tdf, dt, T_alts, lapse_rate):
ts = tdf.loc[dt, :]
# dt_col = dt.strftime('%Y-%m-%d %H:%M')
# ts.name = dt_col
# Tloc_df = Tloc_df.join(ts, how='right')
# Tloc_df = Tloc_df.dropna(axis=0)
ts_vs_alt = pd.Series(ts.values, index=T_alts)
ts_vs_alt_for_fit = ts_vs_alt.dropna()
# try:
[a, b] = np.polyfit(ts_vs_alt_for_fit.index.values,
ts_vs_alt_for_fit.values, 1)
# except TypeError as e:
# print('{}, dt: {}'.format(e, dt))
# print(ts_vs_alt)
# return
if lapse_rate == 'auto':
lapse_rate = np.abs(a) * 1000
if lapse_rate < 5.0:
lapse_rate = 5.0
elif lapse_rate > 10.0:
lapse_rate = 10.0
return ts_vs_alt, lapse_rate
# import time
dt = pd.to_datetime(dt)
# read Israeli GNSS sites coords:
if network == 'soi-apn':
df = pd.read_csv(
soi_path /
'israeli_gnss_coords.txt',
delim_whitespace=True,
header=0)
elif network == 'axis':
df = read_axis_stations(path=axis_path)
if verbose:
print('{} network selected.'.format(network))
# use station=None to pick all stations, otherwise pick one...
if stations is not None:
if isinstance(stations, str):
stations = [stations]
df = df.loc[stations, :]
print('selected only {} stations'.format(stations))
else:
print('selected all {} stations.'.format(network))
# prepare lats and lons of gnss sites:
gps_lats = np.linspace(df.lat.min(), df.lat.max(), df.lat.values.shape[0])
gps_lons = np.linspace(df.lon.min(), df.lon.max(), df.lon.values.shape[0])
gps_lons_lats_as_cols = np.column_stack([gps_lons, gps_lats])
# load IMS temp data:
if ds_td is None:
glob_str = 'IMS_TD_israeli_10mins*.nc'
file = path_glob(ims_path, glob_str=glob_str)[0]
ds = xr.open_dataset(file)
else:
ds = ds_td
time_dim = list(set(ds.dims))[0]
# slice to a starting year(1996?):
ds = ds.sel({time_dim: slice(start_year, None)})
years = sorted(list(set(ds[time_dim].dt.year.values)))
# get coords and alts of IMS stations:
index = [x for x in ds]
T_geo = pd.DataFrame([ds[x].attrs['station_alt'] for x in ds], index=index)
T_geo.columns = ['station_alt']
T_geo['station_lat'] = [ds[x].attrs['station_lat'] for x in ds]
T_geo['station_lon'] = [ds[x].attrs['station_lon'] for x in ds]
T_geo['station_lat'] = pd.to_numeric(T_geo['station_lat'], errors='coerce')
T_geo['station_alt'] = pd.to_numeric(T_geo['station_alt'], errors='coerce')
T_geo['station_lon'] = pd.to_numeric(T_geo['station_lon'], errors='coerce')
T_geo = T_geo.dropna()
T_alts = T_geo['station_alt'].values
T_lons = T_geo['station_lon'].values
T_lats = T_geo['station_lat'].values
print('loading IMS_TD of israeli stations 10mins freq..')
# transform to dataframe and add coords data to df:
tdf = ds.to_dataframe()[[x for x in T_geo.index]]
if cut_days_ago is not None:
# use cut_days_ago to drop last x days of data:
# this is vital bc towards the newest data, TD becomes scarce bc not
# all of the stations data exists...
n = cut_days_ago * 144
tdf.drop(tdf.tail(n).index, inplace=True)
print('last date to be handled is {}'.format(tdf.index[-1]))
# use this to solve for a specific datetime:
if dt is not None:
dt_col = dt.strftime('%Y-%m-%d %H:%M')
# t0 = time.time()
# prepare the ims coords and temp df(Tloc_df) and the lapse rate:
ts_vs_alt, lapse_rate = choose_dt_and_lapse_rate(
tdf, dt, T_alts, lapse_rate)
if plot:
fig, ax_lapse = plt.subplots(figsize=(10, 6))
sns.regplot(x=ts_vs_alt.index, y=ts_vs_alt.values, color='r',
scatter_kws={'color': 'b'}, ax=ax_lapse)
suptitle = dt.strftime('%Y-%m-%d %H:%M')
ax_lapse.set_xlabel('Altitude [m]')
ax_lapse.set_ylabel('Temperature [degC]')
ax_lapse.text(0.5, 0.95, 'Lapse_rate: {:.2f} degC/km'.format(lapse_rate),
horizontalalignment='center', verticalalignment='center',
transform=ax_lapse.transAxes, fontsize=12, color='k',
fontweight='bold')
ax_lapse.grid()
ax_lapse.set_title(suptitle, fontsize=14, fontweight='bold')
# neutrilize the lapse rate effect:
ts_lr_neutral = neutrilize_t(ts_vs_alt, lapse_rate)
# prepare the regressors(IMS stations coords) and the
# target(IMS temperature at the coords):
X, y = prepare_Xy(ts_lr_neutral, T_lats, T_lons)
# pick the model and params:
model = pick_model(method, variogram, n_neighbors)
# fit the model:
model.fit(X, y)
# predict at the GNSS stations coords:
interpolated = model.predict(
gps_lons_lats_as_cols).reshape((gps_lats.shape))
# add prediction to df:
df[dt_col] = interpolated
# fix for lapse rate:
df[dt_col] -= lapse_rate * df['alt'] / 1000.0
# concat gnss stations and Tloc DataFrames:
Tloc_df = pd.DataFrame(T_lats, index=tdf.columns)
Tloc_df.columns = ['lat']
Tloc_df['lon'] = T_lons
Tloc_df['alt'] = T_alts
all_df = pd.concat([df, Tloc_df], axis=0)
# fname = gis_path / 'ne_10m_admin_0_sovereignty.shp'
# fname = gis_path / 'gadm36_ISR_0.shp'
# ax = plt.axes(projection=ccrs.PlateCarree())
da = xr.DataArray(interpolated, dims='station')
da['station'] = df.index
# da = da.expand_dims('time')
da['time'] = pd.to_datetime(dt)
# da = da.sortby('time')
ds = da.to_dataset(dim='station')
for da in ds:
ds[da].attrs['units'] = 'degC'
if plot:
fig, ax = plt.subplots(figsize=(6, 10))
# shdf = salem.read_shapefile(salem.get_demo_file('world_borders.shp'))
# shdf = salem.read_shapefile(gis_path / 'Israel_and_Yosh.shp')
isr = gpd.read_file(gis_path / 'Israel_and_Yosh.shp')
# shdf = shdf.loc[shdf['CNTRY_NAME'] == 'Israel'] # remove other countries
isr.crs = {'init': 'epsg:4326'}
time_snap = gpd.GeoDataFrame(all_df, geometry=gpd.points_from_xy(all_df.lon,
all_df.lat),
crs=isr.crs)
time_snap = gpd.sjoin(time_snap, isr, op='within')
isr.plot(ax=ax)
cmap = plt.get_cmap('rainbow', 10)
time_snap.plot(ax=ax, column=dt_col, cmap=cmap,
edgecolor='black', legend=True)
for x, y, label in zip(df.lon, df.lat,
df.index):
ax.annotate(label, xy=(x, y), xytext=(3, 3),
textcoords="offset points")
suptitle = dt.strftime('%Y-%m-%d %H:%M')
fig.suptitle(suptitle, fontsize=14, fontweight='bold')
else:
# do the above (except plotting) for the entire data, saving each year:
for year in years:
dts = tdf.index[tdf.index.year == year]
# read Israeli GNSS sites coords again:
if network == 'soi-apn':
df = pd.read_csv(
soi_path /
'israeli_gnss_coords.txt',
delim_whitespace=True,
header=0)
elif network == 'axis':
df = read_axis_stations(path=axis_path)
cnt = 1
dt_col_list = []
inter_list = []
# t0 = time.time()
# t1 = time.time()
# t2 = time.time()
# t3 = time.time()
# t4 = time.time()
# t5 = time.time()
# t6 = time.time()
# t7 = time.time()
# t8 = time.time()
for dt in dts:
dt_col = dt.strftime('%Y-%m-%d %H:%M')
if np.mod(cnt, 144) == 0:
# t1 = time.time()
print('working on {}'.format(dt_col))
# print('time1:{:.2f} seconds'.format(t1-t0))
# t0 = time.time()
# prepare the ims coords and temp df(Tloc_df) and
# the lapse rate:
ts_vs_alt, lapse_rate = choose_dt_and_lapse_rate(
tdf, dt, T_alts, lapse_rate)
# if np.mod(cnt, 144) == 0:
# t2 = time.time()
# print('time2: {:.4f}'.format((t2-t1)*144))
# neutrilize the lapse rate effect:
ts_lr_neutral = neutrilize_t(ts_vs_alt, lapse_rate)
# prepare the regressors(IMS stations coords) and the
# target(IMS temperature at the coords):
# if np.mod(cnt, 144) == 0:
# t3 = time.time()
# print('time3: {:.4f}'.format((t3-t2)*144))
X, y = prepare_Xy(ts_lr_neutral, T_lats, T_lons)
# if np.mod(cnt, 144) == 0:
# t4 = time.time()
# print('time4: {:.4f}'.format((t4-t3)*144))
# pick model and params:
model = pick_model(method, variogram, n_neighbors)
# if np.mod(cnt, 144) == 0:
# t5 = time.time()
# print('time5: {:.4f}'.format((t5-t4)*144))
# fit the model:
model.fit(X, y)
# if np.mod(cnt, 144) == 0:
# t6 = time.time()
# print('time6: {:.4f}'.format((t6-t5)*144))
# predict at the GNSS stations coords:
interpolated = model.predict(
gps_lons_lats_as_cols).reshape((gps_lats.shape))
# if np.mod(cnt, 144) == 0:
# t7 = time.time()
# print('time7: {:.4f}'.format((t7-t6)*144))
# fix for lapse rate:
interpolated -= lapse_rate * df['alt'].values / 1000.0
# if np.mod(cnt, 144) == 0:
# t8 = time.time()
# print('time8: {:.4f}'.format((t8-t7)*144))
# add to list:
dt_col_list.append(dt_col)
inter_list.append(interpolated)
cnt += 1
# convert to dataset: