-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathGNSS_post_processing.py
1531 lines (1343 loc) · 57.1 KB
/
GNSS_post_processing.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
# -*- coding: utf-8 -*-
"""
@author: Adrien Wehrlé, University of Oslo (UiO), 2019
Contains different developed (SDF,RF,KMF and KM2FA) and used (EWS and GWS)
methods for GNSS post-processing. For each method, the different steps are run
below the initialization of all needed functions.
For more informations, e.g. a detailed description of the methods,
please see the report available here:
https://github.com/AdrienWehrle/GNSS_post_processing/blob/master/WEHRLE_UiO_internship_report.pdf
"""
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import scipy.io
import matplotlib.cm as cm
from datetime import datetime, timedelta
import time
import pickle
from kneed import KneeLocator
from collections import Counter
import scipy.stats as stats
from scipy.stats import linregress
from sklearn.cluster import KMeans
from scipy.spatial.distance import cdist
def SDF_EM(
df,
sd_threshold=np.nanmean(df.global_sd),
fq="24H",
sampling_fq="1H",
w_min=0,
w_max=3 * np.nanstd(df.global_sd),
w_step=0.0001,
temporal_resolution=False,
representation=False,
save=False,
):
"""Determination of the SDF method's optimal threshold (step 2) with the
help of the Elbow Method (from w_min to w_max each w_step) to compute
daily velocities (see Adrien Wehrlé's internship report).
If temporal_resolution==True, velocities are computed for each temporal
resolutions (24, 12, 8, 6, 3 and 1 hour).
If save==True, the resulted velocities are saved in a pickle file
(if temporal_resolution==True) or a csv file (if temporal_resolution=False).
If representation==True, results of the Elbow Method and velocities are
displayed.
"""
def SDF(
df,
sd_threshold=np.nanmean(df.global_sd),
fq="24H",
sampling_fq="1H",
w_min=0,
w_max=3 * np.nanstd(df.global_sd),
):
"""The Standard Deviations Filtering (SDF) is a method that post-processes
GNSS measurements to obtain the resulting velocities. It consists in four steps:
1) Ambiguities resolution check
2) Global standard deviation filter
3) Distance to the linear trend filter
4) Velocity determination
"""
processing_start = time.clock()
df_length = len(df)
def amb_filter(df, init=df_length):
"""
Deleting all values where ambiguities are not solved (Q!=1)
"""
initial_len = len(df)
df = df.iloc[np.where(df.Q == 1)]
final_len = len(df)
nb_del_values = initial_len - final_len
pc_add_values = nb_del_values / init * 100
print(
"amb_filter: %d values removed" % nb_del_values,
"(%.5f %% of the raw data)" % pc_add_values,
)
return df, nb_del_values
def sd_filter(df, init=df_length, sdthr=sd_threshold):
"""
Deleting all values that have a global standard deviation (global_sd)
above a given threshold (sdthr).
The global standard deviation is obtained by combining the standard
deviations of each positioning component (X, Y and Z) computed
by RTKLIB, at each timestep.
"""
# uncomment if not already determined
# df['global_sd'] = np.sqrt(df.sde ** 2 + df.sdu ** 2 + df.sdn * *2)
initial_len = len(df)
df = df[df.global_sd < sdthr]
final_len = len(df)
nb_del_values = initial_len - final_len
pc_add_values = nb_del_values / init * 100
print(
"sd_filter: %d values have been removed" % nb_del_values,
"(%.5f %% of the raw data)" % pc_add_values,
)
return df, nb_del_values
def pos_filter(df, init=df_length):
"""
Deleting values by computing their minimum distance (mindist) to
the linear trend of the station track.
Values whose zscored distances are above 1 sigma are deleted.
"""
def pos_filter_intermediate(df, init=df_length):
def linear_regression(df):
lr_results = linregress(df.X, df.Y)
y = df.X * lr_results.slope + lr_results.intercept
return y, lr_results
linear_regress, lr_results = linear_regression(df)
residuals = df.Y - linear_regress
mindist = np.abs(np.sin(1 - lr_results.slope) * residuals)
return mindist
mindist = pos_filter_intermediate(df)
zscore = stats.zscore(mindist)
df["zscore"] = zscore
initial_len = len(df)
df = df[df.zscore < 1]
final_len = len(df)
nb_del_values = initial_len - final_len
pc_add_values = nb_del_values / init * 100
print(
"pos_filter: %d values removed" % nb_del_values,
"(%.5f %% of the raw data)" % pc_add_values,
)
return df, nb_del_values
def appropriate_datetime(
df, freq="12H", sampling_freq="1H", nb_col=0, mode="mean"
):
"""
Determine the appropriate datetime while resampling a df with a
given timestep (freq) and a targeted precision (sampling_freq).
Resampling functions (e.g. pd.resample()) always fix the windows
indexes to the lowest limit (with a frequency of 12 hours, timesteps
are initialy 00:00 and 12:00). It is here proposed to replace these
indexes by the mean time (mean mode) or the median time (median mode)
of the values contained in each window.
nb_col: column index of the datetimes
"""
if mode == "mean":
df2 = df.resample(sampling_freq).mean()
df_modified = pd.DataFrame(df2.resample(freq).mean())
if mode == "median":
df2 = df.resample(sampling_freq).median()
df_modified = pd.DataFrame(df2.resample(freq).median())
values = (
df2.iloc[:, nb_col]
.resample(freq)
.apply(lambda x: np.where(~np.isnan(x))[-1])
)
res = []
for i in range(0, len(values)):
interm = np.array(values.iloc[i])
res.append(interm) # necessary to turn resampling results into a df
res = pd.DataFrame(res)
mean_time_h = res.mean(axis=1, skipna=True)
mean_time_m = (mean_time_h % 1) * 60 # turn the decimal part into minutes
dt = []
for i in range(0, len(mean_time_h)):
if mean_time_h.iloc[i] / mean_time_h.iloc[i] == 1:
date = datetime.strptime(
str(df_modified.index[i]), "%Y-%m-%d %H:%M:%S"
)
if sampling_freq[-1] == "H":
date = date.replace(
hour=int(mean_time_h.iloc[i]) + df_modified.index.hour[i]
)
if sampling_freq[-1] == "T":
date = date.replace(
hour=int(mean_time_h.iloc[i]) + df_modified.index.hour[i]
)
date = date.replace(
minute=int(
mean_time_m.iloc[i] + df_modified.index.minute[i]
)
)
dt.append(date)
else:
dt.append(
datetime.strptime(
str(df_modified.index[i]), "%Y-%m-%d %H:%M:%S"
)
)
dt = pd.to_datetime(dt, format="%Y-%m-%d %H:%M:%S")
df_modified.index = dt
return df_modified
df["timestamp"] = df.index
interm_results, nbdv1 = amb_filter(df)
interm_results, nbdv2 = sd_filter(interm_results)
data_filt, nbdv3 = pos_filter(interm_results)
nbdv_total = nbdv1 + nbdv2 + nbdv3
per_nbdv_total = (nbdv_total / df_length) * 100
print("\n")
print(
"In total, %d values removed" % nbdv_total,
"(%.3f %% of the raw data)" % per_nbdv_total,
)
data_filt_dt = appropriate_datetime(
data_filt, freq=fq, sampling_freq=sampling_fq
)
# Velocity determination
deltatime = np.diff(data_filt_dt.index)
deltatime = pd.DataFrame(deltatime)
deltatime_dec = deltatime.iloc[:, 0] / timedelta(days=1)
SDF_velocity = pd.DataFrame(
(np.sqrt(np.diff(data_filt_dt.X) ** 2 + np.diff(data_filt_dt.Y) ** 2))
/ deltatime_dec
)
SDF_velocity.index = data_filt_dt.index[:-1]
SDF_vertvelocity = pd.DataFrame(np.diff(data_filt_dt.Z) / deltatime_dec)
SDF_vertvelocity.index = data_filt_dt.index[:-1]
processing_end = time.clock()
processing_time = processing_end - processing_start
if processing_time > 60:
processing_time = processing_time / 60
print("KMF method processing time: %.3f minutes" % processing_time)
if processing_time < 60:
print("KMF method processing time: %.3f seconds" % processing_time)
return SDF_velocity, SDF_vertvelocity
if temporal_resolution:
freqs = np.array(
[
["24H", "1H"],
["12H", "1H"],
["8H", "1H"],
["6H", "1H"],
["3H", "1H"],
["1H", "1T"],
]
)
# global_sds = np.arange(0.7 * np.mean(df.global_sd),
# 3 * np.mean(df.global_sd), 0.0001)
global_sd_range = np.arange(w_min, w_max, w_step)
missval = []
SDF_velocities = []
colors = cm.rainbow(np.linspace(0, 1, len(freqs)))
j = 0
t = 0
for k in range(0, len(freqs)):
missval = []
for i in global_sd_range:
SDF_velocity, SDF_vertvelocity = SDF(
df, sd_threshold=i, fq=freqs[k][0], sampling_fq=freqs[k][1]
)
missval.append(np.sum(np.isnan(SDF_velocity)) / len(SDF_velocity) * 100)
mv = np.float(np.sum(np.isnan(SDF_velocity)) / len(SDF_velocity) * 100)
if mv == 100:
t += 1
if t == 3:
print("FINISHED")
break
print(" %d" % j, "/ %d" % len(global_sd_range))
j += 1
# a rolling linear regression is used to better determine the elbow point
if np.int(len(global_sd_range) / 10) % 2 == 0: # window size must be odd
regress = scipy.signal.savgol_filter(
missval, np.int(len(global_sd_range) / 10) + 1, 1
)
else:
regress = scipy.signal.savgol_filter(
missval, np.int(len(global_sd_range) / 10), 1
)
# improvment needed to automatically find the curve shape and slope
kn = KneeLocator(
global_sd_range[: j + 1],
regress,
curve="convex",
direction="decreasing",
)
optimal_sdthreshold = kn.knee
print("KNEE:", optimal_sdthreshold)
SDF_velocity, SDF_vertvelocity = SDF(
df,
sd_threshold=optimal_sdthreshold,
fq=freqs[k][0],
sampling_fq=freqs[k][1],
)
SDF_velocities.append(SDF_velocity)
# results visualisation
if representation:
plt.figure()
plt.subplot(211)
plt.plot(
global_sd_range[: j + 1],
missval,
color="black",
label="",
alpha=0.5,
)
plt.plot(global_sd_range[: j + 1], regress, color=colors[k])
plt.xlabel("Global standard deviation threshold", fontsize=14)
plt.ylabel("Missing values percentage ($\%$)", fontsize=14)
plt.axvline(
optimal_sdthreshold,
label="knee point: %.3f" % optimal_sdthreshold,
color=colors[k],
)
plt.subplot(212)
plt.plot(
SDF_velocity.index,
SDF_velocity.iloc[:, 0],
color="black",
alpha=0.5,
)
plt.xlabel("Time (year-month)", fontsize=16)
plt.ylabel("Velocity (meters/day)", fontsize=16)
print("%d" % k, "/ %d" % len(freqs))
j = 0
t = 0
results = {
"24H": SDF_velocities[0],
"12H": SDF_velocities[1],
"8H": SDF_velocities[2],
"6H": SDF_velocities[3],
"3H": SDF_velocities[4],
"1H": SDF_velocities[5],
}
if save:
f = open("SDF_method.pkl", "wb")
pickle.dump(results, f)
f.close()
else:
global_sd_range = np.arange(w_min, w_max, w_step)
missval = []
colors = cm.rainbow(np.linspace(0, 1, len(freqs)))
j = 0
t = 0
for i in global_sd_range:
SDF_velocity, SDF_vertvelocity = SDF(
df, sd_threshold=i, fq="24H", sampling_fq="1H"
)
missval.append(np.sum(np.isnan(SDF_velocity)) / len(SDF_velocity) * 100)
mv = np.float(np.sum(np.isnan(SDF_velocity)) / len(SDF_velocity) * 100)
if mv == 100:
t += 1
if t == 3:
print("FINISHED")
break
print("%d" % j, "/ %d" % len(global_sd_range))
j += 1
# a rolling linear regression is used to better determine the elbow point
if np.int(len(global_sd_range) / 10) % 2 == 0: # window size must be odd
regress = scipy.signal.savgol_filter(
missval, np.int(len(global_sd_range) / 10) + 1, 1
)
else:
regress = scipy.signal.savgol_filter(
missval, np.int(len(global_sd_range) / 10), 1
)
kn = KneeLocator(
global_sd_range[: j + 1],
regress,
curve="convex",
direction="decreasing",
)
optimal_sdthreshold = kn.knee
print("KNEE:", optimal_sdthreshold)
SDF_velocity, SDF_vertvelocity = SDF(
df, sd_threshold=optimal_sdthreshold, fq="24H", sampling_fq="1H"
)
results = pd.DataFrame([SDF_velocity, SDF_vertvelocity])
# results visualisation
if representation:
plt.figure()
plt.subplot(211)
plt.plot(
global_sd_range[: j + 1],
missval,
color="black",
label="",
alpha=0.5,
)
plt.plot(global_sd_range[: j + 1], regress)
plt.xlabel("Global standard deviation threshold", fontsize=14)
plt.ylabel("Missing values percentage ($\%$)", fontsize=14)
plt.axvline(
optimal_sdthreshold, label="knee point: %.3f" % optimal_sdthreshold
)
plt.subplot(212)
plt.plot(
SDF_velocity.index,
SDF_velocity.iloc[:, 0],
color="black",
alpha=0.5,
)
plt.xlabel("Time (year-month)", fontsize=16)
plt.ylabel("Velocity (meters/day)", fontsize=16)
if save:
results.to_csv("SDF_method.csv")
return results
def RF_EM(
df,
ratio_threshold=np.nanmean(df.ratio),
w_min=0,
w_max=3 * np.nanstd(df.ratio),
w_step=0.5,
temporal_resolution=False,
representation=False,
save=False,
):
"""Determination of the RF method's optimal threshold (step 1) with the
help of the Elbow Method (from w_min to w_max each w_step) to compute daily
velocities (see Adrien Wehrlé's internship report).
If temporal_resolution=True, velocities are computed for each temporal
resolutions (24, 12, 8, 6, 3 and 1 hour).
If representation=True, results of the Elbow Method and velocities are displayed.
If save=True, the resulted velocities are saved in a pickle file (if
temporal_resolution=True) or a csv file (if temporal_resolution=False).
"""
def RF(
df,
ratio_threshold=np.nanmean(df.ratio),
w_min=0,
w_max=3 * np.nanstd(df.ratio),
w_step=0.5,
):
"""The Ratio Filtering (RF) is a method that post-processes GNSS measurements
to obtain the resulting velocities. It consists in three steps:
1) Ratio variable filter
2) Distance to the linear trend filter
3) Velocity determination
"""
processing_start = time.clock()
df_length = len(df)
def ratio_filter(df, ratiothr=ratio_threshold, init=df_length):
"""
Deleting all values that have a ratio value (global_sd) above a
given threshold (ratiothr).
The global standard deviation is obtained by combining the standard
deviations of each positioning component (X, Y and Z) computed by
RTKLIB, at each timestep.
"""
initial_len = len(df)
df = df[df.ratio > ratiothr]
final_len = len(df)
nb_del_values = initial_len - final_len
pc_add_values = nb_del_values / init * 100
print(
"sd_filter: %d values have been removed" % nb_del_values,
"(%.5f %% of the raw data)" % pc_add_values,
)
return df, nb_del_values
def pos_filter(df, init=df_length):
"""
Deleting values by computing their minimum distance (mindist) to the linear trend of the station track.
Values whose zscored distances are above 1 sigma are deleted.
"""
def pos_filter_intermediate(df, init=df_length):
def linear_regression(df):
lr_results = linregress(df.X, df.Y)
y = df.X * lr_results.slope + lr_results.intercept
return y, lr_results
linregress, lr_results = linear_regression(df)
residuals = df.Y - linregress
mindist = np.abs(np.sin(1 - lr_results.slope) * residuals)
return mindist
mindist = pos_filter_intermediate(df)
zscore = stats.zscore(mindist)
df["zscore"] = zscore
initial_len = len(df)
df = df[df.zscore < 1]
final_len = len(df)
nb_del_values = initial_len - final_len
pc_add_values = nb_del_values / init * 100
print(
"pos_filter: %d values removed" % nb_del_values,
"(%.5f %% of the raw data)" % pc_add_values,
)
return df, nb_del_values
def appropriate_datetime(
df, freq="12H", sampling_freq="1H", nb_col=0, mode="mean"
):
"""
Determine the appropriate datetime while resampling a df with
a given timestep (freq) and a targeted precision (sampling_freq).
Resampling functions (e.g. pd.resample()) always fix the windows
indexes to the lowest limit (with a frequency of 12 hours,
timesteps are initialy 00:00 and 12:00). It is here proposed to
replace these indexes by the mean time (mean mode) or the median
time (median mode) of the values contained in each window.
nb_col: column index of the datetimes
"""
if mode == "mean":
df2 = df.resample(sampling_freq).mean()
df_modified = pd.DataFrame(df2.resample(freq).mean())
if mode == "median":
df2 = df.resample(sampling_freq).median()
df_modified = pd.DataFrame(df2.resample(freq).median())
values = (
df2.iloc[:, nb_col]
.resample(freq)
.apply(lambda x: np.where(~np.isnan(x))[-1])
)
res = []
for i in range(0, len(values)):
interm = np.array(values.iloc[i])
res.append(interm) # necessary to turn resampling results into a df
res = pd.DataFrame(res)
mean_time_h = res.mean(axis=1, skipna=True)
mean_time_m = (mean_time_h % 1) * 60 # turn the decimal part into minutes
dt = []
for i in range(0, len(mean_time_h)):
if mean_time_h.iloc[i] / mean_time_h.iloc[i] == 1:
date = datetime.strptime(
str(df_modified.index[i]), "%Y-%m-%d %H:%M:%S"
)
if sampling_freq[-1] == "H":
date = date.replace(
hour=int(mean_time_h.iloc[i]) + df_modified.index.hour[i]
)
if sampling_freq[-1] == "T":
date = date.replace(
hour=int(mean_time_h.iloc[i]) + df_modified.index.hour[i]
)
date = date.replace(
minute=int(
mean_time_m.iloc[i] + df_modified.index.minute[i]
)
)
dt.append(date)
else:
dt.append(
datetime.strptime(
str(df_modified.index[i]), "%Y-%m-%d %H:%M:%S"
)
)
dt = pd.to_datetime(dt, format="%Y-%m-%d %H:%M:%S")
df_modified.index = dt
return df_modified
df["timestamp"] = df.index
interm_results, nbdv1 = ratio_filter(df)
data_filt, nbdv2 = pos_filter(interm_results)
nbdv_total = nbdv1 + nbdv2
per_nbdv_total = (nbdv_total / df_length) * 100
print("\n")
print(
"In total, %d values removed" % nbdv_total,
"(%.3f %% of the raw data)" % per_nbdv_total,
)
data_filt_dt = appropriate_datetime(data_filt)
# velocity determination
deltatime = np.diff(data_filt_dt.index)
deltatime = pd.DataFrame(deltatime)
deltatime_dec = deltatime.iloc[:, 0] / timedelta(days=1)
RF_velocity = pd.DataFrame(
(np.sqrt(np.diff(data_filt_dt.X) ** 2 + np.diff(data_filt_dt.Y) ** 2))
/ deltatime_dec
)
RF_velocity.index = data_filt_dt.index[:-1]
RF_vertvelocity = pd.DataFrame(np.diff(data_filt_dt.Z) / deltatime_dec)
RF_vertvelocity.index = data_filt_dt.index[:-1]
processing_end = time.clock()
processing_time = processing_end - processing_start
if processing_time > 60:
processing_time = processing_time / 60
print("KMF method processing time: %.3f minutes" % processing_time)
if processing_time < 60:
print("KMF method processing time: %.3f seconds" % processing_time)
return RF_velocity, RF_vertvelocity
if temporal_resolution:
freqs = np.array(
[
["24H", "1H"],
["12H", "1H"],
["8H", "1H"],
["6H", "1H"],
["3H", "1H"],
["1H", "1T"],
]
)
ratios_range = np.arange(w_min, w_max, w_step)
# ratios=np.arange(0, np.mean(df.ratio) + 3 * np.std(df.ratio), 0.5)
missval = []
RF_velocities = []
colors = cm.rainbow(np.linspace(0, 1, len(freqs)))
j = 0
t = 0
for k in range(0, len(freqs)):
missval = []
for i in ratios_range:
RF_velocity, RF_vertvelocity = RF(
df, ratio_threshold=i, fq=freqs[k][0], sampling_fq=freqs[k][1]
)
missval.append(np.sum(np.isnan(RF_velocity)) / len(RF_velocity) * 100)
mv = np.float(np.sum(np.isnan(RF_velocity)) / len(RF_velocity) * 100)
if mv == 100:
t += 1
if t == 3:
print("FINISHED")
break
print(" %d" % j, "/ %d" % len(ratios_range))
j += 1
# a rolling linear regression is used to better determine the elbow point
if np.int(len(ratios_range) / 10) % 2 == 0: # window size must be odd
regress = scipy.signal.savgol_filter(
missval, np.int(len(ratios_range) / 10) + 1, 1
)
else:
regress = scipy.signal.savgol_filter(
missval, np.int(len(ratios_range) / 10), 1
)
kn = KneeLocator(
ratios_range[: j + 1], regress, curve="convex", direction="increasing"
)
optimal_rthreshold = kn.knee
print("KNEE:", optimal_rthreshold)
RF_velocity, RF_vertvelocity = RF(
df,
ratio_threshold=optimal_rthreshold,
fq=freqs[k][0],
sampling_fq=freqs[k][1],
)
RF_velocities.append(RF_velocity)
# results visualisation
if representation:
plt.figure()
plt.subplot(211)
plt.plot(
ratios_range[: j + 1], missval, color="black", label="", alpha=0.5
)
plt.plot(ratios_range[: j + 1], regress, color=colors[k])
plt.xlabel("Ratio threshold", fontsize=14)
plt.ylabel("Missing values percentage ($\%$)", fontsize=14)
plt.axvline(
optimal_rthreshold,
label="knee point: %.3f" % optimal_rthreshold,
color=colors[k],
)
plt.subplot(212)
plt.plot(
RF_velocity.index, RF_velocity.iloc[:, 0], color="black", alpha=0.5
)
plt.xlabel("Time (year-month)", fontsize=16)
plt.ylabel("Velocity (meters/day)", fontsize=16)
print("%d" % k, "/ %d" % len(freqs))
j = 0
t = 0
results = {
"24H": RF_velocities[0],
"12H": RF_velocities[1],
"8H": RF_velocities[2],
"6H": RF_velocities[3],
"3H": RF_velocities[4],
"1H": RF_velocities[5],
}
if save:
f = open("RF_method.pkl", "wb")
pickle.dump(results, f)
f.close()
else:
ratios_range = np.arange(w_min, w_max, w_step)
missval = []
colors = cm.rainbow(np.linspace(0, 1, len(freqs)))
j = 0
t = 0
for i in ratios_range:
RF_velocity, RF_vertvelocity = RF(
df, ratio_threshold=i, fq="24H", sampling_fq="1H"
)
missval.append(np.sum(np.isnan(RF_velocity)) / len(RF_velocity) * 100)
mv = np.float(np.sum(np.isnan(RF_velocity)) / len(RF_velocity) * 100)
if mv == 100:
t += 1
if t == 3:
print("FINISHED")
break
print("%d" % j, "/ %d" % len(ratios_range))
j += 1
# a rolling linear regression is used to better determine the elbow point
if np.int(len(ratios_range) / 10) % 2 == 0: # window size must be odd
regress = scipy.signal.savgol_filter(
missval, np.int(len(ratios_range) / 10) + 1, 1
)
else:
regress = scipy.signal.savgol_filter(
missval, np.int(len(ratios_range) / 10), 1
)
kn = KneeLocator(
ratios_range[: j + 1],
regress,
curve="convex",
direction="increasing",
)
optimal_rthreshold = kn.knee
print("KNEE:", optimal_rthreshold)
SDF_velocity, SDF_vertvelocity = RF(
df, ratio_threshold=optimal_rthreshold, fq="24H", sampling_fq="1H"
)
results = pd.DataFrame([SDF_velocity, SDF_vertvelocity])
# results visualisation
if representation:
plt.figure()
plt.subplot(211)
plt.plot(
ratios_range[: j + 1],
missval,
color="black",
label="",
alpha=0.5,
)
plt.plot(ratios_range[: j + 1], regress)
plt.xlabel("Global standard deviation threshold", fontsize=14)
plt.ylabel("Missing values percentage ($\%$)", fontsize=14)
plt.axvline(
optimal_rthreshold,
label="knee point: %.3f" % optimal_rthreshold,
)
plt.subplot(212)
plt.plot(
SDF_velocity.index,
SDF_velocity.iloc[:, 0],
color="black",
alpha=0.5,
)
plt.xlabel("Time (year-month)", fontsize=16)
plt.ylabel("Velocity (meters/day)", fontsize=16)
if save:
results.to_csv("RF_method.csv")
return results
def KMF(
df,
nbc_min=1,
nbc_max=10,
nb_cycles=5,
standardisation=False,
variables_importance=False,
representation=False,
projection="2D",
save=False,
):
"""The K-Means filtering (KMF) is a method that post-processes GNSS measurements
to obtain the resulting velocities. It is based on K-means automatic
clustering, a basic machine learning algorithm that divides a dataset
into k groups by determining the relations between the chosen variables.
It consists in six steps:
1) Computation of the Z-transformed minimum distances
2) Determination of the optimal number of clusters by the Elbow Method
3) K-Means algorithm run
4) Clusters filtering
5) Determination of the optimal number of cycles by the Elbow Method
6) Velocity determination
The variables are initially fixed to the one used in Adrien Wehrlé's work.
If standardisation=True, the variables are reduced and normalized.
If variables_importance=True, a quantification of the variables "usefulness" is led.
If representation=True, a scatter plot of the data with the clusters as colors is
represented in 2D (projection='2D') or in 3D (projection='3D').
If save=True, the resulted velocities are saved in a csv file.
"""
processing_start = time.clock()
initial_length = len(df)
def zscore(df):
"""
Computing the minimum distance (mindist) to the linear trend of the
station track for each value, then z-score transformed.
"""
def pos_filter_intermediate(df):
def linear_regression(df):
lr_results = linregress(df.X, df.Y)
y = df.X * lr_results.slope + lr_results.intercept
return y, lr_results
linear_regress, lr_results = linear_regression(df)
residuals = df.Y - linear_regress
mindist = np.abs(np.sin(lr_results.slope) * residuals)
return mindist
mindist = pos_filter_intermediate(df)
zscore = stats.zscore(mindist)
df["zsc_e"] = zscore
return df
def standardisation(KMF_data):
"""
Standardising the data: centers and reduces each variable.
"""
KMF_data = KMF_data.apply(lambda x: (x - x.mean()) / x.std())
return KMF_data
def elbow_point(data, mini=nbc_min, maxi=nbc_max):
"""
Determine the optimal number of clusters (optimal_nbclusters) with the
help of the Elbow Method. KMF algorithm is run with a range of number
of clusters (from nbc_min to nbc_max): when plotting the Sum of Squared
Error (SSE) as function of the number of clusters, the elbow of the curve
is the optimal one.
"""
if standardisation:
data = standardisation(data)
distortions = []
K = range(nbc_min, nbc_max)
for k in K:
kmeanModel = KMeans(n_clusters=k).fit(data)
kmeanModel.fit(data)
distortions.append(
sum(
np.min(
cdist(data, kmeanModel.cluster_centers_, "euclidean"), axis=1
)
)
/ data.shape[0]
)
print("K-means fit N° %d solved" % k)
kn = KneeLocator(K, distortions, curve="convex", direction="decreasing")
optimal_nbclusters = kn.knee
return optimal_nbclusters
def K_means(data, nbclusters):
"""
K-means algorithm
"""
if standardisation:
data = standardisation(data)
kmeans = KMeans(n_clusters=nbclusters)
kmeans.fit(data)
# algorithm outputs
centroids = kmeans.cluster_centers_
labels = kmeans.labels_
data["label"] = labels
data["X"] = df.X
data["Y"] = df.Y
return data, centroids, labels
def variables_importance(data_clustered):
"""
Quantification of the "usefulness" of each variables used for clustering
using ANOVA.
"We usually examine the means for each cluster on each dimension using
ANOVA to assess how distinct our clusters are. Ideally, we would obtain
significantly different means for most, if not all dimensions, used
in the analysis. The magnitude of the F values performed on each
dimension is an indication of how well the respective dimension
discriminates between clusters."
(BURNS, Robert P. et BURNS, Richard. Business research methods and statistics
using SPSS. Sage, 2008.)
"""
values = np.array(list(Counter(labels)))
fvalues = []
for i in range(0, len(data_clustered.columns)):
data = data_clustered.iloc[:, i]
f, p = stats.f_oneway(*[data[data_clustered.label == v] for v in values])
fvalues.append(f)
fvalues = np.array(fvalues)
plt.figure()
plt.semilogy(
np.arange(0, len(data_clustered.columns)),
fvalues,
alpha=0.2,
color="black",
LineStyle="--",
marker="o",
)
plt.xlabel("Variables", fontsize=16)
plt.ylabel("F-value ($\o$)", fontsize=16)
plt.title("Variables F-values based on ANOVA for each iteration", fontsize=16)
plt.xticks(np.arange(0, len(data_clustered.columns)), data_clustered.columns)
return fvalues
def filt_kclusters(data_clustered):
"""
Choose the right clusters. In the case of Adrien Wehrlé's work,
the bigger cluster contains all the values to delete (determined
after a manual work on the K-means results).
"""
counter_interm = Counter(data_clustered.label)
nb_counts = []
values = Counter(data_clustered.label)
values = np.array(list(values))
for i in range(0, len(counter_interm)):
nb_counts.append(counter_interm[i])
nb_counts = pd.DataFrame(nb_counts, columns=["nb_counts"])
values = pd.DataFrame(values, columns=["val"])
counter = pd.concat([values, nb_counts], axis=1)
maxi = np.max(counter.nb_counts)
rgroup = counter.val[counter.nb_counts == maxi].index
filtered_data = data_clustered[data_clustered.label != rgroup[0]]
return filtered_data
def velocity(data_filtered):
"""
Velocity determination from the clustered and filtered positions
"""
deltatime = np.diff(data_filtered.index)
deltatime = pd.DataFrame(deltatime)
deltatime_dec = deltatime.iloc[:, 0] / timedelta(days=1)
KMF_velocity = (
np.sqrt(np.diff(data_filtered.X) ** 2 + np.diff(data_filtered.Y) ** 2)
) / deltatime_dec
KMF_velocity = pd.DataFrame(KMF_velocity)
KMF_velocity.index = data_filtered.index[:-1]
return KMF_velocity