-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathqc.py
1852 lines (1498 loc) · 57 KB
/
qc.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
"""
The QC module contains a set of functions for performing the basic QC
checks on marine reports as well as some generally helpful functions
for identifying which grid box or pentad an observations falls in
"""
import numpy as np
import math
from datetime import datetime
from datetime import timedelta
import calendar
def month_match(y1, m1, y2, m2):
if y1 == y2 and m1 == m2:
return 1
else:
return 0
def yesterday(year, month, day):
"""'
For specified year month and day return the year month and day of the day before.
:param year: year
:param month: month
:param day: day
:type year: integer
:type month: integer
:type day: integer
:return: tuple of year, month and day, returns None if the input day does not exist (e.g. Feb 30th)
:rtype: integer
"""
try:
dt = datetime(year, month, day)
delta = timedelta(-1)
dt = dt + delta
return dt.year, dt.month, dt.day
except:
return None, None, None
def season(month):
"""
Return short season name for given month, None for months like 13 that do not exist
:param month: month
:type month: integer
:return: DJF, MAM, JJA, or SON or None if the input month is non-existent (e.g. 13)
:rtype: string
"""
if month < 0 or month > 12:
return None
ssnlist = ['DJF', 'DJF',
'MAM', 'MAM', 'MAM',
'JJA', 'JJA', 'JJA',
'SON', 'SON', 'SON',
'DJF']
return ssnlist[month - 1]
def pentad_to_month_day(p):
"""
Given a pentad number, return the month and day of the first day in the pentad
:param p: pentad number from 1 to 73
:type p: integer
:return: month and day of the first day of the pentad
:rtype: integer
"""
assert 0 < p < 74, 'p outside allowed range 1-73 ' + str(p)
m = [1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2,
3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4,
5, 5, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6,
7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8,
9, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10,
11, 11, 11, 11, 11, 11, 12, 12, 12, 12, 12, 12]
d = [1, 6, 11, 16, 21, 26, 31, 5, 10, 15, 20, 25, 2, 7, 12, 17, 22,
27, 1, 6, 11, 16, 21, 26, 1, 6, 11, 16, 21, 26, 31, 5, 10, 15, 20,
25, 30, 5, 10, 15, 20, 25, 30, 4, 9, 14, 19, 24, 29, 3, 8, 13, 18,
23, 28, 3, 8, 13, 18, 23, 28, 2, 7, 12, 17, 22, 27, 2, 7, 12, 17, 22, 27]
return m[p - 1], d[p - 1]
def which_pentad(inmonth, inday):
"""
take month and day as inputs and return pentad in range 1-73.
:param inmonth: month containing the day for which we want to calculate the pentad
:param inday: day for the day for which we want to calculate the pentad
:type inmonth: integer
:type inday: integer
:return: pentad (5-day period) containing input day, from 1 (1 Jan-5 Jan) to 73 (27-31 Dec)
:rtype: integer
The calculation is rather simple. It just loops through the year and adds up days till it reaches
the day we are interested in. February 29th is treated as though it were March 1st in a regular year.
"""
assert 12 >= inmonth >= 1
assert 31 >= inday >= 1
pentad = (day_in_year(inmonth, inday) - 1) / 5
pentad = pentad + 1
assert pentad >= 1
assert pentad <= 73
return pentad
def day_in_year(month, day):
"""
Find the day number of a particular day from Jan 1st which is 1
to Dec 31st which is 365.
:param month: month to be processed
:param day: day in the month
:type month: integer
:type day: integer
:return: day number in year 1-365
:rtype: integer
"""
assert month >= 1
assert month <= 12, str(month)
month_lengths = get_month_lengths(2004)
assert day >= 1
assert day <= month_lengths[month - 1]
month_lengths = get_month_lengths(2003)
if month == 1:
dindex = day
elif month == 2 and day == 29:
dindex = day_in_year(3, 1)
else:
dindex = np.sum(month_lengths[0:month - 1]) + day
return dindex
def get_hires_sst(lat, lon, month, day, hires_field):
"""
Get a value from a high resolution ie 0.25 degree daily SST field
:param lat: latitude of point to extract
:param lon: longitude of point to extract
:param month: month of point to extract
:param day: day in month of point to extract
:param hires_field: the field from which to extract the point
:type lat: float
:type lon: float
:type month: int
:type day: int
:type hires_field: numpy array
:return: the SST from the field at the specified point
"""
assert lat >= -90.0
assert lat <= 90.0
assert lon >= -180.00
assert lon <= 360.00
assert month >= 1
assert month <= 12
month_lengths = get_month_lengths(2004)
assert day >= 1
assert day <= month_lengths[month - 1]
dindex = day_in_year(month, day) - 1
yindex = lat_to_yindex(lat, 0.25)
xindex = lon_to_xindex(lon, 0.25)
result = hires_field[dindex, 0, yindex, xindex]
if result == -999:
result = None
return result
def get_sst_daily(lat, lon, month, day, sst):
"""
Get SST from pentad climatology interpolated to day
"""
assert lat >= -90.0
assert lat <= 90.0
assert lon >= -185.00
assert lon <= 365.00
assert month >= 1
assert month <= 12
month_lengths = get_month_lengths(2004)
assert day >= 1
assert day <= month_lengths[month - 1]
dindex = day_in_year(month, day) - 1
yindex = mds_lat_to_yindex(lat)
xindex = mds_lon_to_xindex(lon)
result = sst[dindex, yindex, xindex]
if type(result) is np.float64 or type(result) is np.float32:
pass
else:
if result.mask:
result = None
else:
result = result.data[0]
return result
def get_sst(lat, lon, month, day, sst):
"""
when given an array (sst) of appropriate type, extracts the value associated with that pentad,
latitude and longitude.
:param lat: latitude of the point
:param lon: longitude of the point
:param month: month of the point
:param day: day of the point
:param sst: an array holding the 1x1x5-day gridded values
:type lat: float
:type lon: float
:type month: integer
:type day: integer
:type sst: numpy array
:return: value in array at this point
:rtype: float
The structure of the SST array has to be quite specific it assumes a grid that is 360 x 180 x 73
i.e. one year of 1degree lat x 1degree lon data split up into pentads. The west-most box is at 180degrees with
index 0 and the northern most box also has index zero.
"""
assert lat >= -90.0
assert lat <= 90.0
assert lon >= -185.00
assert lon <= 365.00
assert month >= 1
assert month <= 12
month_lengths = get_month_lengths(2004)
assert day >= 1
assert day <= month_lengths[month - 1]
if len(sst[:, 0, 0]) == 1:
result = get_sst_single_field(lat, lon, sst)
else:
# read sst from grid
pentad = which_pentad(month, day)
yindex = lat_to_yindex(lat)
xindex = lon_to_xindex(lon)
result = sst[pentad - 1, yindex, xindex]
# sometimes this will be a numpy array and sometimes it will
# be a masked array. Need to identify which and
# make sure output is appropriate
if type(result) is np.float64 or type(result) is np.float32:
pass
else:
if result.mask:
result = None
else:
result = result.data[0]
return result
def get_hires_clim(rep, clim):
"""
Get the climatological value for this particular observation
:param rep: a MarineReport
:param clim: a masked array containing the climatological averages
:type rep: MarineReport
:type clim: numpy array
"""
try:
rep_clim = get_hires_sst(rep.lat(),
rep.lon(),
rep.getvar('MO'),
rep.getvar('DY'),
clim)
rep_clim = float(rep_clim)
except:
rep_clim = None
return rep_clim
def bilinear_interp(x1, x2, y1, y2, x, y, q11, q12, q21, q22):
"""
Perform a bilinear interpolation at the point x,y from the rectangular grid
defined by x1,y1 and x2,y2 with values at the four corners equal to Q11, Q12,
Q21 and Q22.
"""
assert x1 <= x <= x2
assert y1 <= y <= y2
assert x2 > x1
assert y2 > y1
assert q11 is not None and q12 is not None and q21 is not None and q22 is not None
val = q11 * (x2 - x) * (y2 - y)
val += q21 * (x - x1) * (y2 - y)
val += q12 * (x2 - x) * (y - y1)
val += q22 * (x - x1) * (y - y1)
val /= (x2 - x1) * (y2 - y1)
assert val <= 0.0001 + max([q11, q12, q21, q22]), \
str(val) + ' ' + str(q11) + ' ' + str(q12) + ' ' + str(q21) + ' ' + str(q22)
assert val >= -0.0001 + min([q11, q12, q21, q22]), \
str(val) + ' ' + str(q11) + ' ' + str(q12) + ' ' + str(q21) + ' ' + str(q22)
return val
def missing_mean(inarr):
result = 0.0
num = 0.0
for val in inarr:
if val is not None:
result += val
num += 1.0
if num == 0.0:
return None
else:
return result / num
def fill_missing_vals(q11, q12, q21, q22):
"""
For a group of four neighbouring grid boxes which form a square,
fill gaps using means of neighbours
"""
outq11 = q11
outq12 = q12
outq21 = q21
outq22 = q22
if outq11 is None:
outq11 = missing_mean([q12, q21])
if outq11 is None:
outq11 = q22
if outq22 is None:
outq22 = missing_mean([q12, q21])
if outq22 is None:
outq22 = q11
if outq12 is None:
outq12 = missing_mean([q11, q22])
if outq12 is None:
outq12 = q21
if outq21 is None:
outq21 = missing_mean([q11, q22])
if outq21 is None:
outq21 = q12
return outq11, outq12, outq21, outq22
def get_four_surrounding_points(lat, lon, max90=1):
assert -90.0 <= lat <= 90.0
assert -180.0 <= lon <= 180.0
x2_index = lon_to_xindex(lon + 0.5)
x2 = xindex_to_lon(x2_index)
if x2 < lon:
x2 += 360.
x1_index = lon_to_xindex(lon - 0.5)
x1 = xindex_to_lon(x1_index)
if x1 > lon:
x1 -= 360.
if lat + 0.5 <= 90:
y2_index = lat_to_yindex(lat + 0.5)
y2 = yindex_to_lat(y2_index)
else:
y2 = 89.5
if max90 == 0:
y2 = 90.5
if lat - 0.5 >= -90:
y1_index = lat_to_yindex(lat - 0.5)
y1 = yindex_to_lat(y1_index)
else:
y1 = -89.5
if max90 == 0:
y1 = -90.5
return x1, x2, y1, y2
def get_clim_interpolated(rep, clim):
lat = rep.lat()
lon = rep.lon()
mo = rep.getvar('MO')
dy = rep.getvar('DY')
try:
pert1 = get_sst(lat + 0.001, lon + 0.001, mo, dy, clim)
except:
pert1 = None
try:
pert2 = get_sst(lat + 0.001, lon - 0.001, mo, dy, clim)
except:
pert2 = None
try:
pert3 = get_sst(lat - 0.001, lon + 0.001, mo, dy, clim)
except:
pert3 = None
try:
pert4 = get_sst(lat - 0.001, lon - 0.001, mo, dy, clim)
except:
pert4 = None
if pert1 is None and pert2 is None and pert3 is None and pert4 is None:
return None
x1, x2, y1, y2 = get_four_surrounding_points(lat, lon, 1)
try:
q11 = get_sst(y1, x1, mo, dy, clim)
except:
q11 = None
if q11 is not None:
q11 = float(q11)
try:
q22 = get_sst(y2, x2, mo, dy, clim)
except:
q22 = None
if q22 is not None:
q22 = float(q22)
try:
q12 = get_sst(y2, x1, mo, dy, clim)
except:
q12 = None
if q12 is not None:
q12 = float(q12)
try:
q21 = get_sst(y1, x2, mo, dy, clim)
except:
q21 = None
if q21 is not None:
q21 = float(q21)
q11, q12, q21, q22 = fill_missing_vals(q11, q12, q21, q22)
x1, x2, y1, y2 = get_four_surrounding_points(lat, lon, 0)
return bilinear_interp(x1, x2, y1, y2,
lon, lat,
q11, q12, q21, q22)
def get_clim(rep, clim):
"""
Get the climatological value for this particular observation
:param rep: a MarineReport
:param clim: a masked array containing the climatological averages
:type rep: MarineReport
:type clim: numpy array
"""
try:
rep_clim = get_sst(rep.lat(), rep.lon(),
rep.getvar('MO'),
rep.getvar('DY'),
clim)
rep_clim = float(rep_clim)
except:
rep_clim = None
return rep_clim
def get_sst_single_field(lat, lon, sst):
"""
when given an array (sst) of appropriate type, extracts the value associated with that pentad,
latitude and longitude.
:param lat: latitude of the point
:param lon: longitude of the point
:param sst: an array holding the 1x1x5-day gridded values
:type lat: float
:type lon: float
:type sst: numpy array
:return: value in array at this point
:rtype: float
The structure of the SST array has to be quite specific it assumes a grid that is 360 x 180 x 73
i.e. one year of 1degree lat x 1degree lon data split up into pentads. The west-most box is at 180degrees with
index 0 and the northern most box also has index zero.
"""
assert lat >= -90.0
assert lat <= 90.0
assert lon >= -180.00
assert lon <= 360.00
# read sst from grid
yindex = lat_to_yindex(lat)
xindex = lon_to_xindex(lon)
result = sst[0, yindex, xindex]
# sometimes this will be a numpy array and sometimes it will
# be a masked array. Need to identify which and
# make sure output is appropriate
if type(result) is np.float64 or type(result) is np.float32:
pass
else:
if result.mask:
result = None
else:
result = result.data[0]
return result
def blacklist(inid, indeck, inyear, inmonth, inlat, inlon, inpt=1):
"""
Blacklisting of observations from Deck 732 and others as needed
:param inid: ID of the report
:param indeck: Deck of the report
:param inyear: year of the report
:param inmonth: month of the report
:param inlat: latitude of the report
:param inlon: longitude of the report
:param inpt: pentad of the report
:type inid: string
:type indeck: integer
:type inyear: integer
:type inmonth: integer
:type inlat: float
:type inlon: float
:type inpt: integer
If the report is from Deck 732, compares the observations year and location to a table of pre-identified
regions in which Deck 732 observations are known to be dubious - see Rayner et al. 2006 and Kennedy et al.
2011b. Observations at 0 degrees latitude 0 degrees longitude are blacklisted as this is a common error.
C-MAN stations with platform type 13 are blacklisted. SEAS data from deck 874 are unreliable (SSTs were
often in excess of 50degC) and so the deck was removed.
"""
if inlon > 180.0:
inlon -= 360
result = 0
if inlat == 0.0 and inlon == 0.0:
result = 1 # blacklist all obs at 0,0
if inpt is not None and inpt == 13:
result = 1 # C-MAN data
if inid == 'SUPERIGORINA':
result = 1
# these are the definitions of the regions which are blacklisted for Deck 732
region = {1: [-175, 40, -170, 55],
2: [-165, 40, -160, 60],
3: [-145, 40, -140, 50],
4: [-140, 30, -135, 40],
5: [-140, 50, -130, 55],
6: [-70, 35, -60, 40],
7: [-50, 45, -40, 50],
8: [5, 70, 10, 80],
9: [0, -10, 10, 0],
10: [-30, -25, -25, -20],
11: [-60, -50, -55, -45],
12: [75, -20, 80, -15],
13: [50, -30, 60, -20],
14: [30, -40, 40, -30],
15: [20, 60, 25, 65],
16: [0, -40, 10, -30],
17: [-135, 30, -130, 40]}
# this dictionary contains the regions that are to be excluded for this year
year_to_regions = {1958: [1, 2, 3, 4, 5, 6, 14, 15],
1959: [1, 2, 3, 4, 5, 6, 14, 15],
1960: [1, 2, 3, 5, 6, 9, 14, 15],
1961: [1, 2, 3, 5, 6, 14, 15, 16],
1962: [1, 2, 3, 5, 12, 13, 14, 15, 16],
1963: [1, 2, 3, 5, 6, 12, 13, 14, 15, 16],
1964: [1, 2, 3, 5, 6, 12, 13, 14, 16],
1965: [1, 2, 6, 10, 12, 13, 14, 15, 16],
1966: [1, 2, 6, 9, 14, 15, 16],
1967: [1, 2, 5, 6, 9, 14, 15],
1968: [1, 2, 3, 5, 6, 9, 14, 15],
1969: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 13, 14, 15, 16],
1970: [1, 2, 3, 4, 5, 6, 8, 9, 14, 15],
1971: [1, 2, 3, 4, 5, 6, 7, 8, 9, 13, 14, 16],
1972: [4, 7, 8, 9, 10, 11, 13, 16, 17],
1973: [4, 7, 8, 10, 11, 13, 16, 17],
1974: [4, 7, 8, 10, 11, 16, 17]}
if indeck == 732:
if inyear in year_to_regions:
regions_to_check = year_to_regions[inyear]
for regid in regions_to_check:
thisreg = region[regid]
if thisreg[0] <= inlon <= thisreg[2] and thisreg[1] <= inlat <= thisreg[3]:
result = 1
if indeck == 874:
result = 1 # SEAS data gets blacklisted
if ((inyear == 2005 and inmonth == 11) or
(inyear == 2005 and inmonth == 12) or
(inyear == 2006 and inmonth == 1)):
if inid in ["53521 ", "53522 ", "53566 ", "53567 ",
"53568 ", "53571 ", "53578 ", "53580 ",
"53582 ", "53591 ", "53592 ", "53593 ",
"53594 ", "53595 ", "53596 ", "53599 ",
"53600 ", "53601 ", "53602 ", "53603 ",
"53604 ", "53605 ", "53606 ", "53607 ",
"53608 ", "53609 ", "53901 ", "53902 "]:
result = 1
return result
def climatology_plus_stdev_with_lowbar(inval, inclimav, instdev, limit, lowbar):
"""
Climatology check with standard deviation-based limits but with a minimum width
:param inval: value to be compared to climatology
:param inclimav: the climatological average to which it will be compared
:param instdev: the standard deviation which will be used to test the anomaly
:param limit: maximum standardised anomaly
:param lowbar: the anomaly must be greater than lowbar to fail regardless of standard deviation
:return: return 1 if the difference is outside the specified range, 0 otherwise.
"""
assert limit > 0, "multiplier must be positive and non-zero"
result = 0
if inval is None or inclimav is None or instdev is None:
result = 1
else:
if abs(inval - inclimav) / instdev > limit and abs(inval - inclimav) > lowbar:
result = 1
assert result == 0 or result == 1
return result
def climatology_plus_stdev_check(inval, inclimav, instdev,
stdev_limits, limit):
"""
Climatology check which uses standardised anomalies.
:param inval: value to be compared to climatology
:param inclimav: the climatological average to which the value will be compared
:param instdev: the climatological standard deviation which will be used to standardise the anomaly
:param stdev_limits: upper and lower limits for standard deviation used in check
:param limit: the maximum allowed normalised anomaly
:type inval: float
:type inclimav: float
:type instdev: float
:type stdev_limits: two-membered list
:type limit: float
:return: return 1 if the difference is outside the specified limit, 0 otherwise (or if any input is None)
:rtype: integer
"""
assert stdev_limits[1] > stdev_limits[0], "limits are awry"
assert limit > 0, "multiplier must be positive and non-zero"
result = 0
if inval is None or inclimav is None or instdev is None:
result = 1
else:
stdev = instdev
if stdev < stdev_limits[0]:
stdev = stdev_limits[0]
if stdev > stdev_limits[1]:
stdev = stdev_limits[1]
if abs(inval - inclimav) / stdev > limit:
result = 1
assert result == 0 or result == 1
return result
def climatology_check(inval, inclimav, limit=8.0):
"""
Simple function to compare a value with a climatological average with some arbitrary limit on the difference
:param inval: value to be compared to climatology
:param inclimav: the climatological average to which the value will be compared
:param limit: the maximum allowed difference between the two
:type inval: float
:type inclimav: float
:type limit: float
:return: return 1 if the difference is outside the specified limit, 0 otherwise
:rtype: integer
This may be the second simplest function I have ever written (see blacklist)
"""
result = 0
if inval is None or inclimav is None or limit is None:
result = 1
else:
if abs(inval - inclimav) > limit:
result = 1
assert result == 0 or result == 1
return result
def value_check(inval):
"""
Check if a value is equal to None
:param inval: the input value
:param inval: float
:return: 1 if the input value is None, 0 otherwise
:return type: integer
"""
result = 0
if inval is None:
result = 1
return result
def no_normal_check(inclimav):
"""
Check if a climatological average is equal to None
:param inclimav: the input value
:type inclimav: float
:return: 1 if the input value is None, 0 otherwise
:return type: integer
"""
result = 0
if inclimav is None:
result = 1
return result
def hard_limit(val, limits):
"""
Check if a value is outside specified limits
:param val: value to be tested
:param limits: two membered list of lower and upper limit
:type val: float
:type limits: list of floats
:return: 1 if the input is outside the limits, 0 otherwise
:return type: integer
"""
assert limits[1] > limits[0], 'limits are not well specified'
if val is None:
return 1
result = 1
if limits[0] <= val <= limits[1]:
result = 0
return result
def supersat_check(invaltd, invalt):
"""
Check if a valid dewpoint temperature is
greater than a valid air temperature
:param invaltd: the input value for dewpoint temperature
:param invalt: the input value for air temperature
:type invaltd: float
:type invalt: float
:return: 1 if the input values are invalid/None
:return: 1 if the dewpoint temperature is greater than the air temperarture
:return: 0 otherwise
:return type: integer
"""
result = 0
if (invaltd is None) | (invalt is None):
result = 1
elif invaltd > invalt:
result = 1
return result
def sst_freeze_check(insst, sst_uncertainty=0.0, freezing_point=-1.80, n_sigma=2.0):
"""
Compare an input SST to see if it is above freezing.
:param insst: the input SST
:param sst_uncertainty: the uncertainty in the SST value, defaults to zero
:param freezing_point: the freezing point of the water, defaults to -1.8C
:param n_sigma: number of sigma to use in the check
:type insst: float
:type sst_uncertainty: float
:type freezing_point: float
:type n_sigma: float
:return: 1 if the input SST is below freezing point by more than twice the uncertainty, 0 otherwise
:return type: integer
This is a simple freezing point check made slightly more complex. We want to check if a
measurement of SST is above freezing, but there are two problems. First, the freezing point
can vary from place to place depending on the salinity of the water. Second, there is uncertainty
in SST measurements. If we place a hard cut-off at -1.8, then we are likely to bias the average
of many measurements too high when they are near the freezing point - observational error will
push the measurements randomly higher and lower, and this test will trim out the lower tail, thus
biasing the result. The inclusion of an SST uncertainty parameter *might* mitigate that.
"""
assert sst_uncertainty is not None and freezing_point is not None
# fail if SST below the freezing point by more than twice the uncertainty
result = 0
if insst is not None:
if insst < (freezing_point - n_sigma * sst_uncertainty):
result = 1
assert result == 1 or result == 0
return result
def position_check(inlat, inlon):
"""
Simple check to make sure that the latitude and longitude are within the bounds specified
by the ICOADS documentation. Latitude is between -90 and 90. Longitude is between -180 and 360
:param inlat: latitude
:param inlon: longitude
:type inlat: float
:type inlon: float
:return: 1 if either latitude or longitude is invalid, 0 otherwise
:return type: integer
"""
# return 1 if lat or lon is invalid, 0 otherwise
assert inlat is not None and not (math.isnan(inlat))
assert inlon is not None and not (math.isnan(inlon))
result = 0
if inlat < -90 or inlat > 90:
result = 1
if inlon < -180 or inlon > 360:
result = 1
assert result == 1 or result == 0
return result
def time_check(inhour):
"""
Check that the time is valid
:param inhour: hour of the time to be checked
:type inhour: float
:return: 1 if the hour is invalid, 0 otherwise
:return type: integer
"""
result = 0
if inhour is not None and (inhour >= 24 or inhour < 0):
result = 1
if inhour is None:
result = 1
return result
def date_check(inyear, inmonth, inday):
"""
Check that the date is valid
:param inyear: year of the date to be checked
:param inmonth: month of the data to be checked
:param inday: day of the date to be checked
:type inyear: integer
:type inmonth: integer
:type inday: integer
:return: 1 if any one of the inputs (or the combined inputs) is invalid, 0 otherwise
:return type: integer
"""
# return 1 if date is valid. 0 otherwise
assert inyear is not None
assert inmonth is not None
result = 0
if inyear > 2024 or inyear < 1850:
result = 1
if inmonth < 1 or inmonth > 12:
result = 1
month_lengths = get_month_lengths(inyear)
if inday is None:
result = 1
else:
if inday < 1 or inday > month_lengths[inmonth - 1]:
result = 1
return result
def wind_consistency(windspeed, winddirection, variablelimit):
"""
Test to compare windspeed to winddirection.
:param windspeed: wind speed
:param winddirection: wind direction in range 1-362
:param variablelimit: maximum wind speed consistent with variable wind direction
:type windspeed: float
:type winddirection: integer
:type variablelimit: float
:return: pass (0) or fail (1)
:rtype: integer
"""
result = 0
# direction 361 is Calm i.e. windspeed should be zero
if winddirection == 361 and windspeed != 0:
result = 1
# direction 363 is Variable i.e. low windspeed
if winddirection == 362 and windspeed > variablelimit:
result = 1
return result
def p_data_given_good(x, q, r_hi, r_lo, mu, sigma):
"""
Calculate the probability of an observed value x given a normal distribution with mean mu
standard deviation of sigma, where x is constrained to fall between R_hi and R_lo
and is known only to an integer multiple of Q, the quantization level.
:param x: observed value for which probability is required
:param q: quantization of x, i.e. x is an integer multiple of Q
:param r_hi: the upper limit on x imposed by previous QC choices.
:param r_lo: the lower limit on x imposed by previous QC choices.
:param mu: the mean of the distribution.
:param sigma: the standard deviation of the distribution
:type x: float
:type q: float
:type r_hi: float
:type r_lo: float
:type mu: float
:type sigma: float
:return: probability of the observed value given the specified distribution.
:rtype: float
"""
assert q > 0.0, "q <= 0" + str(q)
assert sigma > 0.0, "sigma <= 0 " + str(sigma)
assert r_hi > r_lo, "Limits not ascending r_lo " + str(r_lo) + " > r_hi " + str(r_hi)
assert x >= r_lo, "x below lower limit " + str(x) + " < r_lo " + str(r_lo)
assert x <= r_hi, "x above upper limit " + str(x) + " > r_hi " + str(r_hi)
upper_x = min([x + 0.5 * q, r_hi + 0.5 * q])
lower_x = max([x - 0.5 * q, r_lo - 0.5 * q])
normalizer = 0.5 * (math.erf((r_hi + 0.5 * q - mu) / (sigma * math.sqrt(2))) -
math.erf((r_lo - 0.5 * q - mu) / (sigma * math.sqrt(2))))
return 0.5 * (math.erf((upper_x - mu) / (sigma * math.sqrt(2))) -
math.erf((lower_x - mu) / (sigma * math.sqrt(2)))) / normalizer
def p_data_given_gross(q, r_hi, r_lo):
"""
Calculate the probability of the data given a gross error
assuming gross errors are uniformly distributed between
R_low and R_high and that the quantization, rounding level is Q
:param q: quantization of x, i.e. x is an integer multiple of Q
:param r_hi: the upper limit on x imposed by previous QC choices.
:param r_lo: the lower limit on x imposed by previous QC choices.
:type q: float
:type r_hi: float
:type r_lo: float
:return: probability of the observed value given that its a gross error.
:rtpye: float
"""
assert r_hi > r_lo, "Limits not ascending r_lo " + str(r_lo) + " > r_hi " + str(r_hi)
assert q > 0.0, "q <= 0" + str(q)
r = r_hi - r_lo
return 1. / (1. + (r / q))