-
Notifications
You must be signed in to change notification settings - Fork 3
/
PROMICE_toolbox.py
1709 lines (1456 loc) · 66.3 KB
/
PROMICE_toolbox.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 -*-
"""
tip list:
%matplotlib inline
%matplotlib qt
import pdb; pdb.set_trace()
"""
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import math
import datetime
import pytz
import os
import warnings
import jaws_tools
import nead
warnings.filterwarnings("ignore", category=RuntimeWarning)
from sklearn.linear_model import LinearRegression
def field_info(fields):
tmp =pd.read_csv('L1/L1_variable_list.csv', skipinitialspace=True)
field_list = tmp.fields.tolist()
units = tmp.units.tolist()
display_description = tmp.display_description.tolist()
database_fields = tmp.database_fields.tolist()
database_fields_data_types = tmp.database_fields_data_types.tolist()
field_list = (
field_list
+ [s + "_qc" for s in field_list]
+ [s + "_adj_flag" for s in field_list]
)
units = units + ["-" for s in units] + ["-" for s in units]
display_description = (
display_description
+ [s + "_quality_flag" for s in display_description]
+ [s + "_adj_flag" for s in display_description]
)
database_fields = (
database_fields
+ [s + "_quality_flag" for s in database_fields]
+ [s + "_adj_flag" for s in database_fields]
)
database_fields_data_types = (
database_fields_data_types
+ ["int" for s in database_fields_data_types]
+ ["int" for s in database_fields_data_types]
)
ind = [field_list.index(s) for s in fields]
return (
[units[i] for i in ind],
[display_description[i] for i in ind],
[database_fields[i] for i in ind],
[database_fields_data_types[i] for i in ind],
)
def Msg(txt):
f = open("out/Report.md", "a")
print(txt)
f.write(txt + "\n")
def flag_data(df, site, var_list=["all"]):
"""
Replace data within a specified variable, between specified dates by NaN.
Reads from file "metadata/flags/<site>.csv".
INTPUTS:
df: PROMICE data with time index
site: string of PROMICE site
var_list: list of the variables for which data removal should be
conducted (default: all)
plot: whether data removal should be plotted
OUTPUTS:
promice_data: Dataframe containing PROMICE data for the desired settings [DataFrame]
"""
df_out = df.copy()
if not os.path.isfile("metadata/flags/" + site + ".csv"):
Msg("No erroneous data listed for " + site)
return df
flag_data = pd.read_csv("metadata/flags/" + site + ".csv",
comment="#",
skipinitialspace=True)
flag_data.t0 = pd.to_datetime(flag_data.t0, format='mixed', utc=True)
flag_data.t1 = pd.to_datetime(flag_data.t1, format='mixed', utc= True)
flag_data.loc[flag_data.t0.isnull(), "t0"] = df_out.index[0]
flag_data.loc[flag_data.t1.isnull(), "t1"] = df_out.index[-1]
if var_list[0] == "all":
var_list = np.unique(flag_data.variable)
Msg("Flagging data:")
Msg("|start time|end time|variable|")
Msg("|-|-|-|")
for ind in flag_data.index:
var = flag_data.loc[ind,'variable']
t0 = flag_data.loc[ind,'t0']
t1 = flag_data.loc[ind,'t1']
flag = flag_data.loc[ind,'flag']
if (var not in df_out.columns) & ('*' not in var) & ('$' not in var) & (' ' not in var):
Msg("Warning: " + var + " not found")
continue
if ('*' in var) |('$' in var):
var_list = df_out.filter(regex=(var)).columns
else:
var_list = var.split(' ')
for var in var_list:
if '_qc' in var: continue
Msg("|" + str(t0) + "|" + str(t1) + "|" + var + "|")
if var in df_out.columns.values:
if var + "_qc" in df_out.columns:
df_out.loc[t0:t1, var + "_qc"] = flag
else:
df_out[var + "_qc"] = "OK"
df_out.loc[t0:t1, var + "_qc"] = flag
return df_out
def plot_flagged_data(df1, df2, site, tag="", var_list=[]):
"""
Replace data within a specified variable, between specified dates by NaN.
Reads from file "metadata/flags/<site>.csv".
INTPUTS:
df: PROMICE data with time index
site: string of PROMICE site
var_list: list of the variables for which data removal should be
conducted (default: all)
plot: whether data removal should be plotted
OUTPUTS:
promice_data: Dataframe containing PROMICE data for the desired settings [DataFrame]
"""
Msg(" ")
df = df1.copy()
df_out = df2.copy()
if not os.path.isfile("metadata/adjustments/" + site + ".csv"):
Msg("No data to fix at " + site)
return []
adj_info = pd.read_csv("metadata/adjustments/" + site + ".csv",
comment="#", skipinitialspace=True)
adj_info.t0 = pd.to_datetime(adj_info.t0, format='mixed', utc=True)
adj_info.t1 = pd.to_datetime(adj_info.t1, format='mixed', utc= True)
adj_info.loc[adj_info.t0.isnull(), "t0"] = df_out.index[0]
adj_info.loc[adj_info.t1.isnull(), "t1"] = df_out.index[-1]
# if "*" is given as variable then we append this adjustement for all variables
for ind in adj_info.loc[adj_info.variable == "*", :].index:
line_template = adj_info.loc[[ind], :].copy()
for var in df_out.columns:
line_template.variable = var
line_template.index = [adj_info.index.max() + 1]
adj_info = pd.concat((adj_info, line_template))
adj_info = adj_info.drop(labels=ind, axis=0)
adj_info.set_index(["variable", "t0"], drop=False, inplace=True)
if len(var_list) == 0:
var_list = df.columns
if isinstance(var_list,str):
var_list = [var_list]
for var in var_list:
plot = False
if (df[var].isnull().all() | ("_qc" in var)
| ("_min" in var) | ("_max" in var)
| ("_std" in var) | ("_adj_flag" in var)
| ("_min" in var) ):
print('not plotting',var)
continue
if var in var_list: plot=True
if var+"_qc" in df.columns:
var_qc = var+"_qc"
df[var_qc].values[df[var_qc].isnull()] = "OK"
flags_uni = np.unique(df[var_qc].values.astype(str))
if len(flags_uni) > 1: plot=True
else:
if plot:
flags_uni = ["OK"]
var_qc = var+"_qc"
df[var_qc] = "OK"
if plot:
fig = plt.figure(figsize=(12, 8))
df_out[var].plot(style=".",color='gray', label="before adjustment or filtering")
for flag in flags_uni:
if flag == "OK":
df.loc[df[var_qc] == flag, var].plot(
marker="o", linestyle="none", color="green", label=flag
)
elif flag == "CHECKME":
df.loc[df[var_qc] == flag, var].plot(
marker="o", linestyle="none", color="orange", label=flag
)
elif flag == "NAN":
df.loc[df[var_qc] == flag, var].plot(
marker="o", linestyle="none", color="violet", label=flag
)
elif flag == "CONFIRMED":
df.loc[df[var_qc] == flag, var].plot(
marker="o", linestyle="none", color="tab:brown", label=flag
)
elif flag == "OOL":
df.loc[df[var_qc] == flag, var].plot(
marker="o", linestyle="none", color="red", label=flag
)
elif flag == "IWS":
df.loc[df[var_qc] == flag, var].plot(
marker="o", linestyle="none", color="cyan", label=flag
)
elif flag == "FROZEN":
df.loc[df[var_qc] == flag, var].plot(
marker="o", linestyle="none", color="blue", label=flag
)
elif flag == "FROZEN_WS":
df.loc[df[var_qc] == flag, var].plot(
marker="o", linestyle="none", color="lightblue", label=flag
)
else:
try:
df.loc[df[var_qc] == flag, var].plot(
marker="o", linestyle="none", label=flag
)
except:
Msg("Could not plot flag: ", flag)
if var in adj_info.index.get_level_values(0).unique():
[
plt.axvline(t, linestyle="--", color="red")
for t in adj_info.loc[var].t0.values
]
plt.axvline(np.nan, linestyle="--", color="red", label="Adjustment times")
plt.xlabel("Year")
plt.ylabel(var)
plt.legend()
plt.title(site)
fig.savefig("figures/L1_data_treatment/" + site.replace(" ", "")
+ "_" + var + ".jpeg",
dpi=120, bbox_inches="tight")
Msg("![Adjusted and flagged data at " + site
+ "](../figures/L1_data_treatment/" + site.replace(" ", "")
+ "_" + var + ".jpeg)")
Msg(" ")
def remove_flagged_data(df):
"""
Remove flagged data
"""
for var in df.columns:
if var[-3:] == "_qc":
df[var].values[df[var].isnull()] = "OK"
if len(np.unique(df[var].values)) > 1:
msk = (df[var].values == "OK") | (df[var].values == "")
df.loc[~msk, var[:-3]] = np.nan
df = df.drop(columns=[var])
return df
import pytz
def adjust_data(df, site, var_list=[], skip_var=[], skip_time_shifts=False):
df_out = df.copy()
if not os.path.isfile("metadata/adjustments/" + site + ".csv"):
Msg("No data to fix at " + site)
return df_out
adj_info = pd.read_csv(
"metadata/adjustments/" + site + ".csv",
comment="#", skipinitialspace=True
)
adj_info.t0 = pd.to_datetime(adj_info.t0, format='mixed', utc=True)
adj_info.t1 = pd.to_datetime(adj_info.t1, format='mixed', utc= True)
adj_info.loc[adj_info.t0.isnull(), "t0"] = df_out.index[0]
adj_info.loc[adj_info.t1.isnull(), "t1"] = df_out.index[-1]
# if "*" is given as variable then we append this adjustement for all variables
for ind in adj_info.loc[adj_info.variable == "*", :].index:
line_template = adj_info.loc[[ind], :].copy()
for var in df_out.columns:
line_template.variable = var
line_template.index = [adj_info.index.max() + 1]
adj_info = pd.concat((adj_info, line_template))
adj_info = adj_info.drop(labels=ind, axis=0)
adj_info = adj_info.sort_values(by=["variable", "t0"])
# putting sonic correction first
adj_info = pd.concat((adj_info.loc[adj_info.adjust_function.str.startswith('sonic_correction'),:],
adj_info.loc[~adj_info.adjust_function.str.startswith('sonic_correction'),:]))
# putting sensor swap first
adj_info = pd.concat((adj_info.loc[adj_info.adjust_function.str.startswith('swap'),:],
adj_info.loc[~adj_info.adjust_function.str.startswith('swap'),:]))
adj_info.loc[adj_info.adjust_function == "time_shift", :] = (
adj_info.loc[adj_info.adjust_function == "time_shift", :]
.sort_values(by="t0", ascending=False)
.values
)
if skip_time_shifts:
adj_info = adj_info.loc[adj_info.adjust_function != "time_shift", :]
adj_info.set_index(["variable", "t0"], drop=False, inplace=True)
if len(var_list) == 0:
var_list = np.unique(adj_info.variable)
else:
adj_info = adj_info.loc[np.isin(adj_info.variable, var_list), :]
var_list = np.unique(adj_info.variable)
if len(skip_var) > 0:
adj_info = adj_info.loc[~np.isin(adj_info.variable, skip_var), :]
var_list = np.unique(adj_info.variable)
Msg("|start time|end time|variable|operation|value|number of removed samples|")
Msg("|-|-|-|-|-|-|")
for var in var_list:
for t0, t1, func, val in zip(
adj_info.loc[var].t0,
adj_info.loc[var].t1,
adj_info.loc[var].adjust_function,
adj_info.loc[var].adjust_value,
):
if (pd.to_datetime(t0) > df.index[-1]) | (pd.to_datetime(t1) < df.index[0]):
continue
# counting nan values before filtering
if "_qc" not in var:
nan_count_1 = np.sum(np.isnan(df_out.loc[t0:t1, var].values))
if t1 < t0:
Msg("Dates in wrong order")
if func == "add":
df_out.loc[t0:t1, var] = df_out.loc[t0:t1, var].values + val
# flagging adjusted values
if var + "_adj_flag" not in df_out.columns:
df_out[var + "_adj_flag"] = 0
msk = df_out.loc[t0:t1, var].notnull()
ind = df_out.loc[t0:t1, var].loc[msk].index
df_out.loc[ind, var + "_adj_flag"] = 1
if func == "multiply":
df_out.loc[t0:t1, var] = df_out.loc[t0:t1, var].values * val
if "DW" in var:
df_out.loc[t0:t1, var] = df_out.loc[t0:t1, var] % 360
# flagging adjusted values
if var + "_adj_flag" not in df_out.columns:
df_out[var + "_adj_flag"] = 0
msk = df_out.loc[t0:t1, var].notnull()
ind = df_out.loc[t0:t1, var].loc[msk].index
df_out.loc[ind, var + "_adj_flag"] = 1
if func == "min_filter":
tmp = df_out.loc[t0:t1, var].values
tmp[tmp < val] = np.nan
if func == "max_filter":
tmp = df_out.loc[t0:t1, var].values
tmp[tmp > val] = np.nan
df_out.loc[t0:t1, var] = tmp
if func == "upper_perc_filter":
tmp = df_out.loc[t0:t1, var].copy()
df_w = df_out.loc[t0:t1, var].resample("14D").quantile(1 - val / 100)
df_w = df_out.loc[t0:t1, var].resample("14D").var()
for m_start, m_end in zip(df_w.index[:-2], df_w.index[1:]):
msk = (tmp.index >= m_start) & (tmp.index < m_end)
values_month = tmp.loc[msk].values
values_month[values_month < df_w.loc[m_start]] = np.nan
tmp.loc[msk] = values_month
df_out.loc[t0:t1, var] = tmp.values
if func == "biweekly_upper_range_filter":
tmp = df_out.loc[t0:t1, var].copy()
df_max = df_out.loc[t0:t1, var].resample("14D").max()
for m_start, m_end in zip(df_max.index[:-2], df_max.index[1:]):
msk = (tmp.index >= m_start) & (tmp.index < m_end)
lim = df_max.loc[m_start] - val
values_month = tmp.loc[msk].values
values_month[values_month < lim] = np.nan
tmp.loc[msk] = values_month
# remaining samples following outside of the last 2 weeks window
msk = tmp.index >= m_end
lim = df_max.loc[m_start] - val
values_month = tmp.loc[msk].values
values_month[values_month < lim] = np.nan
tmp.loc[msk] = values_month
# updating original pandas
df_out.loc[t0:t1, var] = tmp.values
if func == "hampel_filter":
tmp = df_out.loc[t0:t1, var]
tmp = hampel(tmp, k=7 * 24, t0=val)
df_out.loc[t0:t1, var] = tmp.values
if func == "grad_filter":
tmp = df_out.loc[t0:t1, var].copy()
msk = df_out.loc[t0:t1, var].copy().diff()
tmp[np.roll(msk.abs() > val, -1)] = np.nan
df_out.loc[t0:t1, var] = tmp
if "swap_with_" in func:
var2 = func[10:]
val_var = df_out.loc[t0:t1, var].values.copy()
val_var2 = df_out.loc[t0:t1, var2].values.copy()
df_out.loc[t0:t1, var2] = val_var
df_out.loc[t0:t1, var] = val_var2
if func == "rotate":
df_out.loc[t0:t1, var] = (df_out.loc[t0:t1, var].values + val) % 360
if func == "air_temp_sonic_correction":
# finding the available air temp measurements
if "TA" + var[-1] in df_out.columns:
tmp = df_out.loc[t0:t1, "TA" + var[-1]]
else:
tmp = df_out.loc[t0:t1, "TA1"]
TA_var = ["TA" + str(i) for i in range(1, 5) if "TA" + str(i) in df_out.columns]
tmp2 = df_out.loc[t0:t1, TA_var].mean(axis=1)
tmp.loc[tmp.isnull()] = tmp2.loc[tmp.isnull()]
tmp = tmp.interpolate(method="nearest", fill_value="extrapolate")
df_out.loc[t0:t1, var] = df_out.loc[t0:t1, var].values * np.sqrt(
(tmp.values + 273.15) / 273.15
)
if func == "air_temp_sonic_anticorrection":
# finding the available air temp measurements
if "TA" + var[-1] in df_out.columns:
tmp = df_out.loc[t0:t1, "TA" + var[-1]]
else:
tmp = df_out.loc[t0:t1, "TA1"]
TA_var = ["TA" + str(i) for i in range(1, 5) if "TA" + str(i) in df_out.columns]
tmp2 = df_out.loc[t0:t1, TA_var].mean(axis=1)
tmp.loc[tmp.isnull()] = tmp2.loc[tmp.isnull()]
tmp = tmp.interpolate(method="nearest", fill_value="extrapolate")
# plt.figure()
# df_out.loc[t0:t1, var].plot(ax=plt.gca(), label='original')
# (df_out.loc[t0:t1, var] * np.sqrt((tmp + 273.15) / 273.15)).plot(ax=plt.gca(), label='corrected')
df_out.loc[t0:t1, var] = df_out.loc[t0:t1, var].values / np.sqrt(
(tmp.values + 273.15) / 273.15
)
# df_out.loc[t0:t1, var].plot(ax=plt.gca(), label='anticorrected')
# plt.gca().legend()
if func == "ice_to_water":
tmp = df_out.loc[t0:t1, "TA" + var[-1]]
tmp2 = df_out.loc[t0:t1, "TA" + str(int(var[-1]) % 2 + 1)]
tmp.loc[tmp.isnull()] = tmp2.loc[tmp.isnull()].values
tmp = tmp.interpolate(method="nearest", fill_value="extrapolate")
df_out.loc[t0:t1, var] = RH_ice2water(
df_out.loc[t0:t1, var].values, tmp.values
)
if func == "water_to_ice":
tmp = df_out.loc[t0:t1, "TA" + var[-1]]
tmp2 = df_out.loc[t0:t1, "TA" + str(int(var[-1]) % 2 + 1)]
tmp.loc[tmp.isnull()] = tmp2.loc[tmp.isnull()].values
tmp = tmp.interpolate(method="nearest", fill_value="extrapolate")
df_out.loc[t0:t1, var] = RH_water2ice(
df_out.loc[t0:t1, var].values, tmp.values
)
if func == "time_shift":
t0 = pd.to_datetime(t0)
t1 = pd.to_datetime(t1)
if t1 + pd.Timedelta(hours=val) > df_out.index[-1]:
# case where the files needs to be extended to receive the shifted data
nb_new_rows = (
t1 + pd.Timedelta(hours=val) - df_out.index[-1]
).total_seconds() / 3600
df_new_rows = df_out.iloc[-int(nb_new_rows) :, :].copy()
df_new_rows.loc[:, :] = np.NaN
df_new_rows.index = df_new_rows.index + (
t1 + pd.Timedelta(hours=val) - df_out.index[-1]
)
df_out = pd.concat((df_out, df_new_rows))
df_out.loc[
t0 + pd.Timedelta(hours=val) : t1 + pd.Timedelta(hours=val), var
] = df_out.loc[t0:t1, var].values
if val > 0:
if val < 10000:
# errasing data that existed during the time shift
df_out.loc[t0 : t0 + pd.Timedelta(hours=val), var] = np.nan
else:
# case of Crawford Point where only the shifted data should be errased
df_out.loc[t0:t1, var] = np.nan
else:
df_out.loc[t1 + pd.Timedelta(hours=val) : t1, var] = np.nan
if (
("_qc" not in var) & ("_min" not in var) & ("_max" not in var)
& ("_std" not in var) & ("_adj_flag" not in var) & ("_min" not in var)
):
nan_count_2 = np.sum(np.isnan(df_out.loc[t0:t1, var].values))
Msg("|" + str(t0) + "|" + str(t1) + "|" + var +"|" + func
+ "|" + str(val) + "|" + str(nan_count_2 - nan_count_1) + "|"
)
return df_out
def correct_net_rad(df_in, site):
df_v5 = df_in.copy()
df_v5['NR_cor'] = np.nan
VW = df_v5[[v for v in ['VW1','VW2'] if v in df_v5.columns]].mean(axis=1)
C_pos = 1 + (0.066*0.2*VW)/(0.066+(0.2*VW))
C_neg = (0.00174*VW)+0.99755
C_pos.loc[C_pos.isnull()] = 1.045
C_neg.loc[C_neg.isnull()] = 1
if site in ['Summit','Swiss Camp']:
# At Summit and Swiss Camp:
# The NR Lite2 is sensitive to wind. A correction theoretically can be
# made by multiplying the calculated irradiances with a factor
# ( 1 + x • v**(3/4) ), where v is the windspeed in m/s, x is determined
# empirically to be approximately 0.01
df_v5.loc['2000-06-01':, 'NR_cor'] = df_v5.loc['2000-06-01':, 'NR'] * \
( 1 + 0.01 * VW.loc['2000-06-01':]**(3/4) )
tmp = df_v5.loc[:'2000-06-01', 'NR']
tmp.loc[tmp>0] = C_pos * tmp.loc[tmp>0]
tmp.loc[tmp<0] = C_neg * tmp.loc[tmp<0]
df_v5.loc[:'2000-06-01', 'NR_cor'] = tmp
else:
df_v5.loc[df_v5.NR>0, 'NR_cor'] = C_pos * df_v5.loc[df_v5.NR>0, 'NR']
df_v5.loc[df_v5.NR<0, 'NR_cor'] = C_neg * df_v5.loc[df_v5.NR<0, 'NR']
return df_v5
def fill_gap_HW(df1, df2, var_target="HW1", var_sec="HW2", note=''):
# Filling the gaps in HW1 with HW2
if var_target+'_org' not in df1.columns:
df1[var_target+'_org'] = ''
# Gap-filling HW using other sensor if available
prev_no_nan = df1[var_target].notnull().shift(1).fillna(False)
is_nan = df1[var_target].isnull()
list_start_gaps = df1.index[(prev_no_nan & is_nan)]
prev_nan = df1[var_target].isnull().shift(1).fillna(False)
no_nan = df1[var_target].notnull()
list_end_gaps = df1.index[(prev_nan & no_nan)]
list_start_gaps = list_start_gaps[list_start_gaps < df2.index[-1]]
list_start_gaps = list_start_gaps[list_start_gaps > df2.index[0]]
list_end_gaps = list_end_gaps[list_end_gaps < df2.index[-1]]
list_end_gaps = list_end_gaps[list_end_gaps > df2.index[0]]
if list_end_gaps[-1] < list_start_gaps[-1]:
list_end_gaps = np.append(list_end_gaps, min(df1.index[-1],df2.index[-1]))
if list_end_gaps[0] < list_start_gaps[0]:
list_start_gaps = np.append(max(df1.index[0],df2.index[0]), list_start_gaps)
for start, end in zip(list_start_gaps, list_end_gaps):
# we look at the month preceeding the gap
# calculate the mean difference between the two heights during that time
mean_diff = (
df1.loc[(start - pd.Timedelta(days=30)) : start, var_target]
- df2.loc[(start - pd.Timedelta(days=30)) : start, var_sec]
).mean()
if np.isnan(mean_diff):
mean_diff = df1.loc[:, var_target].mean() - df2.loc[:, var_sec].mean()
# and use that difference to adjust the secondary height to the height
# that is to be gap-filled
df1.loc[start:end, var_target] = (
df2.loc[start:end, var_sec].values + mean_diff
)
df1.loc[start:end, var_target+'_org'] = var_sec + note
return df1[var_target].values
def augment_data(df_in, latitude, longitude, elevation, site):
# Interpolate small gaps in available variables
# and add variables to the dataset:
# Surface height HS
# Sensible and Latent Heat Fluxes SHF & LHF
# Solar azimuth and zenith angles
# albedo
# for debug:
# df_in = df_v5.copy()
df = df_in.copy()
# Interpolation over gaps smaller than two days
for var in ['HW1','HW2']:
if var not in df.columns:
print(var, 'not in dataframe')
continue
if df[var].isnull().all():
print('No valid data for', var)
continue
# Creating surface height field
ind1 = df[var].first_valid_index()
var_HS = "HS"+var[-1]
df[var_HS] = df.loc[ind1, var] - df[var]
if site in ['SMS1', 'SMS2', 'SMS3', 'SMS4', 'SMS5', 'SMS-PET', 'Summit',
'NASA-SE','Tunu-N', 'EastGRIP', 'LAR1', 'JAR2', 'JAR1',
'Petermann ELA', 'NGRIP']:
thresh = 0.7
if site == 'Tunu-N':
thresh=0.173
if site == 'JAR1':
thresh=0.8
# plt.close('all')
fig, ax = plt.subplots(1,1)
df[var].bfill().plot(ax=ax,marker='.', linestyle='None', label=var+' backfilled')
df[var].plot(ax=ax,marker='.', linestyle='None', label=var)
diff = df[var].bfill().diff()
diff.plot(ax=ax,marker='o', linestyle='None', label='all shifts')
diff.loc[diff.abs()<thresh] = 0
if 'SMS' in site:
diff.loc[diff>0] = 0
for t in diff.loc[diff.abs()>thresh].index.values:
print(t)
# refining the diff value:
t = pd.to_datetime(t, utc=True)
one_week_before_gap = slice(t-pd.Timedelta(days=7), t)
one_week_after_gap = slice(t, t+pd.Timedelta(days=7))
if df.loc[one_week_after_gap, var].isnull().all() | df.loc[one_week_before_gap, var].isnull().all():
# average daily accumulation
if site == 'Tunu-N':
avg_accum = 0.000784
elif site == 'JAR1':
avg_accum = -.0043
elif site == 'NASA-SE':
avg_accum = 0.003
else:
tmp = df[var].resample('D').mean().diff()
avg_accum = -tmp.mean()
last_good_index = df.loc[:t, var].last_valid_index()
next_good_index = df.loc[t:, var].first_valid_index()
diff.loc[t] = df.loc[next_good_index, var] - df.loc[last_good_index, var] + avg_accum * (next_good_index-last_good_index).total_seconds()/3600/24
if (site =='JAR1'):
if (t.year == 2018):
diff.loc[t] = 0
if ((t.year==2012) & (t.month==7)):
diff.loc[t] = 0
else:
diff.loc[t] = df.loc[one_week_after_gap, var].median() - df.loc[one_week_before_gap, var].median()
if (diff.loc[t]!=0):
if t == diff.loc[diff.abs()>thresh].index.values[0]:
ax.axvline(t, linestyle='--', label='shift applied')
else:
ax.axvline(t, linestyle='--', label='_nolegend_')
df[var_HS] = df[var_HS] + diff.cumsum()
df[var_HS].plot(label=var_HS)
plt.legend()
fig.savefig("figures/L1_data_treatment/" + site + "_"+var_HS+"_adjust_auto.png")
x = df[var_HS].index.values.astype(float)/10**9/3600/24
y = df[var_HS].values
print(np.polyfit(x[~np.isnan(x+y)],
y[~np.isnan(x+y)], 1)[-2])
else:
# we then adjust and filter all surface height (could be replaced by an automated adjustment)
df_save=df.copy()
df = adjust_data(df, site, var_HS, skip_time_shifts=True)
print(var_HS)
plot_flagged_data(df, df_save, site, var_list=var_HS)
# HW1 gapfilled with HW2 and inversely
var_sec = var[:-1]+str(int(var[-1])%2 +1)
if var_sec in df.columns:
if df[var].notnull().any():
df[var+'_org'] = var
# df[var] = fill_gap_HW(df, df, var, var_sec)
df.loc[df[var]<0, var] = np.nan
# At swiss camp, using HW from tower to fill the gaps
if site == 'Swiss Camp 10m':
if var == 'HW1':
df_swc = nead.read("L1/hourly/SwissCamp.csv").to_dataframe().reset_index(drop=True)
df_swc['timestamp'] = pd.to_datetime(df_swc.timestamp)
df_swc = df_swc.set_index("timestamp").replace(-999, np.nan)
df[var] = fill_gap_HW(df, df_swc, var, "HW1", note= ' aws')
df[var] = fill_gap_HW(df, df_swc, var, "HW2", note= ' aws')
df.loc[df[var]<0, var] = np.nan
# HS summary:
if 'HS2' in df.columns:
df[['HS1','HS2']].plot()
tmp = df[ ["HS1", "HS2"]].copy()
tmp.HS2 = tmp.HS2- (tmp.HS2-tmp.HS1).mean()
df['HS_combined'] = tmp[["HS1", "HS2"]].mean(axis=1)
# plotting gap-filling process
fig,ax = plt.subplots(2,1, figsize=(15,8))
if 'HW1_org' in df.columns:
df.HW2.plot(ax=ax[0], marker='.',color='gray')
for src in df.HW1_org.unique():
df.HW1.loc[df.HW1_org == src].plot(ax=ax[0], label=src, marker="o", linestyle="None")
df = df.drop(columns=['HW1_org'])
ax[0].set_ylabel('HW1')
if 'HW2_org' in df.columns:
df.HW1.plot(ax=ax[1], marker='.',color='gray')
for src in df.HW2_org.unique():
df.HW2.loc[df.HW2_org == src].plot(ax=ax[1], label=src, marker="o", linestyle="None")
df = df.drop(columns=['HW2_org'])
ax[0].set_ylabel('HW1')
ax[0].legend()
ax[1].legend()
fig.savefig("figures/L1_data_treatment/" + site + "_gap_filling_HW.png")
if 'TA3' in df.columns:
# calculating SHF and LHF
df["SHF"], df["LHF"] = jaws_tools.gradient_fluxes(df.copy())
# interpolating variables at standard heights
df["TA2m"] = extrapolate_variable_standard_height(df,
var=["TA1", "TA2"],
target_height=2,
max_diff=5)
df["RH2m"] = extrapolate_variable_standard_height(df,
var=["RH1", "RH2"],
target_height=2,
max_diff=10)
df["VW10m"] = extrapolate_variable_standard_height(df,
var=["VW1", "VW2"],
target_height=10,
max_diff=10)
df.loc[df['TA2m']>20, 'TA2m'] = np.nan
df.loc[df['TA2m']<-80, 'TA2m'] = np.nan
df.loc[df['RH2m']>120, 'RH2m'] = np.nan
df.loc[df['RH2m']<20, 'RH2m'] = np.nan
df.loc[df['VW10m']>40, 'VW10m'] = np.nan
df.loc[df['VW10m']<0, 'VW10m'] = 0
# Solar zenith and azimuth angles
df["SZA"], df["SAA"] = sza_saa(df, longitude, latitude)
# Albedo
if 'OSWR' in df.columns:
df['Alb'] = calcAlbedo(df.OSWR, df.ISWR, df.SZA)
# Humidity with regard to ice and specific humidity
T1 = df.TA1.copy()
if 'TA3' in df.columns:
T1.loc[T1.isnull()] = df.loc[T1.isnull(), 'TA3']
T1.loc[T1.isnull()] = df.loc[T1.isnull(), 'TA2']
T1.loc[T1.isnull()] = df.loc[T1.isnull(), 'TA4']
df['RH1_cor'] = correctHumidity(df.RH1, T1)
if 'P' in df.columns:
df['Q1'] = calcHumid(T1, df.P, df.RH1_cor) *1000
df.loc[df['Q1']>40, 'Q1'] = np.nan
if 'RH2' in df.columns:
T2 = df.TA2.copy()
T2.loc[T2.isnull()] = df.loc[T2.isnull(), 'TA4']
T2.loc[T2.isnull()] = df.loc[T2.isnull(), 'TA1']
T2.loc[T2.isnull()] = df.loc[T2.isnull(), 'TA3']
df['RH2_cor'] = correctHumidity(df.RH2, T2)
df['Q2'] = calcHumid(T2, df.P, df.RH2_cor) *1000
df.loc[df['Q2']>40, 'Q2'] = np.nan
# adding latitude and longitude fields
try:
if os.path.isfile('metadata/interpolated positions/'+site.replace(' ','')+'_position_interpolated_with_elev.csv'):
df_pos = pd.read_csv( 'metadata/interpolated positions/'+site.replace(' ','')+'_position_interpolated_with_elev.csv')
elif os.path.isfile('metadata/interpolated positions/'+site.replace(' ','')+'_position_interpolated.csv'):
df_pos = pd.read_csv( 'metadata/interpolated positions/'+site.replace(' ','')+'_position_interpolated.csv')
elif os.path.isfile('metadata/interpolated positions/'+site.replace(' ','')+'_position_info.csv'):
df_pos = pd.read_csv( 'metadata/interpolated positions/'+site.replace(' ','')+'_position_info.csv')
df_pos['date'] = df_pos.time_elev_approximation.astype(str) + '-08-01'
df_pos['elev'] = df_pos.elev_approximation
df_pos['lat'] = latitude
df_pos['lon'] = longitude
df_pos.date = pd.to_datetime(df_pos.date, utc=True)
df_pos = df_pos.set_index('date')
df_pos_save = df_pos.copy()
offset = pd.DateOffset(months=7)
df_pos = df_pos.shift(freq=-offset).resample('YS').first().shift(freq=offset)
df['latitude'] =np.nan
df['longitude'] =np.nan
df['elevation'] =np.nan
df_pos = df_pos.resample('H').first().interpolate()
if (df_pos.index[-1] < df.index[-1]) | (df_pos.index[0] > df.index[0]):
df_pos = pd.concat((df.loc[df.index[0]:df_pos.index[0]-pd.to_timedelta('1H'), df.columns[0]],
df_pos,
df.loc[df_pos.index[-1]+pd.to_timedelta('1H'):df.index[-1],
df.columns[0]]))[df_pos.columns]
def extrapolate(df, y_col):
df_ = df[[y_col]].dropna()
return LinearRegression().fit(
df_.index.values.astype(float).reshape(-1,1), df_[y_col]).predict(
df.index.values.astype(float).reshape(-1,1))
for var in df_pos.columns:
df_pos[var+'_interp'] = extrapolate(df_pos,var)
if site != 'Swiss Camp':
df_pos[var] = df_pos[var].fillna(df_pos[var+'_interp'])
else:
df_pos[var] = df_pos[var].fillna(
df_pos.loc[df_pos[var].last_valid_index(),
var])
df['latitude'] = df_pos.loc[df.index,'lat']
df['longitude'] = df_pos.loc[df.index,'lon']
if 'elev' in df_pos.columns:
df['elevation'] = df_pos.loc[df.index,'elev']
fig, ax = plt.subplots(3,1,sharex=True)
df_pos_save.lat.plot(ax=ax[0], marker='o', ls='None')
df[['latitude']].plot(ax=ax[0])
df_pos_save.lon.plot(ax=ax[1], marker='o', ls='None')
df[['longitude']].plot(ax=ax[1])
if 'elev' in df_pos.columns:
df_pos_save.elev.plot(ax=ax[2], marker='o', ls='None')
df[['elevation']].plot(ax=ax[2])
fig.suptitle(site)
fig.savefig("figures/positions/" + site + "_positions.png", dpi=300)
except Exception as e:
print(e)
df['latitude'] = latitude
df['longitude'] = longitude
df['elevation'] = elevation
return df
from scipy.interpolate import interp1d
def interpolate_temperature(dates, depth_cor, temp, depth=10,
min_diff_to_depth=2, kind="quadratic", title="",
plot=True, surface_height=[]):
depth_cor = depth_cor.astype(float)
df_interp = pd.DataFrame()
df_interp["date"] = dates
df_interp["temperatureObserved"] = np.nan
# preprocessing temperatures for small gaps
tmp = pd.DataFrame(temp)
tmp["time"] = dates
tmp = tmp.set_index("time")
tmp = tmp.resample("H").mean()
# tmp = tmp.interpolate(limit=24*7)
temp = tmp.loc[dates].values
for i in (range(len(dates))):
x = depth_cor[i, :].astype(float)
y = temp[i, :].astype(float)
ind_no_nan = ~np.isnan(x + y)
x = x[ind_no_nan]
y = y[ind_no_nan]
x, indices = np.unique(x, return_index=True)
y = y[indices]
if len(x) < 2 or np.min(np.abs(x - depth)) > min_diff_to_depth:
continue
f = interp1d(x, y, kind, fill_value="extrapolate")
df_interp.iloc[i, 1] = np.min(f(depth), 0)
if df_interp.iloc[:5, 1].std() > 0.1:
df_interp.iloc[:5, 1] = np.nan
# df_interp['temperatureObserved'] = df_interp['temperatureObserved'].interpolate(limit=24*7).values
if plot:
import matplotlib.dates as mdates
myFmt = mdates.DateFormatter("%Y-%m")
for i in range(len(depth_cor[0, :]) - 1, 0, -1):
if all(np.isnan(depth_cor[:, i])):
continue
else:
break
if len(surface_height) == 0:
surface_height = (
depth_cor[:, i] - depth_cor[:, i][np.isfinite(depth_cor[:, i])][0]
)
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(17, 6))
plt.subplots_adjust(left=0.1, bottom=0.1, right=0.99, top=0.8)
ax1.plot(dates, surface_height, color="black", linewidth=3)
for i in range(np.shape(depth_cor)[1]):
ax1.plot(dates, -depth_cor[:, i] + surface_height)
ax1.plot(dates, surface_height - 10, color="red", linewidth=5)
ax1.set_ylim(
np.nanmin(surface_height) * 1.1 - 10, np.nanmax(surface_height) * 1.1
)
ax1.set_xlim(min(dates), max(dates))
ax1.set_ylabel("Height (m)")
ax1.xaxis.set_major_formatter(myFmt)
ax1.tick_params(axis="x", rotation=45)
for i in range(np.shape(depth_cor)[1]):
ax2.plot(dates, temp[:, i])
ax2.plot(
dates,
df_interp["temperatureObserved"],
marker="o",
markersize=5,
color="red",
linestyle=None,
)
ax2.set_ylabel("Firn temperature (degC)")
ax2.set_ylim(np.nanmin(temp) * 1.2, min(1, 0.8 * np.nanmax(temp)))
ax2.xaxis.set_major_formatter(myFmt)
ax2.tick_params(axis="x", rotation=45)
ax2.axes.grid()
ax2.set_xlim(min(dates), max(dates))
fig.suptitle(title) # or plt.suptitle('Main title')
im = plt.imread("figures/legend_1.png") # insert local path of the image.
newax = fig.add_axes([0.15, 0.8, 0.2, 0.2], anchor="NW", zorder=0)
newax.imshow(im)
newax.axes.xaxis.set_visible(False)
newax.axes.yaxis.set_visible(False)
fig.savefig("figures/string processing/interp_" + title + ".png", dpi=300)
return df_interp
def therm_depth(df_in, site,min_diff_to_depth=1.5,kind="linear"):
df_v6 = df_in.copy()
# downloading metadata from online google sheet
try:
url = (
"https://docs.google.com/spreadsheets/d/172LNxgYevqwO892zrc98UDMAVTQmJ0XZB5kmMLme4GM/gviz/tq?tqx=out:csv&sheet="
+ site.replace(" ", "%20")
)
pd.read_csv(url).to_csv("metadata/maintenance summary/" + site + ".csv")
except:
print("Cannot download maintenance summary. Using local file.")
pass
maintenance_string = pd.read_csv("metadata/maintenance summary/" + site + ".csv")
col_depth_installation = ['NewDepth1 (m)', 'NewDepth2 (m)', 'NewDepth3 (m)',
'NewDepth4 (m)', 'NewDepth5 (m)', 'NewDepth6 (m)',
'NewDepth7 (m)', 'NewDepth8 (m)', 'NewDepth9 (m)',
'NewDepth10 (m)']
if maintenance_string.shape[0] == 0:
print('No installtion depth reported, using default')
maintenance_string['date'] = [df_v6.index[0]]
maintenance_string[col_depth_installation] = [np.arange(1,11)]
maintenance_string.date = pd.to_datetime(maintenance_string.date,
format='mixed', utc=True)
maintenance_string = maintenance_string.set_index('date')
maintenance_string = maintenance_string[col_depth_installation]
msk = maintenance_string[col_depth_installation].notnull().all(axis=1)
maintenance_string = maintenance_string.loc[msk, :]
temp_cols_name = [v for v in df_v6.columns if 'TS' in v]
num_therm = len(temp_cols_name)
depth_cols_name = ['DTS'+str(i) for i in range(1,num_therm+1)]
df_v6[depth_cols_name] = np.nan
ini_depth = np.arange(1,11)
# filtering the surface height
surface_height = df_v6["HS_combined"].copy()
ind_filter = surface_height.rolling(window=14, center=True).var() > 0.1
if any(ind_filter):
surface_height[ind_filter] = np.nan
df_v6["HS_combined"] = surface_height.values
df_v6["HS_combined"] = df_v6["HS_combined"].interpolate().values
# first initialization of the depths