-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathmk_netcdf_files.py
1784 lines (1386 loc) · 92.9 KB
/
mk_netcdf_files.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/local/sci/bin/python
#************************************************************************
# SVN Info
#$Rev:: 219 $: Revision of last commit
#$Author:: rdunn $: Author of last commit
#$Date:: 2019-05-20 16:56:47 +0100 (Mon, 20 May 2019) $: Date of last commit
#************************************************************************
'''
Python script to read the ISD ASCII text format and output netcdf files
Runs with no inputs in current version.
Compared to IDL output using compare.py on 30May2012 and found to match
except for total_cloud_flags - but on investigation with raw ISD files
the python extraction is the correct one. RJHD
Could change data types to match IDL, but adapting QC so that works with
floats and doubles as appropriate.RJHD
Logic change to match IDL so that overwrite only acted upon if writing
real data, rather than missing. RJHD
'''
import numpy as np
import datetime as dt
import glob
import gzip
import subprocess
import math
import netCDF4 as ncdf
import sys
import os
import argparse
import datetime, calendar
# RJHD utils
from set_paths_and_vars import *
# Globals
INTMDI=-999
FLTMDI=-1.e30
hours = True # output time axis in hours.
NCDC_FLAGS={'A':10,'U':11,'P':12,'I':13,'M':14,'C':15,'R':16, 'E':17, 'J':18}
#---------------------------------------------------------------------
#************************************************************************
def ReadStations(filename):
"""
Read Station Information
:param string filename: name and location of input file
:returns: numpy array of file contents
Use numpy genfromtxt reading to read in all station
data in ID,Lat,Lon,Elev list
"""
return np.genfromtxt(filename, dtype=(str)) # ReadStations
#************************************************************************
def ReadComposites(filename):
"""
Read Composite Station Information
:param string filename: name and location of input file
:returns: list of lists containing composites
"""
composites=[]
try:
with open(filename) as infile:
for line in infile:
split_line=line.split()
composites.append(split_line[:])
except IOError:
print "File not found: ",filename
raise IOError
return composites # ReadComposites
#************************************************************************
def RepresentsInt(s):
"""
Tests if string is an integer
:param string s: string to test
:returns: boolean if string is valid integer
"""
try:
int(s)
return True
except ValueError:
return False # RepresentsInt
#************************************************************************
def TimeMatch(timearray,testtime, lower,upper):
"""
Do matching of np array to find time step
:param array timearray: np array of timestamps
:param float testtime: timestep to find
:return: int of location
"""
return np.argwhere(timearray[lower:upper]==testtime)[0] # TimeMatch
#************************************************************************
def ExtractValues(missing,line,location,length,test,divisor=1.,flagoffset=0, doflag=True):
"""
Extract the appropriate values from the line string.
Assumes that usually it is a value,flag pair, with no scaling factor and that
the flag follows directly on from the value. Can be adjusted.
:param float/int missing: mdi
:param string line: input line from file
:param int location: location of start of string subset to read in
:param int length: length of string to convert to value
:param int test: value of string if data missing
:param float divisor: scaling factor for data, default=1
:param int flagoffset: shift of flag from end of data, default=0
:param boolean doflag: to extract a flag value, default=True
:returns: tuple of value, flag OR value if doflag=False
"""
temp_value=line[location:location+length]
value=missing
flag=INTMDI
if temp_value != test:
if missing==FLTMDI:
value=float(temp_value)/divisor
elif missing==INTMDI:
value=int(temp_value)/divisor
elif missing=='':
value=temp_value
if doflag:
flag=line[location+length+flagoffset:location+length+flagoffset+1]
if RepresentsInt(flag):
flag=int(flag)
else:
try:
flag=NCDC_FLAGS[flag]
except KeyError:
print 'ALPHA FLAG CONVERSION FAILED'
print 'input flag is: '+flag
print 'Line in raw ISD record reads:'
print line
flag=20
if doflag:
return value,flag
else:
return value # ExtractValues
#************************************************************************
def TestToExtract(data,missing,overwrite):
"""
Test if need to extract the data
:param float/int data: data to test
:param float/int missing: missing value
:param boolean overwrite: to overwrite or not
:returns: boolean if condition met
"""
if data==missing or overwrite:
return True
else:
return False # TestToExtract
#************************************************************************
def ExtractionProcess(data, flags, time, missing, missingtest, line, location, length,divisor=1.,flagoffset=0, doflag=True):
"""
Run the extraction, and write the values if the extracted ones are not empty
:param array data: the data array
:param array flags: the flags array
:param int time: the time stamp
:param float/int missing: mdi
:param float/int missingtest: value of string if missing
:param string line: input line from file
:param int location: location of start of string subset to read in
:param int length: length of string to convert to value
:param int test: value of string if data missing
:param float divisor: scaling factor for data, default=1
:param int flagoffset: shift of flag from end of data, default=0
:param boolean doflag: to extract a flag value, default=True
"""
if doflag:
value,flag=ExtractValues(missing,line,location,length,missingtest,divisor=divisor,flagoffset=flagoffset,doflag=doflag)
# no longer want to test that there was a value - as all data taken from
# single observation, regardless of who complete it is.
# left old code extant in case changes to happen in future
if value != missing:
data[time],flags[time]=value,flag
else:
data[time],flags[time]=value,flag
else:
value=ExtractValues(missing,line,location,length,missingtest,divisor=divisor,flagoffset=flagoffset,doflag=doflag)
if value != missing:
data[time]=value
else:
data[time]=value
return # ExtractionProcess
#************************************************************************
def WriteDubious(outfile,infile,code, station, time):
"""
Write note to dubious file list.
:param string outfile: filename to be written to
:param string infile: filename of dubious file
:param string code: text identifier of variables being tested
:param string station: station ID being processed
:param string time: time of the dubious data
:returns: int of flag status.
"""
flagged=0
try:
with open(outfile,'a') as of:
of.write(station+' '+time+' '+code+' variables are first, but not nec. only problem '+infile+'\n')
of.close()
flagged=1
except IOError:
# file doesn't exist as yet, so make a new one
with open(outfile,'w') as of:
of.write(station+' '+time+' '+code+' variables are first, but not nec. only problem '+infile+'\n')
of.close()
flagged=1
return flagged # WriteDubious
#************************************************************************
def SortClouds(cloud_cover,cloud_flags, time, amounts, flags, clouds):
"""
Convert the raw cloud data into oktas for each level
:param array cloud_cover: final cloud_cover array
:param array cloud_flags: final cloud_flags array
:param int time_loc: time stamp
:param array amounts: raw cloud amounts - in oktas
:param array flags: raw cloud flags
:param array clouds: locations of where cloud heights match this level
"""
if len(clouds)>=1 and cloud_cover[time]==INTMDI:
cloud_cover[time]=np.max(amounts[clouds])
cloud_flags[time]=np.max(flags[clouds])
return # SortClouds
#************************************************************************
def SortClouds2(cloud_cover,cloud_flags, time, amounts, amounts2, flags, clouds):
"""
Convert the raw cloud data into oktas and for each level
:param array cloud_cover: final cloud_cover array
:param array cloud_flags: final cloud_flags array
:param int time_loc: time stamp
:param array amounts: raw cloud amounts - in other units - see ISD documentation
:param array amounts2: raw cloud amounts - in oktas
:param array flags: raw cloud flags
:param array clouds: locations of where cloud heights match this level
"""
inoktas=np.where(np.array(amounts2[clouds]) != INTMDI)[0]
if len(inoktas)>=1 and cloud_cover[time]==INTMDI:
cloud_cover[time]=np.max(amounts[clouds][inoktas])
cloud_flags[time]=np.max(flags[clouds][inoktas])
elif cloud_cover[time]==INTMDI:
# convert to oktas
cloud_cover[time]=np.max(amounts[clouds])*2.
cloud_flags[time]=np.max(flags[clouds])
return # SortClouds2
#************************************************************************
def WriteAttributes(variable,long_name,cell_methods,missing_value,units,axis,vmin,vmax,coordinates,standard_name = ''):
"""
Write given attributes into ncdf variable
:param object variable: netcdf Variable
:param string long_name: long_name value for variable to be written
:param string cell_methods: cell_methods value for variable to be written
:param float/int missing_value: missing_value value for variable to be written
:param string units: units value for variable to be written
:param string axis: axis value for variable to be written
:param float/int vmin: valid_min value for variable to be written
:param float/int vmax: valid_max value for variable to be written
:param string standard_name: standard_name value for variable to be written
:param string coordinates: coordinates to associate to variable
"""
variable.long_name=long_name
variable.cell_methods=cell_methods
variable.missing_value=missing_value
# variable.axis=axis # 12/1/17 RJHD - not required for CF compliance.
variable.units=units
variable.valid_min=vmin
variable.valid_max=vmax
variable.coordinates=coordinates
if standard_name != '':
variable.standard_name=standard_name
return # WriteAttributes
#************************************************************************
def WriteFlagAttributes(variable,long_name,missing_value,axis):
"""
Write given attributes into ncdf variable
:param object variable: netcdf Variable
:param string long_name: long_name value for variable to be written
:param float/int missing_value: missing_value value for variable to be written
:param string axis: axis value for variable to be written
"""
variable.long_name=long_name
variable.missing_value=missing_value
variable.units="1"
# variable.axis=axis # 12/1/17 RJHD - not required for CF compliance.
# for future [September 2015]
# http://cfconventions.org/Data/cf-conventions/cf-conventions-1.6/build/cf-conventions.html#flags
return # WriteFlagAttributes
#************************************************************************
def write_coordinates(outfile, short_name, standard_name, long_name, units, axis, data, coordinate_length = 1, do_zip = True):
"""
Write coordinates as variables
:param str outfile: output netcdf file
:param str short_name: netcdf short_name
:param str standard_name: netcdf standard_name
:param str long_name: netcdf long_name
:param str units: netcdf units
:param str axis: netcdf axis
:param flt data: coordinate
:param int coordinate_length: length of dimension
:param bool do_zip: allow for zipping
"""
if "coordinate_length" not in outfile.dimensions:
coord_dim = outfile.createDimension('coordinate_length', coordinate_length)
nc_var = outfile.createVariable(short_name, np.dtype('float'), ('coordinate_length',), zlib = do_zip)
nc_var.standard_name = standard_name
nc_var.long_name = long_name
nc_var.units = units
nc_var.axis = axis
if short_name == "alt":
nc_var.positive = "up"
nc_var[:] = data
return # write_coordinates
#************************************************************************
def MakeNetcdfFiles(STARTYEAR, ENDYEAR, ENDMONTH, restart_id="", end_id="", do_zip = True, Extra = False, doCanada = True):
"""
Parse the ASCII files and do the NetCDF file creation
:param string restart_id: string for starting station, default=""
:param string end_id: string for ending station, default=""
:param boolean do_zip: make netCDF4 files with internal zipping
:param boolean Extra: setting to extract extra variables
"""
print "Note to Self on re-write (26/2/2018)"
print "Use the netcdf_procs to write the netcdf file."
print "Have text lookup file for variable attributes (allow for free text if necessary)"
print "Standardise across the precip1-4 variables OR read all 4 and split into 1/3/6/12/24 hourly accumulations."
print "Cope with updated ISD format."
StationInfo=ReadStations(os.path.join(INPUT_FILE_LOCS, STATION_LIST))
StationIDs=np.array(StationInfo[:,0])
# sorted in case of unordered lists
sort_order=np.argsort(StationIDs)
StationIDs=StationIDs[sort_order]
StationLat=np.array([float(x) for x in StationInfo[sort_order,1]])
StationLon=np.array([float(x) for x in StationInfo[sort_order,2]])
StationElv=np.array([float(x) for x in StationInfo[sort_order,3]])
print "Read in %i stations" % len(StationIDs)
# reduce station list to start and end stations
if restart_id != "":
startindex=np.where(StationIDs==restart_id)[0][0]
StationIDs=StationIDs[startindex:]
StationLat=StationLat[startindex:]
StationLon=StationLon[startindex:]
StationElv=StationElv[startindex:]
if end_id != "":
endindex=np.where(StationIDs==end_id)[0][0]
StationIDs=StationIDs[:endindex+1]
StationLat=StationLat[:endindex+1]
StationLon=StationLon[:endindex+1]
StationElv=StationElv[:endindex+1]
if restart_id !="" or end_id!="":
print "Truncated run selected"
print "Processing %i stations" % len(StationIDs)
nstations=len(StationIDs)
Composites=ReadComposites(os.path.join(INPUT_FILE_LOCS, MERGER_LIST))
# adjust the end points for clarity and ease of use
if ENDMONTH == 12:
# easier to use the 1st January at 00:00
ENDYEAR += 1
ENDMONTH = 1
else:
# easier to use the 1st of the following month at 00:00
ENDMONTH += 1
DaysBetween=dt.datetime(ENDYEAR, ENDMONTH, 1, 0, 0) - dt.datetime(STARTYEAR, 1, 1, 0, 0)
HoursBetween=int(DaysBetween.days*24.)
TimeStamps=np.linspace(0,HoursBetween-1,HoursBetween) # keep in integer hours
ValidYears=np.arange(STARTYEAR, ENDYEAR+1)
dubiousfile=LOG_OUTFILE_LOCS+'dubious_ISD_data_files.txt'
# read in Canadian station list
if doCanada:
Canadian_stations_info = np.genfromtxt(INPUT_FILE_LOCS + "Canada_time_ranges.dat", dtype=(str), delimiter = [12,20,20])
Canadian_station_ids = Canadian_stations_info[:,0]
Canadian_station_start = np.array([dt.datetime.strptime(d.strip(), "%Y-%m-%d %H:%M:%S") for d in Canadian_stations_info[:,1]])
Canadian_station_end = np.array([dt.datetime.strptime(d.strip(), "%Y-%m-%d %H:%M:%S") for d in Canadian_stations_info[:,2]])
dbg_sttime=dt.datetime.now()
for st,station in enumerate(StationIDs):
print '%s, number %i of %i' %(station, st+1, nstations)
temperatures=np.zeros(HoursBetween)
temperature_flags=np.zeros(HoursBetween, dtype=np.int)
dewpoints=np.zeros(HoursBetween)
dewpoint_flags=np.zeros(HoursBetween, dtype=np.int)
total_cloud_cover=np.zeros(HoursBetween, dtype=np.int)
total_cloud_flags=np.zeros(HoursBetween, dtype=np.int)
low_cloud_cover=np.zeros(HoursBetween, dtype=np.int)
low_cloud_flags=np.zeros(HoursBetween, dtype=np.int)
mid_cloud_cover=np.zeros(HoursBetween, dtype=np.int)
mid_cloud_flags=np.zeros(HoursBetween, dtype=np.int)
high_cloud_cover=np.zeros(HoursBetween, dtype=np.int)
high_cloud_flags=np.zeros(HoursBetween, dtype=np.int)
cloud_base=np.zeros(HoursBetween)
cloud_base_flags=np.zeros(HoursBetween, dtype=np.int)
windspeeds=np.zeros(HoursBetween)
windspeeds_flags=np.zeros(HoursBetween, dtype=np.int)
winddirs=np.zeros(HoursBetween, dtype=np.int)
winddirs_flags=np.zeros(HoursBetween, dtype=np.int)
past_sigwx1=np.zeros(HoursBetween, dtype=np.int)
past_sigwx1_period=np.zeros(HoursBetween, dtype=np.int)
past_sigwx1_flag=np.zeros(HoursBetween, dtype=np.int)
precip1_period=np.zeros(HoursBetween, dtype=np.int)
precip1_depth=np.zeros(HoursBetween)
precip1_condition=['null' for i in range(HoursBetween)]
precip1_flag=np.zeros(HoursBetween, dtype=np.int)
slp=np.zeros(HoursBetween)
slp_flag=np.zeros(HoursBetween, dtype=np.int)
sun_duration=np.zeros(HoursBetween)
sun_durationqc=np.zeros(HoursBetween, dtype=np.int)
wind_gust_period=np.zeros(HoursBetween)
wind_gust_value=np.zeros(HoursBetween)
wind_gust_flags=np.zeros(HoursBetween, dtype=np.int)
# Tells you what the true input station id was for the duplicate
# using list as string array.
input_station_id=['null' for i in range(HoursBetween)]
temperatures.fill(FLTMDI)
temperature_flags.fill(INTMDI)
dewpoints.fill(FLTMDI)
dewpoint_flags.fill(INTMDI)
total_cloud_cover.fill(INTMDI)
total_cloud_flags.fill(INTMDI)
low_cloud_cover.fill(INTMDI)
low_cloud_flags.fill(INTMDI)
mid_cloud_cover.fill(INTMDI)
mid_cloud_flags.fill(INTMDI)
high_cloud_cover.fill(INTMDI)
high_cloud_flags.fill(INTMDI)
cloud_base.fill(INTMDI)
cloud_base_flags.fill(INTMDI)
windspeeds.fill(FLTMDI)
windspeeds_flags.fill(INTMDI)
winddirs.fill(INTMDI)
winddirs_flags.fill(INTMDI)
past_sigwx1.fill(INTMDI)
past_sigwx1_period.fill(INTMDI)
past_sigwx1_flag.fill(INTMDI)
precip1_period.fill(INTMDI)
precip1_depth.fill(FLTMDI)
precip1_flag.fill(INTMDI)
slp.fill(FLTMDI)
slp_flag.fill(INTMDI)
sun_duration.fill(INTMDI)
sun_durationqc.fill(INTMDI)
wind_gust_period.fill(FLTMDI)
wind_gust_value.fill(FLTMDI)
wind_gust_flags.fill(INTMDI)
if Extra:
windtypes=['null' for i in range(HoursBetween)]
present_sigwx=np.zeros(HoursBetween, dtype=np.int)
present_sigwx_flags=np.zeros(HoursBetween, dtype=np.int)
past_sigwx2=np.zeros(HoursBetween, dtype=np.int)
past_sigwx2_period=np.zeros(HoursBetween, dtype=np.int)
past_sigwx2_flag=np.zeros(HoursBetween, dtype=np.int)
precip2_period=np.zeros(HoursBetween, dtype=np.int)
precip2_depth=np.zeros(HoursBetween)
precip2_condition=['null' for i in range(HoursBetween)]
precip2_flag=np.zeros(HoursBetween, dtype=np.int)
precip3_period=np.zeros(HoursBetween, dtype=np.int)
precip3_depth=np.zeros(HoursBetween)
precip3_condition=['null' for i in range(HoursBetween)]
precip3_flag=np.zeros(HoursBetween, dtype=np.int)
precip4_period=np.zeros(HoursBetween, dtype=np.int)
precip4_depth=np.zeros(HoursBetween)
precip4_condition=['null' for i in range(HoursBetween)]
precip4_flag=np.zeros(HoursBetween, dtype=np.int)
maximum_temp_period=np.zeros(HoursBetween)
maximum_temp_value=np.zeros(HoursBetween)
maximum_temp_flags=np.zeros(HoursBetween, dtype=np.int)
minimum_temp_period=np.zeros(HoursBetween)
minimum_temp_value=np.zeros(HoursBetween)
minimum_temp_flags=np.zeros(HoursBetween, dtype=np.int)
present_sigwx.fill(INTMDI)
present_sigwx_flags.fill(INTMDI)
past_sigwx2.fill(INTMDI)
past_sigwx2_period.fill(INTMDI)
past_sigwx2_flag.fill(INTMDI)
precip2_period.fill(INTMDI)
precip2_depth.fill(FLTMDI)
precip2_flag.fill(INTMDI)
precip3_period.fill(INTMDI)
precip3_depth.fill(FLTMDI)
precip3_flag.fill(INTMDI)
precip4_period.fill(INTMDI)
precip4_depth.fill(FLTMDI)
precip4_flag.fill(INTMDI)
maximum_temp_period.fill(FLTMDI)
maximum_temp_value.fill(FLTMDI)
maximum_temp_flags.fill(INTMDI)
minimum_temp_period.fill(FLTMDI)
minimum_temp_value.fill(FLTMDI)
minimum_temp_flags.fill(INTMDI)
# extract stations to process, including composites.
is_composite=next((i for i, sublist in enumerate(Composites) if station in sublist), -1)
if is_composite!=-1:
consider_these=Composites[is_composite]
print 'This is a duplicate station containing %s ' % ' '.join(consider_these)
else:
consider_these=[station]
# get listing of all files to process
raw_files=[]
for cstn in consider_these:
if cstn[0:3] >= '725' and cstn[0:3] <= '729':
raw_files.extend(glob.glob(ISD_DATA_LOCS+'station725/'+cstn+'*'))
else:
raw_files.extend(glob.glob(ISD_DATA_LOCS+'station'+cstn[0:2]+'s/'+cstn+'*'))
raw_files.sort()
dbg_lasttime=dt.datetime.now()
for rfile in raw_files:
done_print = False # for output of Canadian station skipping
a=dt.datetime.now()-dbg_lasttime
print rfile, a
dbg_lasttime=dt.datetime.now()
raw_station=rfile.split('/')[-1][0:12]
rfile_year=int(rfile.split('-')[-1].split('.')[0])
rfile_days=dt.datetime(rfile_year,1,1,0,0)-dt.datetime(STARTYEAR,1,1,0,0)
rfile_hours=rfile_days.days*24.
rfile_ydays=dt.datetime(rfile_year+1,1,1,0,0)-dt.datetime(rfile_year,1,1,0,0)
rfile_yhours=rfile_ydays.days*24
if rfile_year in ValidYears:
dubious_flagged=0
if rfile[-2:]!='gz':
subprocess.call(['gzip','-f','-9',rfile])
rfile=rfile+'.gz'
# note - this amends the file identifier in the loop
last_obs_time=0.
try:
with gzip.open(rfile,'r') as infile:
for rawline in infile:
# main processing
# check for remarks
cleanline=rawline[0:rawline.find('REM')]
# find which timestamp we're working at
year=int(cleanline[15:19])
month=int(cleanline[19:21])
day=int(cleanline[21:23])
hour=int(cleanline[23:25])
minute=int(cleanline[25:27])
# found error in minute value in 030910-99999, 035623-99999
if minute < 0:
hour=hour-1
minute=60+minute
elif minute > 59:
hour=hour+1
minute=minute-60
if hour < 0:
day=day-1
hour=24+hour
elif hour > 23:
day=day+1
hour=hour-24
# adjust the day (and month)
dummy, ndays = calendar.monthrange(year, month)
if day <= 0:
month = month -1
dummy, ndays = calendar.monthrange(year, month)
day=ndays - day
elif day > ndays:
month=month+1
day=day - ndays
if month <= 0:
month = 12 - month
year = year - 1
elif month > 12:
month=month - 12
year = year + 1
dt_time = dt.datetime(year, month, day, hour, minute)
if dt_time > dt.datetime(ENDYEAR, ENDMONTH, 1, 0, 0):
# data beyond the end of the timeperiod. Ignored
if not done_print:
print "skipping rest of station {} as {} after end of selected period ({})".format(raw_station, dt.datetime.strftime(dt_time, "%Y-%m-%d %H:%M"), dt.datetime.strftime(dt.datetime(ENDYEAR, ENDMONTH, 1, 0, 0), "%Y-%m-%d %H:%M"))
done_print = True
continue
if doCanada:
if raw_station in Canadian_station_ids:
# then test for restrictions on start/end times
loc, = np.where(Canadian_station_ids == raw_station)
if dt_time < Canadian_station_start[loc[0]]:
if not done_print:
print "skipping year {} of station {} as identified as undocumented move by Environment Canada".format(year, raw_station)
done_print = True
continue
if dt_time > Canadian_station_end[loc[0]]:
if not done_print:
print "skipping year {} of station {} as identified as undocumented move by Environment Canada".format(year, raw_station)
done_print = True
continue
# integer hours
obs_time=ncdf.date2num(dt_time, units='hours since '+str(STARTYEAR)+'-01-01 00:00:00', calendar='julian')
string_obs_time=dt.datetime.strftime(dt_time,"%d-%m-%Y, %H:%M")
# working in hours, so just round the hours since
# start date to get the time stamp 13/6/2012
time_loc=int(round(obs_time))
# test if this time_loc out of bounds:
# e.g. if 2350 on 31/12/ENDYEAR then should not
# takes the obs as it belongs to following year
if time_loc != HoursBetween:
# test if closer to timestamp than previous observation
# overwrite only acted upon if newer real data closer to full hour
currentT=temperatures[time_loc]
currentD=dewpoints[time_loc]
newT=ExtractValues(FLTMDI,cleanline,87,5,'+9999',divisor=10.,doflag=False)
newD=ExtractValues(FLTMDI,cleanline,93,5,'+9999',divisor=10.,doflag=False)
Extract=False
# no extract happened for this time stamp as yet - so extract
if input_station_id[time_loc] =='null':
# this is not an overwrite, so nothing extra needs doing
Extract=True
# if currently have no T or D data
elif currentT==FLTMDI and currentD==FLTMDI:
# if overwriting, only do so with observation closer to time stamp
if input_station_id[time_loc] == raw_station: # tests if already read into this time stamp
if (newT != FLTMDI) or (newD != FLTMDI):
# if updated data would have T or D, then take it, even if further from the time stamp
Extract=True
elif last_obs_time != 0.: # not really necessary as already have at least 1 obs, but still...
# if time stamp closer than last one
if np.abs(TimeStamps[time_loc]-obs_time) < np.abs(TimeStamps[time_loc]-last_obs_time):
Extract=True
# else just take the line - no observations read into this time stamp yet
else:
Extract=True
# if already have T but _no_ D OR D but _no_ T, but new one has T and D, take this line
# this is an overwrite - so also check that overwriting with the same station
elif ((currentT!=FLTMDI and currentD==FLTMDI) or (currentT==FLTMDI and currentD!=FLTMDI)) \
and (newT!=FLTMDI and newD!=FLTMDI):
if input_station_id[time_loc] == raw_station:
# preference to both values over just one
Extract=True
# have D but no T, and new observation comes up with T, select if closer
elif (currentT==FLTMDI and currentD!=FLTMDI) and (newT!=FLTMDI):
# if overwriting, only do so with observation closer to time stamp
if input_station_id[time_loc] == raw_station: # tests if already read into this time stamp
if last_obs_time != 0.: # not really necessary as already have at least 1 obs, but still...
# if time stamp closer than last one
if np.abs(TimeStamps[time_loc]-obs_time) < np.abs(TimeStamps[time_loc]-last_obs_time):
Extract=True
# have T but no D, and new observation comes up with T, select if closer
elif (currentT!=FLTMDI and currentD==FLTMDI) and (newT!=FLTMDI):
# if overwriting, only do so with observation closer to time stamp
if input_station_id[time_loc] == raw_station: # tests if already read into this time stamp
if last_obs_time != 0.: # not really necessary as already have at least 1 obs, but still...
# if time stamp closer than last one
if np.abs(TimeStamps[time_loc]-obs_time) < np.abs(TimeStamps[time_loc]-last_obs_time):
Extract=True
# if already have T and D, and new one also has T and D, but at closer time stamp, take this line
# this is an overwrite - so also check that overwriting with the same station
elif (currentT!=FLTMDI and currentD!=FLTMDI) and (newT!=FLTMDI and newD!=FLTMDI):
if input_station_id[time_loc] == raw_station:
if last_obs_time != 0.: # not really necessary as already have at least 1 obs, but still...
# if time stamp closer than last one
if np.abs(TimeStamps[time_loc]-obs_time) < np.abs(TimeStamps[time_loc]-last_obs_time):
Extract=True
else:
Extract=False # just in case
# sort last obs_time -
last_obs_time=obs_time
if input_station_id[time_loc]=='null':
input_station_id[time_loc]=raw_station
# main variables
dummyflag=0
# if allowed to extract:
if Extract:
ExtractionProcess(temperatures, temperature_flags,time_loc,FLTMDI,'+9999',cleanline,87,5, divisor=10.)
if Extract:
ExtractionProcess(dewpoints, dewpoint_flags,time_loc,FLTMDI,'+9999',cleanline,93,5, divisor=10.)
if Extract:
ExtractionProcess(slp, slp_flag,time_loc,FLTMDI,'99999',cleanline,99,5, divisor=10.)
if Extract:
ExtractionProcess(winddirs, winddirs_flags,time_loc,INTMDI,'999',cleanline,60,3)
if Extra:
ExtractionProcess(windtypes, dummyflag, time_loc,'','-',cleanline,64,1,doflag=False)
if Extract:
ExtractionProcess(windspeeds, windspeeds_flags,time_loc,FLTMDI,'9999',cleanline,65,4, divisor=10.)
if Extract:
ExtractionProcess(cloud_base, cloud_base_flags,time_loc,INTMDI,'99999',cleanline,70,5)
# Optional Variables - need to hunt for start point
# CLOUDs
text_ident='GF1'
exists=cleanline.find(text_ident)
if exists!=-1:
try:
if RepresentsInt(cleanline[exists+3]):
if Extract:
ExtractionProcess(total_cloud_cover, total_cloud_flags,time_loc,INTMDI,'99',cleanline,
exists+3,2,flagoffset=2)
if Extract:
ExtractionProcess(low_cloud_cover, low_cloud_flags,time_loc,INTMDI,'99',cleanline,
exists+8,2)
except IndexError:
# string following data marker doesn't exist
if dubious_flagged==0:
dubious_flagged=WriteDubious(dubiousfile,rfile,text_ident, station, string_obs_time)
elif dubious_flagged==0:
dubious_flagged=WriteDubious(dubiousfile,rfile,text_ident, station, string_obs_time)
text_ident='GA1'
exists_overall=cleanline.find(text_ident)
if exists_overall!=-1:
cloud_amts=np.array([INTMDI for i in range(6)])
cloud_hghts=np.array([INTMDI for i in range(6)])
cloud_flags=np.array([INTMDI for i in range(6)])
flagvals=['GA1','GA2','GA3','GA4','GA5','GA6']
for cl,flg in enumerate(flagvals):
exists=cleanline.find(flg)
if exists!=-1:
try:
if RepresentsInt(cleanline[exists+3]):
if Extract:
ExtractionProcess(cloud_amts, cloud_flags,cl,INTMDI,'99',cleanline,
exists+3,2)
ExtractionProcess(cloud_hghts, dummyflag,cl,INTMDI,'+99999',cleanline,
exists+6,6,doflag=False)
# remove hard coded values?
if cloud_hghts[cl]!=INTMDI:
if cloud_hghts[cl]<=2000:
cloud_hghts[cl]=1
elif cloud_hghts[cl]>=6000:
cloud_hghts[cl]=3
elif cloud_hghts[cl]>=4:
cloud_hghts[cl]=2
except IndexError:
# string following data marker doesn't exist
if dubious_flagged==0:
dubious_flagged=WriteDubious(dubiousfile,rfile,text_ident+'-'+flg, station, string_obs_time)
elif dubious_flagged==0:
dubious_flagged=WriteDubious(dubiousfile,rfile,text_ident+'-'+flg, station, string_obs_time)
# end for loop
SortClouds(total_cloud_cover, total_cloud_flags, time_loc, cloud_amts, cloud_flags, range(len(cloud_amts))) # select all using this slice
lowclouds=np.where(np.array(cloud_hghts) == 1)[0]
SortClouds(low_cloud_cover, low_cloud_flags, time_loc, cloud_amts, cloud_flags, lowclouds)
medclouds=np.where(np.array(cloud_hghts) == 2)[0]
SortClouds(mid_cloud_cover, mid_cloud_flags, time_loc, cloud_amts, cloud_flags, medclouds)
hiclouds=np.where(np.array(cloud_hghts) == 3)[0]
SortClouds(high_cloud_cover, high_cloud_flags, time_loc, cloud_amts, cloud_flags, hiclouds)
text_ident='GD1'
exists_overall=cleanline.find(text_ident)
if exists_overall!=-1:
if (total_cloud_cover[time_loc] == INTMDI):
cloud_amts=np.array([INTMDI for i in range(6)])
cloud_amts2=np.array([INTMDI for i in range(6)])
cloud_hghts=np.array([INTMDI for i in range(6)])
cloud_flags=np.array([INTMDI for i in range(6)])
flagvals=['GD1','GD2','GD3','GD4','GD5','GD6']
for cl,flg in enumerate(flagvals):
exists=cleanline.find(flg)
if exists!=-1:
try:
if RepresentsInt(cleanline[exists+3]):
if Extract:
# if TestToExtract(cloud_amts[cl],INTMDI,overwrite):
ExtractionProcess(cloud_amts, cloud_flags,cl,INTMDI,'9',cleanline,
exists+3,1,flagoffset=1)
if cloud_amts[cl] >= 5 :
cloud_amts[cl]=INTMDI
ExtractionProcess(cloud_amts2, dummyflag,cl,INTMDI,'99',cleanline,
exists+4,2,doflag=False)
ExtractionProcess(cloud_hghts, dummyflag,cl,INTMDI,'+99999',cleanline,
exists+7,6,doflag=False)
# remove hard coded values?
if cloud_hghts[cl]!=INTMDI:
if cloud_hghts[cl]<=2000:
cloud_hghts[cl]=1
elif cloud_hghts[cl]>=6000:
cloud_hghts[cl]=3
elif cloud_hghts[cl]>=4:
cloud_hghts[cl]=2
except IndexError:
# string following data marker doesn't exist
if dubious_flagged==0:
dubious_flagged=WriteDubious(dubiousfile,rfile,text_ident+'-'+flg, station, string_obs_time)
elif dubious_flagged==0:
dubious_flagged=WriteDubious(dubiousfile,rfile,text_ident+'-'+flg, station, string_obs_time)
# end for loop
SortClouds2(total_cloud_cover, total_cloud_flags, time_loc, cloud_amts, cloud_amts2, cloud_flags, range(len(cloud_amts))) # select whole list with slice
lowclouds=np.where(np.array(cloud_hghts) == 1)[0]
if len(lowclouds)>=1:
SortClouds2(low_cloud_cover, low_cloud_flags, time_loc, cloud_amts, cloud_amts2, cloud_flags, lowclouds)
medclouds=np.where(np.array(cloud_hghts) == 2)[0]
if len(medclouds)>=1:
SortClouds2(mid_cloud_cover, mid_cloud_flags, time_loc, cloud_amts, cloud_amts2, cloud_flags, medclouds)
hiclouds=np.where(np.array(cloud_hghts) == 3)[0]
if len(hiclouds)>=1:
SortClouds2(high_cloud_cover, high_cloud_flags, time_loc, cloud_amts, cloud_amts2, cloud_flags, hiclouds)
# PAST-SIGWX
text_ident='AY1'
exists=cleanline.find(text_ident)
if exists!=-1:
try:
if RepresentsInt(cleanline[exists+3]):
if Extract:
ExtractionProcess(past_sigwx1, past_sigwx1_flag,time_loc,INTMDI,'-',cleanline,
exists+3,1)
ExtractionProcess(past_sigwx1_period, dummyflag,time_loc,INTMDI,'99',cleanline,
exists+5,2,doflag=False)
except IndexError:
if dubious_flagged==0:
dubious_flagged=WriteDubious(dubiousfile,rfile,text_ident, station, string_obs_time)
elif dubious_flagged==0:
dubious_flagged=WriteDubious(dubiousfile,rfile,text_ident, station, string_obs_time)
text_ident='AZ1'
exists=cleanline.find(text_ident)
if exists!=-1:
try:
if RepresentsInt(cleanline[exists+3]):
if Extract:
ExtractionProcess(past_sigwx1, past_sigwx1_flag,time_loc,INTMDI,'-',cleanline,
exists+3,1)
ExtractionProcess(past_sigwx1_period, dummyflag,time_loc,INTMDI,'99',cleanline,
exists+5,2,doflag=False)