-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathPW_stations.py
executable file
·4964 lines (4727 loc) · 214 KB
/
PW_stations.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 Mar 25 15:50:20 2019
work flow for ZWD and PW retreival after python copy_gipsyx_post_from_geo.py:
1)save_PPP_field_unselected_data_and_errors(field='ZWD')
2)select_PPP_field_thresh_and_combine_save_all(field='ZWD')
3)use mean_ZWD_over_sound_time_and_fit_tstm to obtain the mda (model dataarray)
3*) can't use produce_kappa_ml_with_cats for hour on 5 mins data, dahhh!
can do that with dayofyear, month, season (need to implement it first)
4)save_GNSS_PW_israeli_stations using mda (e.g., season) from 3
5) do homogenization using Homogenization_R.py and run homogenize_pw_dataset
6) for hydro analysis and more run produce_all_GNSS_PW_anomalies
@author: shlomi
"""
import pandas as pd
import numpy as np
from PW_paths import work_yuval
from PW_paths import work_path
from PW_paths import geo_path
from pathlib import Path
from sklearn.linear_model import LinearRegression
from scipy import stats
hydro_path = work_yuval / 'hydro'
garner_path = work_yuval / 'garner'
ims_path = work_yuval / 'IMS_T'
gis_path = work_yuval / 'gis'
sound_path = work_yuval / 'sounding'
climate_path = work_yuval / 'climate'
dem_path = work_yuval / 'AW3D30'
phys_soundings = sound_path / 'bet_dagan_phys_sounding_2007-2019.nc'
tela_zwd = work_yuval / 'gipsyx_results/tela_newocean/TELA_PPP_1996-2019.nc'
jslm_zwd = work_yuval / 'gipsyx_results/jslm_newocean/JSLM_PPP_2001-2019.nc'
alon_zwd = work_yuval / 'gipsyx_results/alon_newocean/ALON_PPP_2005-2019.nc'
tela_zwd_aligned = work_yuval / 'tela_zwd_aligned_with_physical_bet_dagan.nc'
alon_zwd_aligned = work_yuval / 'ALON_zwd_aligned_with_physical_bet_dagan.nc'
jslm_zwd_aligned = work_yuval / 'JSLM_zwd_aligned_with_physical_bet_dagan.nc'
tela_ims = ims_path / '10mins/TEL-AVIV-COAST_178_TD_10mins_filled.nc'
alon_ims = ims_path / '10mins/ASHQELON-PORT_208_TD_10mins_filled.nc'
jslm_ims = ims_path / '10mins/JERUSALEM-CENTRE_23_TD_10mins_filled.nc'
station_on_geo = geo_path / 'Work_Files/PW_yuval/GNSS_stations'
era5_path = work_yuval / 'ERA5'
PW_stations_path = work_yuval / '1minute'
# stations = pd.read_csv('All_gps_stations.txt', header=0, delim_whitespace=True,
# index_col='name')
logs_path = geo_path / 'Python_Projects/PW_from_GPS/log_files'
GNSS_path = work_yuval / 'GNSS_stations'
cwd = Path().cwd()
gnss_sound_stations_dict = {'acor': '08001', 'mall': '08302'}
# TODO: kappa_ml_with_cats yields smaller k using cats not None, check it...
# TODO: then assemble PW for all the stations.
class LinearRegression_with_stats(LinearRegression):
"""
LinearRegression class after sklearn's, but calculate t-statistics
and p-values for model coefficients (betas).
Additional attributes available after .fit()
are `t` and `p` which are of the shape (y.shape[1], X.shape[1])
which is (n_features, n_coefs)
This class sets the intercept to 0 by default, since usually we include it
in X.
"""
def __init__(self, *args, **kwargs):
# if not "fit_intercept" in kwargs:
# kwargs['fit_intercept'] = False
super().__init__(*args,**kwargs)
def fit(self, X, y=None, verbose=True, **fit_params):
from scipy import linalg
""" A wrapper around the fitting function.
Improved: adds the X_ and y_ and results_ attrs to class.
Parameters
----------
X : xarray DataArray, Dataset other other array-like
The training input samples.
y : xarray DataArray, Dataset other other array-like
The target values.
Returns
-------
Returns self.
"""
self = super().fit(X, y, **fit_params)
n, k = X.shape
yHat = np.matrix(self.predict(X)).T
# Change X and Y into numpy matricies. x also has a column of ones added to it.
x = np.hstack((np.ones((n,1)),np.matrix(X)))
y = np.matrix(y).T
# Degrees of freedom.
df = float(n-k-1)
# Sample variance.
sse = np.sum(np.square(yHat - y),axis=0)
self.sampleVariance = sse/df
# Sample variance for x.
self.sampleVarianceX = x.T*x
# Covariance Matrix = [(s^2)(X'X)^-1]^0.5. (sqrtm = matrix square root. ugly)
self.covarianceMatrix = linalg.sqrtm(self.sampleVariance[0,0]*self.sampleVarianceX.I)
# Standard erros for the difference coefficients: the diagonal elements of the covariance matrix.
self.se = self.covarianceMatrix.diagonal()[1:]
# T statistic for each beta.
self.betasTStat = np.zeros(len(self.se))
for i in range(len(self.se)):
self.betasTStat[i] = self.coef_[i]/self.se[i]
# P-value for each beta. This is a two sided t-test, since the betas can be
# positive or negative.
self.betasPValue = 1 - stats.t.cdf(abs(self.betasTStat),df)
return self
def compare_different_cats_bet_dagan_tela():
from aux_gps import error_mean_rmse
ds, mda = mean_ZWD_over_sound_time_and_fit_tstm(
plot=False, times=['2013-09', '2020'], cats=None)
ds_hour, mda = mean_ZWD_over_sound_time_and_fit_tstm(
plot=False, times=['2013-09', '2020'], cats=['hour'])
ds_season, mda = mean_ZWD_over_sound_time_and_fit_tstm(
plot=False, times=['2013-09', '2020'], cats=['season'])
ds_hour_season, mda = mean_ZWD_over_sound_time_and_fit_tstm(
plot=False, times=['2013-09', '2020'], cats=['hour', 'season'])
ds = ds.dropna('sound_time')
ds_hour = ds_hour.dropna('sound_time')
ds_season = ds_season.dropna('sound_time')
ds_hour_season = ds_hour_season.dropna('sound_time')
mean_none, rmse_none = error_mean_rmse(ds['tpw_bet_dagan'], ds['tela_pw'])
mean_hour, rmse_hour = error_mean_rmse(
ds_hour['tpw_bet_dagan'], ds_hour['tela_pw'])
mean_season, rmse_season = error_mean_rmse(
ds_season['tpw_bet_dagan'], ds_season['tela_pw'])
mean_hour_season, rmse_hour_season = error_mean_rmse(
ds_hour_season['tpw_bet_dagan'], ds_hour_season['tela_pw'])
hour_mean_per = 100 * (abs(mean_none) - abs(mean_hour)) / abs(mean_none)
hour_rmse_per = 100 * (abs(rmse_none) - abs(rmse_hour)) / abs(rmse_none)
season_mean_per = 100 * (abs(mean_none) - abs(mean_season)) / abs(mean_none)
season_rmse_per = 100 * (abs(rmse_none) - abs(rmse_season)) / abs(rmse_none)
hour_season_mean_per = 100 * (abs(mean_none) - abs(mean_hour_season)) / abs(mean_none)
hour_season_rmse_per = 100 * (abs(rmse_none) - abs(rmse_hour_season)) / abs(rmse_none)
print(
'whole data mean: {:.2f} and rmse: {:.2f}'.format(
mean_none,
rmse_none))
print(
'hour data mean: {:.2f} and rmse: {:.2f}, {:.1f} % and {:.1f} % better than whole data.'.format(
mean_hour, rmse_hour, hour_mean_per, hour_rmse_per))
print(
'season data mean: {:.2f} and rmse: {:.2f}, {:.1f} % and {:.1f} % better than whole data.'.format(
mean_season, rmse_season, season_mean_per, season_rmse_per))
print(
'hour and season data mean: {:.2f} and rmse: {:.2f}, {:.1f} % and {:.1f} % better than whole data.'.format(
mean_hour_season, rmse_hour_season, hour_season_mean_per, hour_season_rmse_per))
return
def PW_trend_analysis(path=work_yuval, anom=False, station='tela'):
import xarray as xr
pw = xr.open_dataset(path / 'GNSS_daily_PW.nc')[station]
if anom:
pw = pw.groupby('time.month') - pw.groupby('time.month').mean('time')
pw_lr = ML_fit_model_to_tmseries(pw, modelname='LR', plot=False, verbose=True)
pw_tsen = ML_fit_model_to_tmseries(pw, modelname='TSEN', plot=False, verbose=True)
return pw_tsen
def produce_gnss_pw_from_uerra(era5_path=era5_path,
glob_str='UERRA_TCWV_*.nc',
pw_path=work_yuval, savepath=None):
from aux_gps import path_glob
import xarray as xr
from aux_gps import save_ncfile
udf = add_UERRA_xy_to_israeli_gps_coords(pw_path, era5_path)
files = path_glob(era5_path, glob_str)
uerra_list = [xr.open_dataset(file) for file in files]
ds_attrs = uerra_list[0].attrs
ds_list = []
for i, uerra in enumerate(uerra_list):
print('proccessing {}'.format(files[i].as_posix().split('/')[-1]))
st_list = []
for station in udf.index:
y = udf.loc[station, 'y']
x = udf.loc[station, 'x']
uerra_st = uerra['tciwv'].isel(y=y, x=x).reset_coords(drop=True)
uerra_st.name = station
uerra_st.attrs = uerra['tciwv'].attrs
uerra_st.attrs['lon'] = udf.loc[station, 'lon']
uerra_st.attrs['lat'] = udf.loc[station, 'lat']
st_list.append(uerra_st)
ds_st = xr.merge(st_list)
ds_list.append(ds_st)
ds = xr.concat(ds_list, 'time')
ds = ds.sortby('time')
ds.attrs = ds_attrs
ds_monthly = ds.resample(time='MS', keep_attrs=True).mean(keep_attrs=True)
if savepath is not None:
filename = 'GNSS_uerra_4xdaily_PW.nc'
save_ncfile(ds, savepath, filename)
filename = 'GNSS_uerra_monthly_PW.nc'
save_ncfile(ds_monthly, savepath, filename)
return ds
def produce_PWV_flux_from_ERA5_UVQ(
path=era5_path,
savepath=None,
pw_path=work_yuval, return_magnitude=False):
import xarray as xr
from aux_gps import calculate_pressure_integral
from aux_gps import calculate_g
from aux_gps import save_ncfile
import numpy as np
ds = xr.load_dataset(era5_path / 'ERA5_UVQ_mm_israel_1979-2020.nc')
ds = ds.sel(expver=1).reset_coords(drop=True)
g = calculate_g(ds['latitude']).mean().item()
qu = calculate_pressure_integral(ds['q'] * ds['u'])
qv = calculate_pressure_integral(ds['q'] * ds['v'])
qu.name = 'qu'
qv.name = 'qv'
# convert to mm/sec units
qu = 100 * qu / (g * 1000)
qv = 100 * qv / (g * 1000)
# add attrs:
qu.attrs['units'] = 'mm/sec'
qv.attrs['units'] = 'mm/sec'
qu_gnss = produce_era5_field_at_gnss_coords(
qu, savepath=None, pw_path=pw_path)
qv_gnss = produce_era5_field_at_gnss_coords(
qv, savepath=None, pw_path=pw_path)
if return_magnitude:
qflux = np.sqrt(qu_gnss**2 + qv_gnss**2)
qflux.attrs['units'] = 'mm/sec'
return qflux
else:
return qu_gnss, qv_gnss
def produce_era5_field_at_gnss_coords(era5_da, savepath=None,
pw_path=work_yuval):
import xarray as xr
from aux_gps import save_ncfile
print('reading ERA5 {} field.'.format(era5_da.name))
gps = produce_geo_gnss_solved_stations(plot=False)
era5_pw_list = []
for station in gps.index:
slat = gps.loc[station, 'lat']
slon = gps.loc[station, 'lon']
da = era5_da.sel(latitude=slat, longitude=slon, method='nearest')
da.name = station
da.attrs['era5_lat'] = da.latitude.values.item()
da.attrs['era5_lon'] = da.longitude.values.item()
da = da.reset_coords(drop=True)
era5_pw_list.append(da)
ds = xr.merge(era5_pw_list)
if savepath is not None:
name = era5_da.name
yrmin = era5_da['time'].dt.year.min().item()
yrmax = era5_da['time'].dt.year.max().item()
filename = 'GNSS_ERA5_{}_{}-{}.nc'.format(name, yrmin, yrmax)
save_ncfile(ds, savepath, filename)
return ds
def produce_gnss_pw_from_era5(era5_path=era5_path,
glob_str='era5_TCWV_israel*.nc',
pw_path=work_yuval, savepath=None):
from aux_gps import path_glob
import xarray as xr
from aux_gps import save_ncfile
filepath = path_glob(era5_path, glob_str)[0]
print('opening ERA5 file {}'.format(filepath.as_posix().split('/')[-1]))
era5_pw = xr.open_dataarray(filepath)
era5_pw = era5_pw.sortby('time')
gps = produce_geo_gnss_solved_stations(plot=False)
era5_pw_list = []
for station in gps.index:
slat = gps.loc[station, 'lat']
slon = gps.loc[station, 'lon']
da = era5_pw.sel(lat=slat, lon=slon, method='nearest')
da.name = station
da.attrs['era5_lat'] = da.lat.values.item()
da.attrs['era5_lon'] = da.lon.values.item()
da = da.reset_coords(drop=True)
era5_pw_list.append(da)
ds_hourly = xr.merge(era5_pw_list)
ds_monthly = ds_hourly.resample(time='MS', keep_attrs=True).mean(keep_attrs=True)
if savepath is not None:
filename = 'GNSS_era5_hourly_PW.nc'
save_ncfile(ds_hourly, savepath, filename)
filename = 'GNSS_era5_monthly_PW.nc'
save_ncfile(ds_monthly, savepath, filename)
return ds_hourly
def plug_in_approx_loc_gnss_stations(log_path=logs_path, file_path=cwd):
from aux_gps import path_glob
import pandas as pd
def plug_loc_to_log_file(logfile, loc):
def replace_field(content_list, string, replacment):
pos = [(i, x) for i, x in enumerate(content_list)
if string in x][0][0]
con = content_list[pos].split(':')
con[-1] = ' {}'.format(replacment)
con = ':'.join(con)
content_list[pos] = con
return content_list
with open(logfile) as f:
content = f.read().splitlines()
repl = [
'X coordinate (m)',
'Y coordinate (m)',
'Z coordinate (m)',
'Latitude (deg)',
'Longitude (deg)',
'Elevation (m)']
location = [loc['X'], loc['Y'], loc['Z'], '+' +
str(loc['lat']), '+' + str(loc['lon']), loc['alt']]
for rep, loca in list(zip(repl, location)):
try:
content = replace_field(content, rep, loca)
except IndexError:
print('did not found {} field...'.format(rep))
pass
with open(logfile, 'w') as f:
for item in content:
f.write('{}\n'.format(item))
print('writing {}'.format(logfile))
return
# load gnss accurate loc:
acc_loc_df = pd.read_csv(file_path / 'israeli_gnss_coords.txt',
delim_whitespace=True)
log_files = path_glob(log_path, '*updated_by_shlomi*.log')
for logfile in log_files:
st_log = logfile.as_posix().split('/')[-1].split('_')[0]
try:
loc = acc_loc_df.loc[st_log, :]
except KeyError:
print('station {} not found in accurate location df, skipping'.format(st_log))
continue
plug_loc_to_log_file(logfile, loc)
print('Done!')
return
def build_df_lat_lon_alt_gnss_stations(gnss_path=GNSS_path, savepath=None):
from aux_gps import path_glob
import pandas as pd
import pyproj
from pathlib import Path
stations_in_gnss = [x.as_posix().split('/')[-1]
for x in path_glob(GNSS_path, '*')]
dss = [
load_gipsyx_results(
x,
sample_rate='MS',
plot_fields=None) for x in stations_in_gnss]
# stations_not_found = [x for x in dss if isinstance(x, str)]
# [stations_in_gnss.remove(x) for x in stations_in_gnss if x is None]
dss = [x for x in dss if not isinstance(x, str)]
dss = [x for x in dss if x is not None]
lats = [x.dropna('time').lat[0].values.item() for x in dss]
lons = [x.dropna('time').lon[0].values.item() for x in dss]
alts = [x.dropna('time').alt[0].values.item() for x in dss]
df = pd.DataFrame(lats)
df.index = [x.attrs['station'].lower() for x in dss]
df['lon'] = lons
df['alt'] = alts
df.columns = ['lat', 'lon', 'alt']
ecef = pyproj.Proj(proj='geocent', ellps='WGS84', datum='WGS84')
lla = pyproj.Proj(proj='latlong', ellps='WGS84', datum='WGS84')
X, Y, Z = pyproj.transform(lla, ecef, df['lon'].values, df['lat'].values,
df['alt'].values, radians=False)
df['X'] = X
df['Y'] = Y
df['Z'] = Z
# read station names from log files:
stations_approx = pd.read_fwf(Path().cwd()/'stations_approx_loc.txt',
delim_whitespace=False, skiprows=1, header=None)
stations_approx.columns=['index','X','Y','Z','name', 'extra']
stations_approx['name'] = stations_approx['name'].fillna('') +' ' + stations_approx['extra'].fillna('')
stations_approx.drop('extra', axis=1, inplace=True)
stations_approx = stations_approx.set_index('index')
df['name'] = stations_approx['name']
df.sort_index(inplace=True)
# add new g0 soi-apn:
g0 = pd.read_csv(cwd/'SOI-APN_stations_2020-02-12.csv')
g0 = g0[['name', 'lat', 'lon', 'alt', 'X', 'Y', 'Z']]
g0 = g0.set_index('name')
df = pd.concat([df, g0], axis=0)
df = df[~df.index.duplicated(keep='first')]
if savepath is not None:
filename = 'israeli_gnss_coords.txt'
df.to_csv(savepath/filename, sep=' ')
return df
def produce_homogeniety_results_xr(ds, alpha=0.05, test='snht', sim=20000):
import pyhomogeneity as hg
import xarray as xr
from aux_gps import homogeneity_test_xr
hg_tests_dict = {
'snht': hg.snht_test,
'pett': hg.pettitt_test,
'b_like': hg.buishand_likelihood_ratio_test,
'b_u': hg.buishand_u_test,
'b_q': hg.buishand_q_test,
'b_range': hg.buishand_range_test}
if test == 'all':
tests = [x for x in hg_tests_dict.keys()]
ds_list = []
for t in tests:
print('running {} test...'.format(t))
rds = ds.map(homogeneity_test_xr, hg_test_func=hg_tests_dict[t],
alpha=alpha, sim=sim, verbose=False)
rds = rds.to_array('station').to_dataset('results')
ds_list.append(rds)
rds = xr.concat(ds_list, 'test')
rds['test'] = tests
rds.attrs['alpha'] = alpha
rds.attrs['sim'] = sim
else:
rds = ds.map(homogeneity_test_xr, hg_test_func=hg_tests_dict[test],
alpha=alpha, sim=sim, verbose=False)
rds = rds.to_array('station').to_dataset('results')
rds.attrs['alpha'] = alpha
rds.attrs['sim'] = sim
# df=rds.to_array('st').to_dataset('results').to_dataframe()
print('Done!')
return rds
def run_error_analysis(station='tela', task='edit30hr'):
station_on_geo = geo_path / 'Work_Files/PW_yuval/GNSS_stations'
if task == 'edit30hr':
path = station_on_geo / station / 'rinex/30hr'
err, df = gipsyx_runs_error_analysis(path, glob_str='*.dr.gz')
elif task == 'run':
path = station_on_geo / station / 'rinex/30hr/results'
err, df = gipsyx_runs_error_analysis(path, glob_str='*.tdp')
return err, df
def gipsyx_runs_error_analysis(path, glob_str='*.tdp'):
from collections import Counter
from aux_gps import get_timedate_and_station_code_from_rinex
from aux_gps import path_glob
import pandas as pd
import logging
def find_errors(content_list, name):
keys = [x for x in content_list if 'KeyError' in x]
vals = [x for x in content_list if 'ValueError' in x]
excpt = [x for x in content_list if 'Exception' in x]
err = [x for x in content_list if 'Error' in x]
trouble = [x for x in content_list if 'Trouble' in x]
problem = [x for x in content_list if 'Problem' in x]
fatal = [x for x in content_list if 'FATAL' in x]
timed = [x for x in content_list if 'Timed' in x]
errors = keys + vals + excpt + err + trouble + problem + fatal + timed
if not errors:
dt, _ = get_timedate_and_station_code_from_rinex(name)
logger.warning('found new error on {} ({})'.format(name, dt.strftime('%Y-%m-%d')))
return errors
logger = logging.getLogger('gipsyx_post_proccesser')
rfns = []
files = path_glob(path, glob_str, True)
for file in files:
# first get all the rinex filenames that gipsyx ran successfuly:
rfn = file.as_posix().split('/')[-1][0:12]
rfns.append(rfn)
if files:
logger.info('running error analysis for station {}'.format(rfn[0:4].upper()))
all_errors = []
errors = []
dates = []
rinex = []
files = path_glob(path, '*.err')
for file in files:
rfn = file.as_posix().split('/')[-1][0:12]
# now, filter the error files that were copyed but there is tdp file
# i.e., the gipsyx run was successful:
if rfn in rfns:
continue
else:
dt, _ = get_timedate_and_station_code_from_rinex(rfn)
dates.append(dt)
rinex.append(rfn)
with open(file) as f:
content = f.readlines()
# you may also want to remove whitespace characters like `\n` at
# the end of each line
content = [x.strip() for x in content]
all_errors.append(content)
errors.append(find_errors(content, rfn))
er = [','.join(x) for x in all_errors]
df = pd.DataFrame(data=rinex, index=dates, columns=['rinex'])
df['error'] = er
df = df.sort_index()
total = len(rfns) + len(df)
good = len(rfns)
bad = len(df)
logger.info('total files: {}, successful runs: {}, errornous runs: {}'.format(
total, good, bad))
logger.info('success percent: {0:.1f}%'.format(100.0 * good / total))
logger.info('error percent: {0:.1f}%'.format(100.0 * bad / total))
# now count the similar errors and sort:
flat_list = [item for sublist in errors for item in sublist]
counted_errors = Counter(flat_list)
errors_sorted = sorted(counted_errors.items(), key=lambda x: x[1],
reverse=True)
return errors_sorted, df
def compare_gipsyx_soundings(sound_path=sound_path, gps_station='acor',
times=['1996', '2019'], var='pw'):
import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
import matplotlib.dates as mdates
import xarray as xr
from aux_gps import path_glob
# sns.set_style('whitegrid')
# ds = mean_zwd_over_sound_time(
# physical_file, ims_path=ims_path, gps_station='tela',
# times=times)
sound_station = gnss_sound_stations_dict.get(gps_station)
gnss = load_gipsyx_results(plot_fields=None, station=gps_station)
sound_file = path_glob(sound_path, 'station_{}_soundings_ts_tm_tpw*.nc'.format(sound_station))[0]
sds = xr.open_dataset(sound_file)
time_dim = list(set(sds.dims))[0]
sds = sds.rename({time_dim: 'time'})
sds[gps_station] = gnss.WetZ
if var == 'zwd':
k = kappa(sds['Tm'], Tm_input=True)
sds['sound'] = sds.Tpw / k
sds[gps_station] = gnss.WetZ
elif var == 'pw':
linear_model = ml_models_T_from_sounding(times=times,
station=sound_station,
plot=False, models=['LR'])
linear_model = linear_model.sel(name='LR').values.item()
k = kappa_ml(sds['Ts'] - 273.15, model=linear_model, no_error=True)
sds[gps_station] = sds[gps_station] * k
sds['sound'] = sds.Tpw
sds = sds.dropna('time')
sds = sds.sel(time=slice(*times))
df = sds[['sound', gps_station]].to_dataframe()
fig, axes = plt.subplots(2, 1, sharex=True, figsize=(12, 8))
[x.set_xlim([pd.to_datetime(times[0]), pd.to_datetime(times[1])])
for x in axes]
df.columns = ['{} soundings'.format(sound_station), '{} GNSS station'.format(gps_station)]
sns.scatterplot(
data=df,
s=20,
ax=axes[0],
style='x',
linewidth=0,
alpha=0.8)
# axes[0].legend(['Bet_Dagan soundings', 'TELA GPS station'])
df_r = df.iloc[:, 0] - df.iloc[:, 1]
df_r.columns = ['Residual distribution']
sns.scatterplot(
data=df_r,
color='k',
s=20,
ax=axes[1],
linewidth=0,
alpha=0.5)
axes[0].grid(b=True, which='major')
axes[1].grid(b=True, which='major')
if var == 'zwd':
axes[0].set_ylabel('Zenith Wet Delay [cm]')
axes[1].set_ylabel('Residuals [cm]')
elif var == 'pw':
axes[0].set_ylabel('Precipitable Water [mm]')
axes[1].set_ylabel('Residuals [mm]')
# sonde_change_x = pd.to_datetime('2013-08-20')
# axes[1].axvline(sonde_change_x, color='red')
# axes[1].annotate(
# 'changed sonde type from VIZ MK-II to PTU GPS',
# (mdates.date2num(sonde_change_x),
# 10),
# xytext=(
# 15,
# 15),
# textcoords='offset points',
# arrowprops=dict(
# arrowstyle='fancy',
# color='red'),
# color='red')
plt.tight_layout()
plt.subplots_adjust(wspace=0, hspace=0.01)
return sds
def produce_zwd_from_sounding_and_compare_to_gps(phys_sound_file=phys_soundings,
zwd_file=tela_zwd_aligned,
tm=None, plot=True):
"""compare zwd from any gps station (that first has to be aligned to
Bet_dagan station) to that of Bet-Dagan radiosonde station using tm from
either bet dagan or user inserted. by default, using zwd from pw by
inversing Bevis 1992 et al. formula"""
import xarray as xr
import matplotlib.pyplot as plt
import seaborn as sns
import matplotlib.dates as mdates
station = zwd_file.as_posix().split('/')[-1].split('_')[0]
zwd_and_tpw = xr.open_dataset(zwd_file)
tpw = zwd_and_tpw['Tpw']
pds = get_ts_tm_from_physical(phys_sound_file, plot=False)
if tm is None:
k = kappa(pds['tm'], Tm_input=True)
else:
k = kappa(tm, Tm_input=True)
zwd_sound = tpw / k
zwd_and_tpw['WetZ_from_bet_dagan'] = zwd_sound
radio = zwd_and_tpw['WetZ_from_bet_dagan']
gps = zwd_and_tpw['{}_WetZ'.format(station)]
gps.name = ['WetZ_from_TELA']
if plot:
# sns.set_style("whitegrid")
df = radio.to_dataframe()
df[gps.name] = gps.to_dataframe()
fig, axes = plt.subplots(2, 1, sharex=True, figsize=(12, 8))
[x.set_xlim([pd.to_datetime('2007-12-31'), pd.to_datetime('2019')]) for x in axes]
# radio.plot.line(marker='.', linewidth=0., ax=axes[0])
sns.scatterplot(data=df, s=20, ax=axes[0], style='x', linewidth=0, alpha=0.8)
# gps.plot.line(marker='.', linewidth=0., ax=axes[0])
#sns.scatterplot(data=df, y= 'tela_WetZ', s=10, ax=axes[0])
# axes[0].legend('radiosonde', '{}_gnss_site'.format(station))
df_r = df.iloc[:, 0] - df.iloc[:, 1]
df_r.columns = ['Residuals']
# (radio - gps).plot.line(marker='.', linewidth=0., ax=axes[1])
sns.scatterplot(data=df_r, color = 'k', s=20, ax=axes[1], linewidth=0, alpha=0.5)
axes[0].grid(b=True, which='major')
axes[1].grid(b=True, which='major')
axes[0].set_ylabel('Zenith Wet Delay [cm]')
axes[1].set_ylabel('Residuals [cm]')
axes[0].set_title('Zenith wet delay from Bet-Dagan radiosonde station and TELA GNSS satation')
sonde_change_x = pd.to_datetime('2013-08-20')
axes[1].axvline(sonde_change_x, color='red')
axes[1].annotate('changed sonde type from VIZ MK-II to PTU GPS', (mdates.date2num(sonde_change_x), 15), xytext=(15, 15),
textcoords='offset points', arrowprops=dict(arrowstyle='fancy', color='red'), color='red')
# axes[1].set_aspect(3)
plt.tight_layout()
plt.subplots_adjust(wspace=0, hspace=0)
# plt.figure()
# (radio - gps).plot.hist(bins=100)
return zwd_and_tpw
def fit_ts_tm_produce_ipw_and_compare_TELA(phys_sound_file=phys_soundings,
zwd_file=tela_zwd_aligned,
IMS_file=None,
sound_path=sound_path,
categories=None, model='LR',
times=['2005', '2019'],
**compare_kwargs):
"""categories can be :'bevis', None, 'season' and/or 'hour'. None means
whole dataset ts-tm.
models can be 'LR' or 'TSEN'. compare_kwargs is for
compare_to_sounding2 i.e., times, season, hour, title"""
import xarray as xr
print(compare_kwargs)
if categories == 'bevis':
results = None
compare_kwargs.update({'title': None})
else:
results = ml_models_T_from_sounding(sound_path, categories, model,
physical_file=phys_sound_file,
times=times)
if categories is None:
compare_kwargs.update({'title': 'whole'})
elif categories is not None and categories != 'bevis':
if isinstance(categories, str):
compare_kwargs.update({'title': [categories][0]})
elif isinstance(categories, list):
compare_kwargs.update({'title': 'hour_season'})
zwd_and_tpw = xr.open_dataset(zwd_file)
if times is not None:
zwd_and_tpw = zwd_and_tpw.sel(time=slice(*times))
station = zwd_file.as_posix().split('/')[-1].split('_')[0]
tpw = zwd_and_tpw['Tpw']
if IMS_file is None:
T = xr.open_dataset(ims_path / 'GNSS_5mins_TD_ALL_1996_2019.nc')
T = T['tela']
else:
# load the 10 mins temperature data from IMS:
T = xr.open_dataset(IMS_file)
T = T.to_array(name='t').squeeze(drop=True)
zwd_and_tpw = zwd_and_tpw.rename({'{}_WetZ'.format(
station): 'WetZ', '{}_WetZ_error'.format(station): 'WetZ_error'})
zwd = zwd_and_tpw[['WetZ', 'WetZ_error']]
zwd.attrs['station'] = station
pw_gps = produce_single_station_IPW(zwd, T, mda=results, model_name=model)
compare_to_sounding2(pw_gps['PW'], tpw, station=station, **compare_kwargs)
return pw_gps, tpw
def mean_ZWD_over_sound_time_and_fit_tstm(path=work_yuval,
sound_path=sound_path,
data_type='phys',
ims_path=ims_path,
gps_station='tela',
times=['2007', '2019'], plot=False,
cats=None,
savepath=None):
import xarray as xr
import joblib
from aux_gps import multi_time_coord_slice
from aux_gps import path_glob
from aux_gps import xr_reindex_with_date_range
from sounding_procedures import load_field_from_radiosonde
from sounding_procedures import get_field_from_radiosonde
"""mean the WetZ over the gps station soundings datetimes to get a more
accurate realistic measurement comparison to soundings"""
# tpw = load_field_from_radiosonde(path=sound_path, field='PW', data_type=data_type,
# reduce='max',dim='Height', plot=False)
min_time = get_field_from_radiosonde(path=sound_path, field='min_time', data_type='phys',
reduce=None, plot=False)
max_time = get_field_from_radiosonde(path=sound_path, field='max_time', data_type='phys',
reduce=None, plot=False)
sound_time = get_field_from_radiosonde(path=sound_path, field='sound_time', data_type='phys',
reduce=None, plot=False)
min_time = min_time.dropna('sound_time').values
max_time = max_time.dropna('sound_time').values
# load the zenith wet daley for GPS (e.g.,TELA) station:
file = path_glob(path, 'ZWD_thresh_*.nc')[0]
zwd = xr.open_dataset(file)[gps_station]
zwd_error = xr.open_dataset(file)[gps_station + '_error']
freq = pd.infer_freq(zwd.time.values)
if not freq:
zwd = xr_reindex_with_date_range(zwd)
zwd_error = xr_reindex_with_date_range(zwd_error)
freq = pd.infer_freq(zwd.time.values)
min_time = zwd.time.sel(time=min_time, method='nearest').values
max_time = zwd.time.sel(time=max_time, method='nearest').values
da_group = multi_time_coord_slice(min_time, max_time, freq=freq,
time_dim='time', name='sound_time')
zwd[da_group.name] = da_group
zwd_error[da_group.name] = da_group
ds = zwd.groupby(zwd[da_group.name]).mean(
'time').to_dataset(name='{}'.format(gps_station))
ds['{}_std'.format(gps_station)] = zwd.groupby(
zwd[da_group.name]).std('time')
ds['{}_error'.format(gps_station)] = zwd_error.groupby(
zwd[da_group.name]).mean('time')
ds['sound_time'] = sound_time.dropna('sound_time')
# ds['tpw_bet_dagan'] = tpw
wetz = ds['{}'.format(gps_station)]
wetz_error = ds['{}_error'.format(gps_station)]
# do the same for surface temperature:
file = path_glob(ims_path, 'GNSS_5mins_TD_ALL_*.nc')[0]
td = xr.open_dataset(file)[gps_station].to_dataset(name='ts')
min_time = td.time.sel(time=min_time, method='nearest').values
max_time = td.time.sel(time=max_time, method='nearest').values
freq = pd.infer_freq(td.time.values)
da_group = multi_time_coord_slice(min_time, max_time, freq=freq,
time_dim='time', name='sound_time')
td[da_group.name] = da_group
ts_sound = td.ts.groupby(td[da_group.name]).mean('time')
ts_sound['sound_time'] = sound_time.dropna('sound_time')
ds['{}_ts'.format(gps_station)] = ts_sound
ts_sound = ts_sound.rename({'sound_time': 'time'})
# prepare ts-tm data:
tm = get_field_from_radiosonde(path=sound_path, field='Tm', data_type=data_type,
reduce=None, dim='Height', plot=False)
ts = get_field_from_radiosonde(path=sound_path, field='Ts', data_type=data_type,
reduce=None, dim='Height', plot=False)
tstm = xr.Dataset()
tstm['Tm'] = tm
tstm['Ts'] = ts
tstm = tstm.rename({'sound_time': 'time'})
# select a model:
mda = ml_models_T_from_sounding(categories=cats, models=['LR', 'TSEN'],
physical_file=tstm, plot=plot,
times=times)
# compute the kappa function and multiply by ZWD to get PW(+error):
k, dk = produce_kappa_ml_with_cats(ts_sound, mda=mda, model_name='TSEN')
ds['{}_pw'.format(gps_station)] = k.rename({'time': 'sound_time'}) * wetz
ds['{}_pw_error'.format(gps_station)] = np.sqrt(
wetz_error**2.0 + dk**2.0)
# divide by kappa calculated from bet_dagan ts to get bet_dagan zwd:
k = kappa(tm, Tm_input=True)
# ds['zwd_bet_dagan'] = ds['tpw_bet_dagan'] / k
if savepath is not None:
m = mda.to_dataset('name')
for model in m:
joblib.dump(m[model].item(), savepath/'ts_tm_{}.pkl'.format(model))
print('{} saved to {}.'.format(model, savepath))
return ds, mda
def load_mda(path=work_yuval):
import joblib
from aux_gps import path_glob
import xarray as xr
files = path_glob(path, 'ts_tm_*.pkl')
names = [x.as_posix().split('/')[-1].split('.')[0].split('_')[-1] for x in files]
dsl = [joblib.load(x) for x in files]
dsl = [xr.DataArray(x) for x in dsl]
mda = xr.concat(dsl, 'name')
mda['name'] = names
mda.attrs['time_dim'] = 'time'
mda.attrs['LR_whole_stderr_slope'] = 0.006420637318868484
return mda
#def align_physical_bet_dagan_soundings_pw_to_gps_station_zwd(
# phys_sound_file, ims_path=ims_path, gps_station='tela',
# savepath=work_yuval, model=None):
# """compare the IPW of the physical soundings of bet dagan station to
# the any gps station - using IMS temperature of that gps station"""
# from aux_gps import get_unique_index
# from aux_gps import keep_iqr
# from aux_gps import dim_intersection
# import xarray as xr
# import numpy as np
# filename = '{}_zwd_aligned_with_physical_bet_dagan.nc'.format(gps_station)
# if not (savepath / filename).is_file():
# print('saving {} to {}'.format(filename, savepath))
# # first load physical bet_dagan Tpw, Ts, Tm and dt_range:
# phys = xr.open_dataset(phys_sound_file)
# # clean and merge:
# p_list = [get_unique_index(phys[x], 'sound_time')
# for x in ['Ts', 'Tm', 'Tpw', 'dt_range']]
# phys_ds = xr.merge(p_list)
# phys_ds = keep_iqr(phys_ds, 'sound_time', k=2.0)
# phys_ds = phys_ds.rename({'Ts': 'ts', 'Tm': 'tm'})
# # load the zenith wet daley for GPS (e.g.,TELA) station:
# zwd = load_gipsyx_results(station=gps_station, plot_fields=None)
# # zwd = xr.open_dataset(zwd_file)
# zwd = zwd[['WetZ', 'WetZ_error']]
# # loop over dt_range and average the results on PW:
# wz_list = []
# wz_std = []
# wz_error_list = []
# for i in range(len(phys_ds['dt_range'].sound_time)):
# min_time = phys_ds['dt_range'].isel(sound_time=i).sel(bnd='Min').values
# max_time = phys_ds['dt_range'].isel(sound_time=i).sel(bnd='Max').values
# wetz = zwd['WetZ'].sel(time=slice(min_time, max_time)).mean('time')
# wetz_std = zwd['WetZ'].sel(time=slice(min_time, max_time)).std('time')
# wetz_error = zwd['WetZ_error'].sel(time=slice(min_time, max_time)).mean('time')
# wz_std.append(wetz_std)
# wz_list.append(wetz)
# wz_error_list.append(wetz_error)
# wetz_gps = xr.DataArray(wz_list, dims='sound_time')
# wetz_gps.name = '{}_WetZ'.format(gps_station)
# wetz_gps_error = xr.DataArray(wz_error_list, dims='sound_time')
# wetz_gps_error.name = '{}_WetZ_error'.format(gps_station)
# wetz_gps_std = xr.DataArray(wz_list, dims='sound_time')
# wetz_gps_std.name = '{}_WetZ_std'.format(gps_station)
# wetz_gps['sound_time'] = phys_ds['sound_time']
# wetz_gps_error['sound_time'] = phys_ds['sound_time']
# new_time = dim_intersection([wetz_gps, phys_ds['Tpw']], 'sound_time')
# wetz_gps = wetz_gps.sel(sound_time=new_time)
# tpw_bet_dagan = phys_ds.Tpw.sel(sound_time=new_time)
# zwd_and_tpw = xr.merge([wetz_gps, wetz_gps_error, wetz_gps_std,
# tpw_bet_dagan])
# zwd_and_tpw = zwd_and_tpw.rename({'sound_time': 'time'})
# comp = dict(zlib=True, complevel=9) # best compression
# encoding = {var: comp for var in zwd_and_tpw.data_vars}
# zwd_and_tpw.to_netcdf(savepath / filename, 'w', encoding=encoding)
# print('Done!')
# return
# else:
# print('found file!')
# zwd_and_tpw = xr.open_dataset(savepath / filename)
# wetz = zwd_and_tpw['{}_WetZ'.format(gps_station)]
# wetz_error = zwd_and_tpw['{}_WetZ_error'.format(gps_station)]
# # load the 10 mins temperature data from IMS:
# td = xr.open_dataset(ims_path/'GNSS_5mins_TD_ALL_1996_2019.nc')
# td = td[gps_station]
# td.name = 'Ts'
# # tela_T = tela_T.resample(time='5min').ffill()
# # compute the kappa function and multiply by ZWD to get PW(+error):
# k, dk = kappa_ml(td, model=model, verbose=True)
# kappa = k.to_dataset(name='{}_kappa'.format(gps_station))
# kappa['{}_kappa_error'.format(gps_station)] = dk
# PW = (
# kappa['{}_kappa'.format(gps_station)] *
# wetz).to_dataset(
# name='{}_PW'.format(gps_station)).squeeze(
# drop=True)
# PW['{}_PW_error'.format(gps_station)] = np.sqrt(
# wetz_error**2.0 +
# kappa['{}_kappa_error'.format(gps_station)]**2.0)
# PW['TPW_bet_dagan'] = zwd_and_tpw['Tpw']
# PW = PW.dropna('time')
# return PW
def read_log_files(path, savepath=None, fltr='updated_by_shlomi',
suff='*.log'):
"""read gnss log files for putting them into ocean tides model"""
import pandas as pd
from aux_gps import path_glob
from tabulate import tabulate
def to_fwf(df, fname, showindex=False):
from tabulate import simple_separated_format
tsv = simple_separated_format(" ")
# tsv = 'plain'
content = tabulate(
df.values.tolist(), list(
df.columns), tablefmt=tsv, showindex=showindex, floatfmt='f')
open(fname, "w").write(content)
files = sorted(path_glob(path, glob_str=suff))
record = {}
for file in files:
filename = file.as_posix().split('/')[-1]
if fltr not in filename:
continue
station = filename.split('_')[0]
print('reading station {} log file'.format(station))
with open(file) as f:
content = f.readlines()
content = [x.strip() for x in content]
posnames = ['X', 'Y', 'Z']
pos_list = []
for pos in posnames:
text = [
x for x in content if '{} coordinate (m)'.format(pos) in x][0]
xyz = float(text.split(':')[-1])
pos_list.append(xyz)
text = [x for x in content if 'Site Name' in x][0]
name = text.split(':')[-1]
st_id = [x for x in content if 'Four Character ID' in x][0]
st_id = st_id.split(':')[-1]
record[st_id] = pos_list
pos_list.append(name)
df = pd.DataFrame.from_dict(record, orient='index')
posnames.append('name')
df.columns = posnames
if savepath is not None:
savefilename = 'stations_approx_loc.txt'
show_index = [x + ' ' for x in df.index.tolist()]
to_fwf(df, savepath / savefilename, show_index)
# df.to_csv(savepath / savefilename, sep=' ')
print('{} was saved to {}.'.format(savefilename, savepath))
return df
def analyze_missing_rinex_files(path, savepath=None):
from aux_gps import get_timedate_and_station_code_from_rinex
from aux_gps import datetime_to_rinex_filename
from aux_gps import path_glob
import pandas as pd
dt_list = []
files = path_glob(path, '*.Z')
for file in files:
filename = file.as_posix().split('/')[-1][:-2]
dt, station = get_timedate_and_station_code_from_rinex(filename)
dt_list.append(dt)
dt_list = sorted(dt_list)
true = pd.date_range(dt_list[0], dt_list[-1], freq='1D')
# df = pd.DataFrame(dt_list, columns=['downloaded'], index=true)
dif = true.difference(dt_list)
dts = [datetime_to_rinex_filename(station, x) for x in dif]
df_missing = pd.DataFrame(data=dts, index=dif.strftime('%Y-%m-%d'),
columns=['filenames'])
df_missing.index.name = 'dates'
if savepath is not None:
filename = station + '_missing_rinex_files.txt'
df_missing.to_csv(savepath / filename)
print('{} was saved to {}'.format(filename, savepath))
return df_missing
def proc_1minute(path):
stations = pd.read_csv(path + 'Zstations', header=0,
delim_whitespace=True)
station_names = stations['NAME'].values.tolist()
df_list = []
for st_name in station_names:
print('Proccessing ' + st_name + ' Station...')
df = pd.read_csv(PW_stations_path + st_name, delim_whitespace=True)
df.columns = ['date', 'time', 'PW']
df.index = pd.to_datetime(df['date'] + 'T' + df['time'])
df.drop(columns=['date', 'time'], inplace=True)
df_list.append(df)
df = pd.concat(df_list, axis=1)
print('Concatanting to Xarray...')
# ds = xr.concat([df.to_xarray() for df in df_list], dim="station")
# ds['station'] = station_names
df.columns = station_names
ds = df.to_xarray()
ds = ds.rename({'index': 'time'})
# da = ds.to_array(name='PW').squeeze(drop=True)