-
Notifications
You must be signed in to change notification settings - Fork 20
/
Utilities.py
1933 lines (1649 loc) · 78.6 KB
/
Utilities.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
from multiprocessing.sharedctypes import Value
import os
import datetime
import collections
import pytz
from collections import Counter
import csv
# from PyQt5.QtWidgets import QApplication, QDesktopWidget, QWidget, QPushButton, QMessageBox
from PyQt5.QtWidgets import QMessageBox
import matplotlib.pyplot as plt
from matplotlib.pyplot import cm
import numpy as np
import scipy.interpolate
from scipy.interpolate import splev, splrep
import scipy as sp
import pandas as pd
from pandas.plotting import register_matplotlib_converters
register_matplotlib_converters()
from tqdm import tqdm
from SB_support import readSB
import HDFRoot
from ConfigFile import ConfigFile
from MainConfig import MainConfig
# This gets reset later in Controller.processSingleLevel to reflect the file being processed.
if "LOGFILE" not in os.environ:
os.environ["LOGFILE"] = "temp.log"
class Utilities:
@staticmethod
def TSIS_1(dateTag, wavelength, F0_raw=None, wv_raw=None):
def dop(year):
# day of perihelion
years = list(range(2001,2031))
key = [str(x) for x in years]
day = [4, 2, 4, 4, 2, 4, 3, 2, 4, 3, 3, 5, 2, 4, 4, 2, 4, 3, 3, 5, 2, 4, 4, 3, 4, 3, 3, 5, 2, 3]
dop = {key[i]: day[i] for i in range(0, len(key))}
result = dop[str(year)]
return result
if F0_raw is None:
fp = 'Data/hybrid_reference_spectrum_p1nm_resolution_c2020-09-21_with_unc.nc'
# fp = 'Data/Thuillier_F0.sb'
# print("SB_support.readSB: " + fp)
print("Reading : " + fp)
if not HDFRoot.HDFRoot.readHDF5(fp):
msg = "Unable to read TSIS-1 netcdf file."
print(msg)
Utilities.writeLogFile(msg)
return None
else:
F0_hybrid = HDFRoot.HDFRoot.readHDF5(fp)
# F0_raw = np.array(Thuillier.data['esun']) # uW cm^-2 nm^-1
# wv_raw = np.array(Thuillier.data['wavelength'])
for ds in F0_hybrid.datasets:
if ds.id == 'SSI':
F0_raw = ds.data # W m^-2 nm^-1
F0_raw = F0_raw * 100 # uW cm^-2 nm^-1
if ds.id == 'Vacuum Wavelength':
wv_raw =ds.data
# Earth-Sun distance
day = int(str(dateTag)[4:7])
year = int(str(dateTag)[0:4])
eccentricity = 0.01672
dayFactor = 360/365.256363
dayOfPerihelion = dop(year)
dES = 1-eccentricity*np.cos(dayFactor*(day-dayOfPerihelion)) # in AU
F0_fs = F0_raw*dES
F0 = sp.interpolate.interp1d(wv_raw, F0_fs)(wavelength)
# Use the strings for the F0 dict
wavelengthStr = [str(wave) for wave in wavelength]
F0 = collections.OrderedDict(zip(wavelengthStr, F0))
return F0, F0_raw, wv_raw
@staticmethod
def Thuillier(dateTag, wavelength):
def dop(year):
# day of perihelion
years = list(range(2001,2031))
key = [str(x) for x in years]
day = [4, 2, 4, 4, 2, 4, 3, 2, 4, 3, 3, 5, 2, 4, 4, 2, 4, 3, 3, 5, 2, 4, 4, 3, 4, 3, 3, 5, 2, 3]
dop = {key[i]: day[i] for i in range(0, len(key))}
result = dop[str(year)]
return result
fp = 'Data/Thuillier_F0.sb'
print("SB_support.readSB: " + fp)
if not readSB(fp, no_warn=True):
msg = "Unable to read Thuillier file. Make sure it is in SeaBASS format."
print(msg)
Utilities.writeLogFile(msg)
return None
else:
Thuillier = readSB(fp, no_warn=True)
F0_raw = np.array(Thuillier.data['esun']) # uW cm^-2 nm^-1
wv_raw = np.array(Thuillier.data['wavelength'])
# Earth-Sun distance
day = int(str(dateTag)[4:7])
year = int(str(dateTag)[0:4])
eccentricity = 0.01672
dayFactor = 360/365.256363
dayOfPerihelion = dop(year)
dES = 1-eccentricity*np.cos(dayFactor*(day-dayOfPerihelion)) # in AU
F0_fs = F0_raw*dES
F0 = sp.interpolate.interp1d(wv_raw, F0_fs)(wavelength)
# Use the strings for the F0 dict
wavelengthStr = [str(wave) for wave in wavelength]
F0 = collections.OrderedDict(zip(wavelengthStr, F0))
return F0
@staticmethod
def mostFrequent(List):
occurence_count = Counter(List)
return occurence_count.most_common(1)[0][0]
@staticmethod
def find_nearest(array,value):
array = np.asarray(array)
idx = (np.abs(array - value)).argmin()
return idx
# ''' ONLY FOR SORTED ARRAYS'''
# idx = np.searchsorted(array, value, side="left")
# if idx > 0 and (idx == len(array) or math.fabs(value - array[idx-1]) < math.fabs(value - array[idx])):
# return array[idx-1]
# else:
# return array[idx]
@staticmethod
def errorWindow(winText,errorText):
msgBox = QMessageBox()
# msgBox.setIcon(QMessageBox.Information)
msgBox.setIcon(QMessageBox.Critical)
msgBox.setText(errorText)
msgBox.setWindowTitle(winText)
msgBox.setStandardButtons(QMessageBox.Ok)
msgBox.exec_()
@staticmethod
def waitWindow(winText,waitText):
msgBox = QMessageBox()
# msgBox.setIcon(QMessageBox.Information)
msgBox.setIcon(QMessageBox.Critical)
msgBox.setText(waitText)
msgBox.setWindowTitle(winText)
# msgBox.setStandardButtons(QMessageBox.Ok)
# msgBox.exec_()
return msgBox
@staticmethod
def YNWindow(winText,infoText):
msgBox = QMessageBox()
msgBox.setIcon(QMessageBox.Information)
msgBox.setText(infoText)
msgBox.setWindowTitle(winText)
msgBox.setStandardButtons(QMessageBox.Ok | QMessageBox.Cancel)
returnValue = msgBox.exec_()
return returnValue
@staticmethod
def writeLogFile(logText, mode='a'):
with open('Logs/' + os.environ["LOGFILE"], mode) as logFile:
logFile.write(logText + "\n")
# Converts degrees minutes to decimal degrees format
@staticmethod # for some reason, these were not set to static method, but didn't refer to self
def dmToDd(dm, direction):
d = int(dm/100)
m = dm-d*100
dd = d + m/60
if direction == b'W' or direction == b'S':
dd *= -1
return dd
# Converts decimal degrees to degrees minutes format
@staticmethod
def ddToDm(dd):
d = int(dd)
m = abs(dd - d)*60
dm = (d*100) + m
return dm
# Converts GPS UTC time (HHMMSS.ds; i.e. 99 ds after midnight is 000000.99)to seconds
# Note: Does not support multiple days
@staticmethod
def utcToSec(utc):
# Use zfill to ensure correct width, fixes bug when hour is 0 (12 am)
t = str(int(utc)).zfill(6)
# print(t)
#print(t[:2], t[2:4], t[4:])
h = int(t[:2])
m = int(t[2:4])
s = float(t[4:])
return ((h*60)+m)*60+s
# Converts datetime date and UTC (HHMMSS.ds) to datetime (uses microseconds)
@staticmethod
def utcToDateTime(dt, utc):
# Use zfill to ensure correct width, fixes bug when hour is 0 (12 am)
num, dec = str(float(utc)).split('.')
t = num.zfill(6)
h = int(t[:2])
m = int(t[2:4])
s = int(t[4:6])
us = 10000*int(dec) # i.e. 0.55 s = 550,000 us
return datetime.datetime(dt.year,dt.month,dt.day,h,m,s,us,tzinfo=datetime.timezone.utc)
# Converts datetag (YYYYDDD) to date string
@staticmethod
def dateTagToDate(dateTag):
dt = datetime.datetime.strptime(str(int(dateTag)), '%Y%j')
timezone = pytz.utc
dt = timezone.localize(dt)
return dt.strftime('%Y%m%d')
# Converts datetag (YYYYDDD) to datetime
@staticmethod
def dateTagToDateTime(dateTag):
dt = datetime.datetime.strptime(str(int(dateTag)), '%Y%j')
timezone = pytz.utc
dt = timezone.localize(dt)
return dt
# Converts seconds of the day (NOT GPS UTCPOS) to GPS UTC (HHMMSS.SS)
@staticmethod
def secToUtc(sec):
m, s = divmod(sec, 60)
h, m = divmod(m, 60)
return float("%d%02d%02d" % (h, m, s))
# Converts seconds of the day to TimeTag2 (HHMMSSmmm; i.e. 0.999 sec after midnight = 000000999)
@staticmethod
def secToTimeTag2(sec):
#return float(time.strftime("%H%M%S", time.gmtime(sec)))
t = sec * 1000
s, ms = divmod(t, 1000)
m, s = divmod(s, 60)
h, m = divmod(m, 60)
return int("%d%02d%02d%03d" % (h, m, s, ms))
# Converts TimeTag2 (HHMMSSmmm) to seconds
@staticmethod
def timeTag2ToSec(tt2):
t = str(int(tt2)).zfill(9)
h = int(t[:2])
m = int(t[2:4])
s = int(t[4:6])
ms = int(t[6:])
# print(h, m, s, ms)
return ((h*60)+m)*60+s+(float(ms)/1000.0)
# Converts datetime.date and TimeTag2 (HHMMSSmmm) to datetime
@staticmethod
def timeTag2ToDateTime(dt,tt2):
t = str(int(tt2)).zfill(9)
h = int(t[:2])
m = int(t[2:4])
s = int(t[4:6])
us = 1000*int(t[6:])
# print(h, m, s, us)
# print(tt2)
return datetime.datetime(dt.year,dt.month,dt.day,h,m,s,us,tzinfo=datetime.timezone.utc)
# Converts datetime to Timetag2 (HHMMSSmmm)
@staticmethod
def datetime2TimeTag2(dt):
h = dt.hour
m = dt.minute
s = dt.second
ms = dt.microsecond/1000
return int("%d%02d%02d%03d" % (h, m, s, ms))
# Converts datetime to Datetag
@staticmethod
def datetime2DateTag(dt):
y = dt.year
# mon = dt.month
day = dt.timetuple().tm_yday
return int("%d%03d" % (y, day))
# Converts HDFRoot timestamp attribute to seconds
@staticmethod
def timestampToSec(timestamp):
timei = timestamp.split(" ")[3]
t = timei.split(":")
h = int(t[0])
m = int(t[1])
s = int(t[2])
return ((h*60)+m)*60+s
# Convert GPRMC Date to Datetag
@staticmethod
def gpsDateToDatetime(year, gpsDate):
date = str(gpsDate).zfill(6)
day = int(date[:2])
mon = int(date[2:4])
return datetime.datetime(year,mon,day,0,0,0,0,tzinfo=datetime.timezone.utc)
# Add a dataset to each group for DATETIME, as defined by TIMETAG2 and DATETAG
# Also screens for nonsense timetags like 0.0 or NaN, and datetags that are not
# in the 20th or 21st centuries
@staticmethod
def rootAddDateTime(node):
for gp in node.groups:
# print(gp.id)
if gp.id != "SOLARTRACKER_STATUS": # No valid timestamps in STATUS
timeData = gp.getDataset("TIMETAG2").data["NONE"].tolist()
dateTag = gp.getDataset("DATETAG").data["NONE"].tolist()
timeStamp = []
for i, timei in enumerate(timeData):
# Converts from TT2 (hhmmssmss. UTC) and Datetag (YYYYDOY UTC) to datetime
# Filter for aberrant Datetags
t = str(int(timei)).zfill(9)
h = int(t[:2])
m = int(t[2:4])
s = int(t[4:6])
if (str(dateTag[i]).startswith("19") or str(dateTag[i]).startswith("20")) \
and timei != 0.0 and not np.isnan(timei) \
and h < 60 and m < 60 and s < 60:
dt = Utilities.dateTagToDateTime(dateTag[i])
timeStamp.append(Utilities.timeTag2ToDateTime(dt, timei))
else:
msg = f"Bad Datetag or Timetag2 found. Eliminating record. {i} DT: {dateTag[i]} TT2: {timei}"
print(msg)
Utilities.writeLogFile(msg)
gp.datasetDeleteRow(i)
dateTime = gp.addDataset("DATETIME")
dateTime.data = timeStamp
return node
# Add a data column to each group dataset for DATETIME, as defined by TIMETAG2 and DATETAG
# Also screens for nonsense timetags like 0.0 or NaN, and datetags that are not
# in the 20th or 21st centuries
@staticmethod
def rootAddDateTimeCol(node):
for gp in node.groups:
if gp.id != "SOLARTRACKER_STATUS": # No valid timestamps in STATUS
for ds in gp.datasets:
# Make sure all datasets have been transcribed to columns
gp.datasets[ds].datasetToColumns()
if not 'Datetime' in gp.datasets[ds].columns:
timeData = gp.datasets[ds].columns["Timetag2"]
dateTag = gp.datasets[ds].columns["Datetag"]
timeStamp = []
for i, timei in enumerate(timeData):
# Converts from TT2 (hhmmssmss. UTC) and Datetag (YYYYDOY UTC) to datetime
# Filter for aberrant Datetags
if (str(dateTag[i]).startswith("19") or str(dateTag[i]).startswith("20")) \
and timei != 0.0 and not np.isnan(timei):
dt = Utilities.dateTagToDateTime(dateTag[i])
timeStamp.append(Utilities.timeTag2ToDateTime(dt, timei))
else:
gp.datasetDeleteRow(i)
msg = f"Bad Datetag or Timetag2 found. Eliminating record. {i} DT: {dateTag[i]} TT2: {timei}"
print(msg)
Utilities.writeLogFile(msg)
gp.datasets[ds].columns["Datetime"] = timeStamp
gp.datasets[ds].columns.move_to_end('Datetime', last=False)
gp.datasets[ds].columnsToDataset()
return node
# Remove records if values of DATETIME are not strictly increasing
# (strictly increasing values required for interpolation)
@staticmethod
def fixDateTime(gp):
dateTime = gp.getDataset("DATETIME").data
# Test for strictly ascending values
# Not sensitive to UTC midnight (i.e. in datetime format)
total = len(dateTime)
globalTotal = total
if total >= 2:
# Check the first element prior to looping over rest
i = 0
if dateTime[i+1] <= dateTime[i]:
gp.datasetDeleteRow(i)
# del dateTime[i] # I'm fuzzy on why this is necessary; not a pointer?
dateTime = gp.getDataset("DATETIME").data
total = total - 1
msg = f'Out of order timestamp deleted at {i}'
print(msg)
Utilities.writeLogFile(msg)
#In case we went from 2 to 1 element on the first element,
if total == 1:
msg = f'************Too few records ({total}) to test for ascending timestamps. Exiting.'
print(msg)
Utilities.writeLogFile(msg)
return False
i = 1
while i < total:
if dateTime[i] <= dateTime[i-1]:
# BUG?:Same values of consecutive TT2s are shockingly common. Confirmed
# that 1) they exist from L1A, and 2) sensor data changes while TT2 stays the same
#
gp.datasetDeleteRow(i)
# del dateTime[i] # I'm fuzzy on why this is necessary; not a pointer?
dateTime = gp.getDataset("DATETIME").data
total = total - 1
msg = f'Out of order TIMETAG2 row deleted at {i}'
print(msg)
Utilities.writeLogFile(msg)
continue # goto while test skipping i incrementation. dateTime[i] is now the next value.
i += 1
else:
msg = f'************Too few records ({total}) to test for ascending timestamps. Exiting.'
print(msg)
Utilities.writeLogFile(msg)
return False
if (globalTotal - total) > 0:
msg = f'Data eliminated for non-increasing timestamps: {100*(globalTotal - total)/globalTotal:3.1f}%'
print(msg)
Utilities.writeLogFile(msg)
return True
# @staticmethod
# def epochSecToDateTagTimeTag2(eSec):
# dateTime = datetime.datetime.utcfromtimestamp(eSec)
# year = dateTime.timetuple()[0]
# return
# Checks if a string is a floating point number
@staticmethod
def isFloat(text):
try:
float(text)
return True
except ValueError:
return False
# Check if dataset contains NANs
@staticmethod
def hasNan(ds):
for k in ds.data.dtype.fields.keys():
for x in range(ds.data.shape[0]):
if k != 'Datetime':
if np.isnan(ds.data[k][x]):
return True
# else:
# if np.isnan(ds.data[k][x]):
# return True
return False
# Check if the list contains strictly increasing values
@staticmethod
def isIncreasing(l):
return all(x<y for x, y in zip(l, l[1:]))
@staticmethod
def windowAverage(data,window_size):
min_periods = round(window_size/2)
df=pd.DataFrame(data)
out=df.rolling(window_size,min_periods,center=True,win_type='boxcar')
# out = [item for items in out for item in items] #flattening doesn't work
return out
@staticmethod
def movingAverage(data, window_size):
# Window size will be determined experimentally by examining the dark and light data from each instrument.
""" Noise detection using a low-pass filter.
https://www.datascience.com/blog/python-anomaly-detection
Computes moving average using discrete linear convolution of two one dimensional sequences.
Args:
-----
data (pandas.Series): independent variable
window_size (int): rolling window size
Returns:
--------
ndarray of linear convolution
References:
------------
[1] Wikipedia, "Convolution", http://en.wikipedia.org/wiki/Convolution.
[2] API Reference: https://docs.scipy.org/doc/numpy/reference/generated/numpy.convolve.html
[3] ABE, N., Zadrozny, B., and Langford, J. 2006. Outlier detection by active learning.
In Proceedings of the 12th ACM SIGKDD International Conference on Knowledge Discovery and
Data Mining. ACM Press, New York, 504–509
[4] V Chandola, A Banerjee and V Kumar 2009. Anomaly Detection: A Survey Article No. 15 in ACM
Computing Surveys"""
# window = np.ones(int(window_size))/float(window_size)
# Convolve is not nan-tolerant, so use a mask
data = np.array(data)
mask = np.isnan(data)
K = np.ones(window_size, dtype=int)
denom = np.convolve(~mask,K)
denom = np.where(denom != 0, denom, 1) # replace the 0s with 1s to block div0 error; the numerator will be zero anyway
out = np.convolve(np.where(mask,0,data), K)/denom
# return np.convolve(data, window, 'same')
# Slice out one half window on either side; this requires an odd-sized window
return out[int(np.floor(window_size/2)):-int(np.floor(window_size/2))]
@staticmethod
def darkConvolution(data,avg,std,sigma):
badIndex = []
for i in range(len(data)):
if i < 1 or i > len(data)-2:
# First and last avg values from convolution are not to be trusted
badIndex.append(True)
elif np.isnan(data[i]):
badIndex.append(False)
else:
# Use stationary standard deviation anomaly (from rolling average) detection for dark data
if (data[i] > avg[i] + (sigma*std)) or (data[i] < avg[i] - (sigma*std)):
badIndex.append(True)
else:
badIndex.append(False)
return badIndex
@staticmethod
def lightConvolution(data,avg,rolling_std,sigma):
badIndex = []
for i in range(len(data)):
if i < 1 or i > len(data)-2:
# First and last avg values from convolution are not to be trusted
badIndex.append(True)
elif np.isnan(data[i]):
badIndex.append(False)
else:
# Use rolling standard deviation anomaly (from rolling average) detection for dark data
if (data[i] > avg[i] + (sigma*rolling_std[i])) or (data[i] < avg[i] - (sigma*rolling_std[i])):
badIndex.append(True)
else:
badIndex.append(False)
return badIndex
@staticmethod
def deglitchThresholds(band,data,minRad,maxRad,minMaxBand):
badIndex = []
for i in range(len(data)):
badIndex.append(False)
# ConfigFile setting updated directly from the checkbox in AnomDetection.
# This insures values of badIndex are false if unthresholded or Min or Max are None
if ConfigFile.settings["bL1aqcThreshold"]:
# Only run on the pre-selected waveband
if band == minMaxBand:
if minRad or minRad==0: # beware falsy zeros...
if data[i] < minRad:
badIndex[-1] = True
if maxRad or maxRad==0:
if data[i] > maxRad:
badIndex[-1] = True
return badIndex
@staticmethod
def interp(x, y, new_x, kind='linear', fill_value=0.0):
''' Wrapper for scipy interp1d that works even if
values in new_x are outside the range of values in x'''
''' NOTE: This will fill missing values at the beginning and end of data record with
the nearest actual record. This is fine for integrated datasets, but may be dramatic
for some gappy ancillary records of lower temporal resolution.'''
# If the last value to interp to is larger than the last value interp'ed from,
# then append that higher value onto the values to interp from
n0 = len(x)-1
n1 = len(new_x)-1
if new_x[n1] > x[n0]:
#print(new_x[n], x[n])
# msg = '********** Warning: extrapolating to beyond end of data record ********'
# print(msg)
# Utilities.writeLogFile(msg)
x.append(new_x[n1])
y.append(y[n0])
# If the first value to interp to is less than the first value interp'd from,
# then add that lesser value to the beginning of values to interp from
if new_x[0] < x[0]:
#print(new_x[0], x[0])
# msg = '********** Warning: extrapolating to before beginning of data record ******'
# print(msg)
# Utilities.writeLogFile(msg)
x.insert(0, new_x[0])
y.insert(0, y[0])
new_y = scipy.interpolate.interp1d(x, y, kind=kind, bounds_error=False, fill_value=fill_value)(new_x)
return new_y
@staticmethod
def interpAngular(x, y, new_x, fill_value="extrapolate"):
''' Wrapper for scipy interp1d that works even if
values in new_x are outside the range of values in x'''
''' NOTE: Except for SOLAR_AZ and SZA, which are extrapolated, this will fill missing values at the
beginning and end of data record with the nearest actual record. This is fine for integrated
datasets, but may be dramatic for some gappy ancillary records of lower temporal resolution.'''
# Eliminate NaNs
whrNan = np.where(np.isnan(y))[0]
y = np.delete(y,whrNan).tolist()
x = np.delete(x,whrNan).tolist()
# Test for all NaNs
if y:
if fill_value != "extrapolate": # Only extrapolate SOLAR_AZ and SZA, otherwise keep fill values constant
# Some angular measurements (like SAS pointing) are + and -. Convert to all +
for i, value in enumerate(y):
if value < 0:
y[i] = 360 + value
# If the last value to interp to is larger than the last value interp'ed from,
# then append that higher value onto the values to interp from
n0 = len(x)-1
n1 = len(new_x)-1
if new_x[n1] > x[n0]:
#print(new_x[n], x[n])
# msg = '********** Warning: extrapolating to beyond end of data record ********'
# print(msg)
# Utilities.writeLogFile(msg)
x.append(new_x[n1])
y.append(y[n0])
# If the first value to interp to is less than the first value interp'd from,
# then add that lesser value to the beginning of values to interp from
if new_x[0] < x[0]:
#print(new_x[0], x[0])
# msg = '********** Warning: extrapolating to before beginning of data record ******'
# print(msg)
# Utilities.writeLogFile(msg)
x.insert(0, new_x[0])
y.insert(0, y[0])
y_rad = np.deg2rad(y)
# f = scipy.interpolate.interp1d(x,y_rad,kind='linear', bounds_error=False, fill_value=None)
f = scipy.interpolate.interp1d(x,y_rad,kind='linear', bounds_error=False, fill_value=fill_value)
new_y_rad = f(new_x)%(2*np.pi)
new_y = np.rad2deg(new_y_rad)
else:
# All y values were NaNs. Fill in NaNs in new_y
new_y = np.empty((len(new_x)))
new_y.fill(np.nan)
new_y = new_y.tolist()
return new_y
# Cubic spline interpolation intended to get around the all NaN output from InterpolateUnivariateSpline
# x is original time to be splined, y is the data to be interpolated, new_x is the time to interpolate/spline to
# interpolate.splrep is intolerant of duplicate or non-ascending inputs, and inputs with fewer than 3 points
@staticmethod
def interpSpline(x, y, new_x):
spl = splrep(x, y)
new_y = splev(new_x, spl)
for i in range(len(new_y)):
if np.isnan(new_y[i]):
print("NaN")
return new_y
@staticmethod
def interpFill(x, y, newXList, fillValue=np.nan):
''' Used where fill is needed instead of interpolation, e.g., STATIONS in L1B.'''
y = np.array(y)
x = np.array(x)
whrNan = np.where(np.isnan(y))[0]
y = np.delete(y,whrNan)
x = np.delete(x,whrNan)
yUnique = np.unique(y) #.tolist()
newYList = []
# Populate with nans first, then replace to guarantee value regardless of any or multiple matches
for newX in newXList:
newYList.append(fillValue)
for value in yUnique:
minX = min(x[y==value])
maxX = max(x[y==value])
for i, newX in enumerate(newXList):
if (newX >= minX) and (newX <= maxX):
newYList[i] = value
return newYList
@staticmethod
def filterData(group, badTimes, sensor = None):
''' Delete flagged records. Sensor is only specified to get the timestamp.
All data in the group (including satellite sensors) will be deleted.
Called by both ProcessL1bqc.'''
msg = f'Remove {group.id} Data'
print(msg)
Utilities.writeLogFile(msg)
if sensor == None:
if group.id == "ANCILLARY":
timeStamp = group.getDataset("LATITUDE").data["Datetime"]
if group.id == "IRRADIANCE":
timeStamp = group.getDataset("ES").data["Datetime"]
if group.id == "RADIANCE":
timeStamp = group.getDataset("LI").data["Datetime"]
else:
if group.id == "IRRADIANCE":
timeStamp = group.getDataset(f"ES_{sensor}").data["Datetime"]
if group.id == "RADIANCE":
timeStamp = group.getDataset(f"LI_{sensor}").data["Datetime"]
if group.id == "REFLECTANCE":
timeStamp = group.getDataset(f"Rrs_{sensor}").data["Datetime"]
startLength = len(timeStamp)
msg = f' Length of dataset prior to removal {startLength} long'
print(msg)
Utilities.writeLogFile(msg)
# Delete the records in badTime ranges from each dataset in the group
finalCount = 0
originalLength = len(timeStamp)
for dateTime in badTimes:
# Need to reinitialize for each loop
startLength = len(timeStamp)
newTimeStamp = []
# msg = f'Eliminate data between: {dateTime}'
# print(msg)
# Utilities.writeLogFile(msg)
start = dateTime[0]
stop = dateTime[1]
if startLength > 0:
counter = 0
for i in range(startLength):
if start <= timeStamp[i] and stop >= timeStamp[i]:
try:
group.datasetDeleteRow(i - counter) # Adjusts the index for the shrinking arrays
counter += 1
finalCount += 1
except:
print('error')
else:
newTimeStamp.append(timeStamp[i])
else:
msg = 'Data group is empty. Continuing.'
print(msg)
Utilities.writeLogFile(msg)
break
timeStamp = newTimeStamp.copy()
# if badTimes == []:
# startLength = 1 # avoids div by zero below when finalCount is 0
for ds in group.datasets:
# if ds != "STATION":
# try:
group.datasets[ds].datasetToColumns()
# except:
# print('sheeeeit')
msg = f' Length of dataset after removal {originalLength-finalCount} long: {round(100*finalCount/originalLength)}% removed'
print(msg)
Utilities.writeLogFile(msg)
return finalCount/originalLength
@staticmethod
def plotRadiometry(root, filename, rType, plotDelta = False):
dirPath = os.getcwd()
outDir = MainConfig.settings["outDir"]
# If default output path (HyperInSPACE/Data) is used, choose the root HyperInSPACE path,
# and build on that (HyperInSPACE/Plots/etc...)
if os.path.abspath(outDir) == os.path.join(dirPath,'Data'):
outDir = dirPath
# Otherwise, put Plots in the chosen output directory from Main
plotDir = os.path.join(outDir,'Plots','L2')
if not os.path.exists(plotDir):
os.makedirs(plotDir)
dataDelta = None
''' Note: If only one spectrum is left in a given ensemble, deltas will
be zero for Es, Li, and Lt.'''
if rType=='Rrs':
print('Plotting Rrs')
group = root.getGroup("REFLECTANCE")
Data = group.getDataset(f'{rType}_HYPER')
if plotDelta:
dataDelta = group.getDataset(f'{rType}_HYPER_unc')
plotRange = [340, 800]
if ConfigFile.settings['bL2WeightMODISA']:
Data_MODISA = group.getDataset(f'{rType}_MODISA')
if plotDelta:
dataDelta_MODISA = group.getDataset(f'{rType}_MODISA_unc')
if ConfigFile.settings['bL2WeightMODIST']:
Data_MODIST = group.getDataset(f'{rType}_MODIST')
if plotDelta:
dataDelta_MODIST = group.getDataset(f'{rType}_MODIST_unc')
if ConfigFile.settings['bL2WeightVIIRSN']:
Data_VIIRSN = group.getDataset(f'{rType}_VIIRSN')
if plotDelta:
dataDelta_VIIRSN = group.getDataset(f'{rType}_VIIRSN_unc')
if ConfigFile.settings['bL2WeightVIIRSJ']:
Data_VIIRSJ = group.getDataset(f'{rType}_VIIRSJ')
if plotDelta:
dataDelta_VIIRSJ = group.getDataset(f'{rType}_VIIRSJ_unc')
if ConfigFile.settings['bL2WeightSentinel3A']:
Data_Sentinel3A = group.getDataset(f'{rType}_Sentinel3A')
if plotDelta:
dataDelta_Sentinel3A = group.getDataset(f'{rType}_Sentinel3A_unc')
if ConfigFile.settings['bL2WeightSentinel3B']:
Data_Sentinel3B = group.getDataset(f'{rType}_Sentinel3B')
if plotDelta:
dataDelta_Sentinel3B = group.getDataset(f'{rType}_Sentinel3B_unc')
if rType=='nLw':
print('Plotting nLw')
group = root.getGroup("REFLECTANCE")
Data = group.getDataset(f'{rType}_HYPER')
if plotDelta:
dataDelta = group.getDataset(f'{rType}_HYPER_unc')
plotRange = [340, 800]
if ConfigFile.settings['bL2WeightMODISA']:
Data_MODISA = group.getDataset(f'{rType}_MODISA')
if plotDelta:
dataDelta_MODISA = group.getDataset(f'{rType}_MODISA_unc')
if ConfigFile.settings['bL2WeightMODIST']:
Data_MODIST = group.getDataset(f'{rType}_MODIST')
if plotDelta:
dataDelta_MODIST = group.getDataset(f'{rType}_MODIST_unc')
if ConfigFile.settings['bL2WeightVIIRSN']:
Data_VIIRSN = group.getDataset(f'{rType}_VIIRSN')
if plotDelta:
dataDelta_VIIRSN = group.getDataset(f'{rType}_VIIRSN_unc')
if ConfigFile.settings['bL2WeightVIIRSJ']:
Data_VIIRSJ = group.getDataset(f'{rType}_VIIRSJ')
if plotDelta:
dataDelta_VIIRSJ = group.getDataset(f'{rType}_VIIRSJ_unc')
if ConfigFile.settings['bL2WeightSentinel3A']:
Data_Sentinel3A = group.getDataset(f'{rType}_Sentinel3A')
if plotDelta:
dataDelta_Sentinel3A = group.getDataset(f'{rType}_Sentinel3A_unc')
if ConfigFile.settings['bL2WeightSentinel3B']:
Data_Sentinel3B = group.getDataset(f'{rType}_Sentinel3B')
if plotDelta:
dataDelta_Sentinel3B = group.getDataset(f'{rType}_Sentinel3B_unc')
''' Could include satellite convolved (ir)radiances in the future '''
if rType=='ES':
print('Plotting Es')
group = root.getGroup("IRRADIANCE")
Data = group.getDataset(f'{rType}_HYPER')
if plotDelta:
dataDelta = group.getDataset(f'{rType}_HYPER_sd')
plotRange = [305, 1140]
if rType=='LI':
print('Plotting Li')
group = root.getGroup("RADIANCE")
Data = group.getDataset(f'{rType}_HYPER')
if plotDelta:
dataDelta = group.getDataset(f'{rType}_HYPER_sd')
plotRange = [305, 1140]
if rType=='LT':
print('Plotting Lt')
group = root.getGroup("RADIANCE")
Data = group.getDataset(f'{rType}_HYPER')
lwData = group.getDataset(f'LW_HYPER')
if plotDelta:
dataDelta = group.getDataset(f'{rType}_HYPER_sd')
# lwDataDelta = group.getDataset(f'LW_HYPER_sd')
plotRange = [305, 1140]
font = {'family': 'serif',
'color': 'darkred',
'weight': 'normal',
'size': 16,
}
# Hyperspectral
x = []
xLw = []
wave = []
subwave = [] # accomodates Zhang, which deletes out-of-bounds wavebands
# For each waveband
for k in Data.data.dtype.names:
if Utilities.isFloat(k):
if float(k)>=plotRange[0] and float(k)<=plotRange[1]: # also crops off date and time
x.append(k)
wave.append(float(k))
# Add Lw to Lt plots
if rType=='LT':
for k in lwData.data.dtype.names:
if Utilities.isFloat(k):
if float(k)>=plotRange[0] and float(k)<=plotRange[1]: # also crops off date and time
xLw.append(k)
subwave.append(float(k))
# Satellite Bands
x_MODISA = []
wave_MODISA = []
if ConfigFile.settings['bL2WeightMODISA'] and (rType == 'Rrs' or rType == 'nLw'):
for k in Data_MODISA.data.dtype.names:
if Utilities.isFloat(k):
if float(k)>=plotRange[0] and float(k)<=plotRange[1]: # also crops off date and time
x_MODISA.append(k)
wave_MODISA.append(float(k))
x_MODIST = []
wave_MODIST = []
if ConfigFile.settings['bL2WeightMODIST'] and (rType == 'Rrs' or rType == 'nLw'):
for k in Data_MODIST.data.dtype.names:
if Utilities.isFloat(k):
if float(k)>=plotRange[0] and float(k)<=plotRange[1]: # also crops off date and time
x_MODIST.append(k)
wave_MODIST.append(float(k))
x_VIIRSN = []
wave_VIIRSN = []
if ConfigFile.settings['bL2WeightVIIRSN'] and (rType == 'Rrs' or rType == 'nLw'):
for k in Data_VIIRSN.data.dtype.names:
if Utilities.isFloat(k):
if float(k)>=plotRange[0] and float(k)<=plotRange[1]: # also crops off date and time
x_VIIRSN.append(k)
wave_VIIRSN.append(float(k))
x_VIIRSJ = []
wave_VIIRSJ = []
if ConfigFile.settings['bL2WeightVIIRSJ'] and (rType == 'Rrs' or rType == 'nLw'):
for k in Data_VIIRSJ.data.dtype.names:
if Utilities.isFloat(k):
if float(k)>=plotRange[0] and float(k)<=plotRange[1]: # also crops off date and time
x_VIIRSJ.append(k)
wave_VIIRSJ.append(float(k))
x_Sentinel3A = []
wave_Sentinel3A = []
if ConfigFile.settings['bL2WeightSentinel3A'] and (rType == 'Rrs' or rType == 'nLw'):
for k in Data_Sentinel3A.data.dtype.names:
if Utilities.isFloat(k):
if float(k)>=plotRange[0] and float(k)<=plotRange[1]: # also crops off date and time
x_Sentinel3A.append(k)
wave_Sentinel3A.append(float(k))
x_Sentinel3B = []
wave_Sentinel3B = []
if ConfigFile.settings['bL2WeightSentinel3B'] and (rType == 'Rrs' or rType == 'nLw'):
for k in Data_Sentinel3B.data.dtype.names:
if Utilities.isFloat(k):
if float(k)>=plotRange[0] and float(k)<=plotRange[1]: # also crops off date and time
x_Sentinel3B.append(k)
wave_Sentinel3B.append(float(k))
total = Data.data.shape[0]
maxRad = 0
minRad = 0
cmap = cm.get_cmap("jet")
color=iter(cmap(np.linspace(0,1,total)))
plt.figure(1, figsize=(8,6))
for i in range(total):
# Hyperspectral
y = []
dy = []
for k in x:
y.append(Data.data[k][i])
if plotDelta:
dy.append(dataDelta.data[k][i])
# Add Lw to Lt plots
if rType=='LT':
yLw = []
# dyLw = []
for k in xLw:
yLw.append(lwData.data[k][i])