-
Notifications
You must be signed in to change notification settings - Fork 0
/
toolv4.1.py
1782 lines (1523 loc) · 63.1 KB
/
toolv4.1.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
## Essential Climate Variable Analysis Tool V2
## Version 1.6.2 - 29/09/20 - 09:45
## Version 2.0 - 22/01/21 - 12:28
## Version 3 - 05/05/21 - 13:51
## Version 4 - 30/06/21
# - Updated Calculations for efficiency and readability
# - Added multiple types of graph solutions
# - Upgraded to using np.arrays
# - Added .pci as operand functionality (for batch submissions)
## Daniel Westwood - [email protected]
## NetCDF4
from netCDF4 import Dataset
## Matplotlib Packages
from mpl_toolkits.basemap import Basemap
from matplotlib.patches import Path, PathPatch
from matplotlib import colors
import matplotlib.widgets as wg
import matplotlib as m
import matplotlib.ticker as ticker
m.use('TkAgg') ## Faster rendering
import matplotlib.image as mpimg
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
#import matplotlib.path as Path
## System
import os
import sys
from datetime import datetime
from getopt import getopt
## Shape
import shapely.affinity
from shapely.geometry import Point, Polygon
## Numpy
import numpy as np
import numpy.ma as ma
import warnings
import math
# Standard dw package tools
STD_PY_LOC = '/home/users/dwest77/dwest77_RSG/std_py'
try:
sys.path.append(STD_PY_LOC)
import find_files as ff
import pmath as pm
import output_data as od
except:
print('ImportError: Std_py library missing: requires find_files.py, pmath.py and output_data.py as minimum')
sys.exit()
## --- Global Variables --- ##
ECV_IDS = ['erb', 'srb', 'cld']
# Dictionary giving alignment to title
TITLE_DICT = { 'fontsize':'large',
'fontweight':'normal',
'color':'black',
'verticalalignment':'baseline',
'horizontalalignment':'center'}
# Transform integer month value to different formats
MONTHS = { 1:'01', 2:'02', 3:'03', 4:'04', 5:'05', 6:'06',
7:'07', 8:'08', 9:'09', 10:'10', 11:'11', 12:'12'}
CAL_MONTHS = { 1:'Jan',2:'Feb',3:'Mar',4:'Apr',5:'May',6:'Jun',
7:'Jul',8:'Aug',9:'Sep',10:'Oct',11:'Nov',12:'Dec'}
MONTH_CONTENT = [31,28,31,30,31,30,31,31,30,31,30,31]
# Imported data from config giles
FILE_PATHS = ff.get_from_file('config/','file_std_roots','.con')
ECV_SET_DICT = ff.get_from_file('config/','ecv_sets','.con')
# General Variables
VERBOSE = False
LENFIG = 4
WIDFIG = 8
# Single set of figures with map and graph
# 1 - Single Fig (Map or Graph)
# 2 - Vertical Figs (Map and Graph)
# 3 - Horizontal Figs (Maps)
# 4 - Triple Fig (Maps and Graph)
# 5 - Quadruple Fig (Maps and Graphs)
MAP_FORMATS = [
[ [0.15, 0.2, 0.7, 0.7] ], # Single Fig
[ [0.05, 0.5, 0.9, 0.45] ], # Vertical Fig
[ [0.02,0.2,0.55,0.7], [0.57,0.2,0.45,0.7] ], # Horizontal Fig
[ [0.02,0.5,0.45,0.45], [0.52,0.5,0.45,0.45] ], # Triple Fig
[ [0.05,0.55,0.4,0.4], [0.55,0.55,0.4,0.4] ] ] # Quadruple Fig
CBAR_FORMATS = [
[ [0.25,0.12,0.5,0.02] ],
[ [0.8,0.4,0.15,0.15] ],
[ [0.15,0.15,0.3,0.02], [0.65,0.15,0.3,0.02] ], # Triple Fig - No HFig Yet
[ [0.12,0.47,0.25,0.02], [0.62,0.47,0.25,0.02] ], # Triple Fig
[ [0.12,0.5,0.25,0.02], [0.62,0.5,0.25,0.02] ] ] # Quadruple Fig
GRAPH_FORMATS = [
[ [0.15, 0.2, 0.7, 0.7] ], # Single Fig
[ [0.1,0.15,0.8,0.25] ], # Vertical Fig
[ [0.02,0.5,0.45,0.45], [0.52,0.5,0.45,0.45] ], # Triple Fig - No HFig Proper Yet
[ [0.1,0.15,0.8,0.25] ], # Triple Fig
[ [0.05,0.1,0.4,0.3], [0.55,0.1,0.4,0.3] ] ] # Quadruple Fig
RAL_LOGOS = [
[ [0.04,0.1,0.15,0.15] ], # Single
[ [0.05,0.4,0.15,0.15] ], # Vertical
[ [0.05,0.4,0.15,0.15] ], # No HFig Proper yet
[ [0.05,0.4,0.15,0.15] ], # No Triple Fig proper
[ [0.05,0.4,0.15,0.15] ] ] # No Quadruple Fig proper
CCI_LOGOS = [
[ [0.78,0.1,0.2,0.15] ], # Single
[ [0.8,0.4,0.15,0.15] ], # Vertical
[ [0.8,0.4,0.15,0.15] ], # No HFig Proper yet
[ [0.8,0.4,0.15,0.15] ], # No Triple Fig proper
[ [0.8,0.4,0.15,0.15] ] ] # No Quadruple Fig proper
## --- Standard Tools --- ##
def identify_c3s_instrument(year, month, instrument): # ECV Class
# Takes year and month as input
# Determines which instrument the data was recorded by due to the date range
# Assumes c3s instrument - for other instruments, need more identify functions
# Operating Ranges of three known c3s instruments
atsr2 = ((year > 1995 and year < 2002) or (year == 1995 and month >= 6) or (year == 2002 and month <= 4))
aatsr = ((year > 2002 and year < 2012) or (year == 2002 and month >= 5) or (year == 2012 and month <= 4))
slstr = (year >= 2017)
if slstr:
if 'slstr' in instrument:
return instrument
else:
return 'slstra'
elif aatsr:
return 'aatsr'
elif atsr2:
return 'atsr2'
else:
return None
def console_intro(): # keep
# Simple console interface - welcome message
print('''
--- > Essential Climate Variable Analysis tool V4 < ---
--- Dev: Daniel Westwood (29/09/2020)
--- Updates: V2 (19/01/2021)
--- V3 (05/05/2021)
--- V4 (01/07/2021)
Required: config files
pci file
''')
## --- End standard tools --- ##
## --- ECV Reading class --- ##
class ecv_reading(): # Single data scene
# Set general properties of ecv reading object
def __init__(self, year, month, day, timeinc, isanom):
# Defines properties of single ecv/scene
# Runs import_data to obtain properties from corresponding netcdf file
# Single value properties:
# - year, month, day
# - isanom
# - date_index
# - timeinc
# Double value (multi-ecv) properties:
# - family, instrument
# - daynight, landsea
# - ecv/variable
# - label, spc, pre_units
# - ncf, basedata, baseunits
# - is_valid
# - lat/lon values (6)
self.year = year
self.month = month
self.day = day
self.isanom = isanom
self.date_index = None
self.timeinc = timeinc # Monthly or Daily
# Set other properties of ecv reading object
def set_ecv_properties(self,ecvs, ecv_sets, families, instruments, labels, spcs, pre_units, vinfos):
self.ecvs = ecvs # actual variable to study
self.ecv_sets = ecv_sets # variable superset (srb, erb, cld)
self.families = families # family of instruments (c3s, cris, iasi)
self.instruments = instruments # instrument subset of family (atsr2, aatsr, slstr etc.)
self.labels = labels # Additions to variable names (adjusted 'A/B')
self.spcs = spcs # Special case keys
self.pre_units = pre_units # Replacement/supplementary units
self.vinfos = vinfos
self.is_valid = [True for int in range(len(self.ecvs))]
self.basedata = [[] for int in range(len(self.ecvs))]
self.baseunits = [None for int in range(len(self.ecvs))]
self.latlist = [None for int in range(len(self.ecvs))]
self.lonlist = [None for int in range(len(self.ecvs))]
self.lat_min = [None for int in range(len(self.ecvs))]
self.lat_max = [None for int in range(len(self.ecvs))]
self.lon_min = [None for int in range(len(self.ecvs))]
self.lon_max = [None for int in range(len(self.ecvs))]
self.all_imports = []
def set_map_properties(self, daynights, landseas):
if daynights != None:
self.daynights = daynights
else:
self.daynights = ['day' for int in range(len(self.ecvs))]
self.landseas = landseas
# Sorting file paths and imports
def sort_file_imports(self):
base_path = ''
# all imports [ [ 0, path/for/import, 'lat', 'lon],
for index in range(len(self.ecvs)):
daynight_original = self.daynights[index]
if self.daynights[index] == 'day+night':
dn = ['day','night']
else:
dn = [self.daynights[index]]
for daynight in dn:
self.daynights[index] = daynight
variable = self.ecvs[index] + self.labels[index]
if self.instruments[index] == 'saved':
self.get_presaved_path(variable, index)
elif self.families[index] == 'esa_cci':
self.get_esa_cci_path(index)
elif self.families[index] == 'iasi':
self.get_iasi_path(index)
elif 'l2grid' in self.families[index]:
self.get_gridded_path(index)
elif 'l2os' in self.families[index]:
self.get_os_path(index)
elif self.families[index] == 'cris':
self.get_cris_path(index)
elif self.families[index] == 'cs':
self.get_custom_path(index)
else:
print('Warning: Unrecognised instrument family: {} - add pathfinder function at ln 258'.format(self.families[index]))
self.daynights[index] = daynight_original
self.sort_paths()
self.concat_all_basedata()
def sort_paths(self):
# Needs list of all indexes of variables
# Corresponding list of paths, 1 path per index
main_paths = {}
main_paths_list = []
main_lats = []
main_lons = []
latlonincs = []
for entry in self.all_imports:
index = entry[0]
path = entry[1]
try:
main_paths[path].append(index)
except:
main_paths[path] = [index]
main_paths_list.append(path)
main_lats.append(entry[2])
main_lons.append(entry[3])
latlonincs.append(entry[4])
for num, path in enumerate(main_paths_list):
print('Importing from ',path)
self.import_set_of_variables(path, main_paths[path], main_lats[num], main_lons[num], latlonincs[num])
# Extract and assemble data from different files
def concat_all_basedata(self):
for index in range(len(self.ecvs)):
if len(self.basedata[index]) == 0:
self.is_valid[index] = False
self.basedata[index] = np.nan
else:
'''
# Old method of averaging
bd_sum = 0
for repeat in range(len(self.basedata[index])):
bd_sum += np.array(self.basedata[index][repeat])
bd_sum = bd_sum/len(self.basedata[index])
'''
# New method of averaging
self.basedata[index] = np.array(self.basedata[index])
self.basedata[index][self.basedata[index] > 99999] = np.nan
self.basedata[index][self.basedata[index] < -99999] = np.nan
bd_sum = np.nanmean(self.basedata[index], axis=0)
self.basedata[index] = bd_sum
def import_set_of_variables(self, path, indexes, lat, lon, latloninc):
try:
ncf = Dataset(path, 'r', format = 'NETCDF4')
except:
print('Error: File not found {} - skipping'.format(path))
indexes = []
for index in indexes:
variable = self.ecvs[index]
self.latlist[index] = ncf.variables[lat][:]
self.lonlist[index] = ncf.variables[lon][:]
if self.spcs[index] == '20_nh3tpw': # Change later
nh3 = ncf['nh3']
tpw = ncf['tpw']
new = np.array(nh3) - (0.0016*np.array(tpw) + 0.21)/1000 # UK region values
self.basedata[index].append(new)
elif self.spcs[index] == '21_nh3tpw': # Change later
tpw = ncf['tpw']
vza = ncf['satzen']
new = np.array(tpw) / np.cos(np.array(vza) * (math.pi/180))
self.basedata[index].append(new)
elif self.spcs[index] == 'nh3tpwvza':
print('Applied adj')
nh3 = ncf['nh3']
tpw = ncf['tpw']
new = np.array(nh3) - (0.003*np.array(tpw) -0.06) # IASI gridded L2 value
self.basedata[index].append(new)
elif self.spcs[index] == '22_tpwvza':
tpw = ncf['tpw']
vza = ncf['satzen']
new = np.array(tpw) / np.cos(np.array(vza) * (math.pi/180))
self.basedata[index].append(new)
elif self.spcs[index] == '23_nh3tpwvza_nh3':
nh3tpwvza = np.array(ncf['nh3tpwvza'])
nh3 = np.array(ncf['nh3'])
diff = nh3tpwvza-nh3
self.basedata[index].append(diff)
elif self.spcs[index] != 'None' and self.spcs[index] != 'XT' and self.spcs[index] != '':
#variable = variable + self.labels[index]
ncf_var = ncf.variables[variable][:]
spc = int(self.spcs[index])
self.basedata[index].append(np.array(ncf_var[spc]))
else:
nvar = np.array(ncf.variables[variable][:])
self.basedata[index].append(np.array(ncf.variables[variable][:]))
try:
self.baseunits[index] = ncf.variables[variable].getncattr('units')
except:
self.baseunits[index] = ''
if latloninc:
self.lat_min[index] = ncf.getncattr('geospatial_lat_min')
self.lat_max[index] = ncf.getncattr('geospatial_lat_max')
self.lon_min[index] = ncf.getncattr('geospatial_lon_min')
self.lon_max[index] = ncf.getncattr('geospatial_lon_max')
else:
self.lat_min[index] = self.latlist[index][0]
self.lat_max[index] = self.latlist[index][len(self.latlist[index])-1]
self.lon_min[index] = self.lonlist[index][0]
self.lon_max[index] = self.lonlist[index][len(self.lonlist[index])-1]
# Assembly of file paths by instrument
def get_presaved_path(self, variable, index):
base_path = '/home/users/dwest77/Documents/ECV_Images/CRIS/{}'.format(variable)
main_path = base_path + '/{}_{}_{}_{}_{}{}.ncf'.format(self.families[index], variable, self.daynights[index], self.landseas[index], self.year, format(self.month,'02d'))
new_entry = [index, main_path, 'lat','lon', False]
self.all_imports.append(new_entry)
def get_gridded_path(self, index):
# Construct custom file path
month = format(self.month, '02d')
instrt = self.families[index].replace('_l2grid','')
main_path = '/gws/pw/j05/rsg_share/public/transfer/barry/6ad76b04-b3df-11eb-a4d3-024ad8e814ad/{}_l2/gridded_l2/{}/{}/{}/'.format(instrt, self.vinfos[index].split('_')[0], self.year, month)
filename = '{}_gridded_l2_{}{}{}_{}.nc'.format(instrt, self.year, month, self.daynights[index], self.vinfos[index]) # Change sub version
new_entry = [index, main_path+filename, 'lat','lon', False]
self.all_imports.append(new_entry)
def get_custom_path(self, index):
# Construct custom file path
daystring = format(self.day,'02d')
month = format(self.month, '02d')
day = format(self.day, '02d')
main_path = '/home/users/dwest77/Documents/IASI_os_l3/NH3/{}/{}/IASI_nh3_Daily_cv9_v12_{}_{}_{}_day.nc'.format(self.year, month,
self.year, month, day)
new_entry = [index, main_path, 'lat','lon', False]
self.all_imports.append(new_entry)
def get_iasi_path(self, index):
# Construct iasi file path
iasi_root_file = FILE_PATHS['iasi_root_file']
if int(self.year) > 2016:
iasi_root_dir = FILE_PATHS['iasi_post16_dir']
else:
iasi_root_dir = FILE_PATHS['iasi_pre16_dir']
ym = '{}{}'.format(self.year, MONTHS[self.month])
main_path = iasi_root_dir + iasi_root_file.format(ym,self.daynights[index])
new_entry = [index, main_path, 'latitude','longitude', False]
self.all_imports.append(new_entry)
def get_os_path(self, index):
# Construct iasi os file path
month = format(self.month, '02d')
instrt = self.families[index].replace('_l2os','')
main_path = '/gws/pw/j05/rsg_share/public/transfer/barry/6ad76b04-b3df-11eb-a4d3-024ad8e814ad/{}_l2/oversampled_l2/{}/{}/{}/'.format(instrt, self.vinfos[index].split('_')[0], self.year, month)
filename = '{}_oversampled_l2_{}{}_{}_{}.nc'.format(instrt, self.year, month, self.daynights[index], self.vinfos[index]) # Change sub version
new_entry = [index, main_path+filename, 'lat','lon', False]
self.all_imports.append(new_entry)
def get_cris_path(self, index):
# Construct cris file path
cris_root_dir = FILE_PATHS['cris_root_dir']
cris_root_file = FILE_PATHS['cris_root_file']
ym = '{}{}'.format(self.year,MONTHS[self.month])
main_path = cris_root_dir + cris_root_file.format(ym,self.daynights[index])
new_entry = [index, main_path, 'latitude','longitude', False]
self.all_imports.append(new_entry)
def get_esa_cci_path(self, index):
# AATSR, ATSR2, SLSTRA, SLSTRB, SLSTRAB
instrument = identify_c3s_instrument(self.year, self.month, self.instruments[index])
doreplace = False
if instrument == 'slstrab':
instrument = 'slstra'
doreplace = True
elif instrument == None:
self.is_valid[index] = False
print('File outside of time range - {}/{} - skipping'.format(self.year, self.month))
return None
# time increment part
tinc = self.timeinc.upper()
time_inc_file = tinc + '-'
time_inc_path = tinc.lower() + '/'
file_date = '{}{}'.format(self.year,MONTHS[self.month])
path_date = '{}/{}/'.format(self.year, MONTHS[self.month])
if self.timeinc == 'Daily':
day = format(self.day,'02d')
file_date += '{}'.format(day)
c3s_root_dir = FILE_PATHS['c3s_root_dir']
c3s_root_file = FILE_PATHS['c3s_root_file']
ext_path = FILE_PATHS['{}_path'.format(instrument)]
ext_files = FILE_PATHS['{}_file'.format(instrument)]
# replace 3a with 3b
if type(ext_files) != list:
ext_files = [ext_files]
# Fully assembled file dir
main_dir = c3s_root_dir + self.ecv_sets[index] + ext_path + time_inc_path + path_date
found_valid = False
file_count = 0
# Check all file names in list of possible names
while not found_valid and file_count < len(ext_files):
# Fully assembled file name
main_file = c3s_root_file + time_inc_file + FILE_PATHS[self.ecv_sets[index]] + ext_files[file_count].format(file_date)
main_path = main_dir + main_file
if os.path.isfile(main_path):
found_valid = True
file_count += 1
if not found_valid:
print('File not found for {}/{} - {} - skipping'.format(self.year, self.month, self.index))
self.is_valid[index] = False
return None
#
new_entry = [index, main_path, 'lat','lon', True]
self.all_imports.append(new_entry)
if doreplace:
new_entry = [index, main_path.replace('3a','3b'), 'lat','lon', True]
all_imports.append(new_entry)
## --- End ECV reading class --- ##
## --- ECV Analysis class --- ##
class ecv_analysis():
# Init function for user specified inputs
def __init__(self, plotconfig):
# Create ecv reading list of ecv instances
# Determine plot config info (default settings or from config file)
# -- Bools -- #
self.use_ral = False
self.use_cci = False
self.output_figures = plotconfig['OutFigs'] # Temp
# -- Strings -- #
self.time_format = plotconfig['TimeFormat'] # Single, Range, Days, Months
self.time_increment = plotconfig['TimeIncrement'] # Monthly/Daily
self.calculate = plotconfig['Calculate']
self.color = plotconfig['Color']
# -- Nums -- #
self.timegroupsize = int(plotconfig['TimeGroupSize']) # Number of readings to group for use in graph
self.fignum = int(plotconfig['FigureNumber'])
self.alpha = float(plotconfig['Alpha'])
# --- Time parameters --- #
self.year_arr = [int(yr) for yr in plotconfig['Years']]
self.month_arr = [int(mth) for mth in plotconfig['Months']]
if self.time_increment == 'Daily':
self.day_arr = [int(day) for day in plotconfig['Days']]
else:
self.day_arr = ''
if self.calculate == 'Anomaly':
self.anomyear_arr = [int(yr) for yr in plotconfig['AnomalyYears']]
self.anommonth_arr = [int(mth) for mth in plotconfig['AnomalyMonths']]
if self.time_increment == 'Daily':
self.anomdays_arr = [int(day) for day in plotconfig['AnomalyDays']]
else:
self.anomdays_arr = ''
else:
self.anomyear_arr = ''
self.anommonth_arr = ''
self.anomdays_arr = ''
if type(plotconfig['ecv']) != list:
self.ecvs = [plotconfig['ecv']]
else:
self.ecvs = plotconfig['ecv']
if type(plotconfig['ecv-set']) != list:
self.ecv_sets = [plotconfig['ecv-set']]
else:
self.ecv_sets = plotconfig['ecv-set']
if type(plotconfig['Family']) != list:
self.families = [plotconfig['Family']]
else:
self.families = plotconfig['Family']
# -- ECV Defined Arrays -- #
self.ecv_reading_list = [] # Array of reading objects
self.data_bounds = [[] for int in range(len(self.ecvs))] # Boundaries of data from lat/lon restrictions
self.graph_data_bounds = [[] for int in range(len(self.ecvs))] # Lat/Lon Boundaries
self.units = [None for int in range(len(self.ecvs))]
self.graph_data = [[] for int in range(len(self.ecvs))] # Data for graph
self.graph_data_count = [[] for int in range(len(self.ecvs))]
self.graph_data_dates = [[] for int in range(len(self.ecvs))] # Dates applied to graph
self.graph_data_errs = [[] for int in range(len(self.ecvs))]
self.data_calculated = [[] for int in range(len(self.ecvs))] # Post-calculations data
self.data_final = [[] for int in range(len(self.ecvs))] # Final Data set to be plotted
self.running_max = [-99999 for int in range(len(self.ecvs))]
self.running_min = [99999 for int in range(len(self.ecvs))]
self.scale = [None for int in range(len(self.ecvs))]
self.pre_units = [None for int in range(len(self.ecvs))]
self.scale_off = [None for int in range(len(self.ecvs))]
self.isvaluebound = [False for int in range(len(self.ecvs))]
self.value_bounds = [[] for int in range(len(self.ecvs))]
try:
self.extension = plotconfig['Extension']
except:
self.extension = ''
try:
self.fileexport = plotconfig['FileExport']
except:
self.fileexport = ''
try:
if type(plotconfig['Vinfo']) != list:
self.vinfos = [plotconfig['Vinfo']]
else:
self.vinfos = plotconfig['Vinfo']
except:
self.vinfos = ['' for i in range(len(self.ecvs))]
try: # Number of bins
self.nbins = int(plotconfig['NBins'])
if self.nbins == 0:
self.togglebins = False
else:
self.togglebins = True
except:
self.nbins = 0
self.togglebins = False
try: # Graph Format
self.graphformat = plotconfig['GraphFormat']
if self.graphformat in ['','None','none']:
self.graphformat = 'Straight'
except:
self.graphformat = 'Straight'
# -- ECV User Arrays -- #
# Special Case Keys
try:
if type(plotconfig['SpecialCaseKey']) != list:
self.spcs = [plotconfig['SpecialCaseKey']]
else:
self.spcs = plotconfig['SpecialCaseKey']
for spc in self.spcs:
if spc in ['','None','none']:
spc = None
except:
print('Warning: Special case keys missing')
self.spcs = ['' for int in range(len(self.ecvs))]
# Daynights
try:
if type(plotconfig['DayNight']) != list:
self.daynights = [plotconfig['DayNight']]
else:
self.daynights = plotconfig['DayNight']
except:
print('Warning: Daynights missing')
self.daynights = ['day' for int in range(len(self.ecvs))]
# Landseas
try:
if type(plotconfig['LandSea']) != list:
self.landseas = [plotconfig['LandSea']]
else:
self.landseas = plotconfig['LandSea']
except:
print('Warning: Landseas missing')
self.landseas = ['land+sea' for int in range(len(self.ecvs))]
# Instruments
try:
if type(plotconfig['Instrument']) != list:
self.instruments = [plotconfig['Instrument']]
else:
self.instruments = plotconfig['Instrument']
except:
print('Warning: Instruments missing')
self.instruments = ['' for int in range(len(self.ecvs))]
try:
if type(plotconfig['Label']) != list:
self.labels = [plotconfig['Label']]
else:
self.labels = plotconfig['Label']
except:
print('Warning: Labels missing')
self.labels = ['' for int in range(len(self.ecvs))]
try: # Graph Errors
if plotconfig['GraphErrors'] == 'y':
self.iserrorgraph = True
else:
self.iserrorgraph = False
except:
self.iserrorgraph = False
try:
if type(plotconfig['ScaleFactor']) == list:
self.scale = [float(sf) for sf in plotconfig['ScaleFactor']]
self.pre_units = plotconfig['ScaleCoeff']
self.scale_off = [float(so) for so in plotconfig['ScaleOffset']]
else:
self.scale = [float(plotconfig['ScaleFactor'])]
self.pre_units = [plotconfig['ScaleCoeff']]
self.scale_off = [float(plotconfig['ScaleOffset'])]
except:
print('Warning: Scales, offsets and units missing')
self.scale = [1 for int in range(len(self.ecvs))]
self.pre_units = ['' for int in range(len(self.ecvs))]
self.scale_off = [0 for int in range(len(self.ecvs))]
# -- Bools -- #
self.mapgraph = plotconfig['MapGraph']
self.ismap = [False for int in range(len(self.ecvs))]
self.ismapbound = [False for int in range(len(self.ecvs))]
self.isgraph = [False for int in range(len(self.ecvs))]
self.isgraphbound = [False for int in range(len(self.ecvs))]
self.map_bounds = [[] for index in range(len(self.ecvs))]
self.user_map_bounds = [[] for index in range(len(self.ecvs))]
self.graph_bounds = [[] for index in range(len(self.ecvs))]
self.user_graph_bounds = [[] for index in range(len(self.ecvs))]
## Set map and graph bounds ##
# Assemble graph bounds
if self.mapgraph in ['map+graph', 'graph']:
self.isgraph = [True for int in range(len(self.ecvs))]
bounds = plotconfig['GraphBounds']
bounds_nest = []
bds = []
for idx, bound in enumerate(bounds):
bds.append(float(bound))
if (idx+1)%4 == 0:
bounds_nest.append(bds)
bds = []
for index in range(len(self.ecvs)):
if plotconfig['GraphCon'][index] == 'y':
self.isgraphbound[index] = True
self.user_graph_bounds[index] = bounds_nest[index]
else:
self.isgraphbound[index] = False
self.user_graph_bounds[index] = []
# Assemble map bounds
if self.mapgraph in ['map+graph','map']:
self.ismap = [True for int in range(len(self.ecvs))]
bounds = plotconfig['MapBounds']
bounds_nest = []
bds = []
for idx, bound in enumerate(bounds):
bds.append(float(bound))
if (idx+1)%4 == 0:
bounds_nest.append(bds)
bds = []
for index in range(len(self.ecvs)):
if plotconfig['MapCon'][index] == 'y':
self.ismapbound[index] = True
self.user_map_bounds[index] = bounds_nest[index]
else:
self.ismapbound[index] = False
self.user_map_bounds[index] = []
try:
if type(plotconfig['ValueCon']) != list:
if plotconfig['ValueCon'] == 'y':
self.isvaluebound = [True]
self.value_bounds = [[float(bound) for bound in plotconfig['ValueBounds']]]
else:
self.isvaluebound = [False]
self.value_bounds = [[0,0,0,0]]
else:
for ivbs in range(len(plotconfig['ValueCon'])):
if plotconfig['ValueCon'][ivbs] == 'y':
self.isvaluebound[ivbs] = True
self.value_bounds[ivbs] = [float(plotconfig['ValueBounds'][ivbs*4 + i]) for i in range(4)]
else:
self.isvaluebound[ivbs] = False
self.value_bounds[ivbs] = [0,0,0,0]
except:
self.isvaluebound = [False for int in range(len(self.ecvs))]
self.value_bounds = [[0,0,0,0] for int in range(len(self.ecvs))]
if plotconfig['ShowOutput'] == 'y':
self.isshow = True
else:
self.isshow = False
if plotconfig['PNGExport'] == 'y':
self.ispngexport = True
try:
self.saveto = plotconfig['SaveTo']
except:
self.saveto = ''
else:
self.ispngexport = False
self.saveto = ''
self.doparts = plotconfig['DoParts']
try:
self.graphname = plotconfig['GraphName']
except:
self.graphname = ''
self.graph_type = plotconfig['GraphType']
#self.ecv_map_example = [None for int in range(len(self.ecvs))]
if self.isshow or self.ispngexport:
self.main()
else:
print('Output method is not defined, please specify png export or show output')
# Main function for analysis
def main(self):
# Defines output layout - config file later
# Flow of processes:
# - get ecvs (data)
# - perform calculations
# - output results
# May later be deconstructed so not all files need to be loaded all together (rearrangement)
print('Starting Main')
if 'Calculate' in self.doparts:
# Retrieve ecv readings
is_abort = self.ecv_retrieval()
if is_abort:
print('Error: No valid ecv readings - no files selected could be read')
return None
# Organise readings into groups
if self.calculate != '':
self.create_groups()
# Set map boundaries
self.get_units()
self.ecv_examples = [self.find_valid_ecv_example(index) for index in range(len(self.ecvs))]
# Perform calculations on ecv array - groups are irrelevant for calculations
for index in range(len(self.ecvs)):
self.calculations(index)
if 'ImportGraph' in self.doparts:
self.import_graph()
self.get_units()
if 'ExportGraph' in self.doparts:
self.export_graph()
if 'ExportMap' in self.doparts:
self.export_map_as_netcdf()
if 'ImportMap' in self.doparts:
self.import_map_as_netcdf()
self.get_units()
for index in range(len(self.ecvs)):
self.apply_value_bounds(index)
self.map_bounds[index] = self.user_map_bounds[index]
self.data_bounds[index] = [0, len(self.data_final[index]), 0, len(self.data_final[index][0])]
if 'Plot' in self.doparts:
self.assemble_outputs()
return None
# Assembly of output figures
def assemble_outputs(self):
# Single Fig (4x6)
# Vertical Fig (8x6)
# Horizontal Fig (4x12)
# Triple Fig (8x12)
# Quadruple Fig (8x12)
fig_options = ['Single','Vertical','Horizontal','Triple','Quadruple']
double_fig_height = ['Vertical','Triple','Quadruple']
double_fig_width = ['Horizontal','Triple','Quadruple']
figure_index = None
for index, option in enumerate(fig_options):
if option == self.output_figures:
figure_index = index
if figure_index == None:
print('Error: Invalid Figure Option in input -',self.output_figures)
return None
if self.output_figures in double_fig_height:
figheight = LENFIG*2
else:
figheight = LENFIG
if self.output_figures in double_fig_width:
figwidth = WIDFIG*2
else:
figwidth = WIDFIG
self.out_fig = plt.figure(figsize=(figwidth,figheight))
self.out_fig.set_facecolor('white')
self.out_fig.canvas.set_window_title('ECV L3 Map/Graph Tool')
# Maps and Graphs
if 'map' in self.mapgraph:
self.map_control(figure_index)
if 'graph' in self.mapgraph:
self.graph_control(figure_index)
# adding logos routine
# self.show_logos(figure_index)
if self.ispngexport:
self.png_export()
if self.isshow:
plt.show()
plt.close()
return None
# Control of map plots
def map_control(self, figure_index):
two_maps = ['Horizontal','Triple','Quadruple']
if self.output_figures in two_maps:
number_of_maps = 2
else:
number_of_maps = 1
for nm in range(number_of_maps):
if self.calculate == 'Anomaly':
unit_label = '{} Anomaly ({})'.format(self.ecvs[nm], '%')
elif self.calculate == 'Trend':
unit_label = '{} Trend ({})'.format(self.ecvs[nm], self.units[nm] + ' y-1')
else:
unit_label = '{} Mean ({})'.format(self.ecvs[nm], self.units[nm])
res = (self.map_bounds[nm][1]-self.map_bounds[nm][0])/len(self.data_final[nm])
self.out_fig = od.output_map(self.out_fig, self.data_final[nm],
self.map_bounds[nm], res,
self.data_bounds[nm], self.value_bounds[nm],
map_axes = MAP_FORMATS[figure_index][nm],
cbar_axes = CBAR_FORMATS[figure_index][nm],
map_title = self.map_title(nm),
cbar_title = unit_label,
color = self.color,
alpha = self.alpha,
landsea = self.landseas[nm])
return None
# Control of graph plots
def graph_control(self, figure_index):
# Control Graph Inputs/Outputs
# Can be expanded using graph_type variable later
# Determines how many graphs are required
two_graphs = ['Horizontal','Quadruple']
if self.output_figures in two_graphs:
number_of_graphs = 2
else:
number_of_graphs = 1
# Plot all data on a single time series
# Plot separate data on different time series
# Plot two variable comparison
# Plot three variable comparison
# Graphtypes: SepTime, Time, Variable, 3D
if 'Time' in self.graph_type:
graph_titles = []
if 'SepTime' in self.graph_type:
for index in range(len(self.ecvs)):
graph_titles.append( self.graph_title([index]))
else:
graph_titles.append(self.graph_title([i for i in range(len(self.ecvs))]))
for index, graph_title in enumerate(graph_titles):
time_array = self.graph_data_dates[index] # For Completeness
ecv_label = self.ecvs[index] + self.labels[index] + ' ({})'.format(self.units[index])
if len(graph_titles) == 1:
graph_data = self.graph_data
graph_errs = self.graph_data_errs
axes = GRAPH_FORMATS[figure_index][0]
else: # Separated graphs
graph_data = [self.graph_data[index]]
graph_errs = [self.graph_data_errs[index]]
axes = GRAPH_FORMATS[figure_index][index]
self.out_fig = od.output_time_series(self.out_fig,
time_array, graph_data, graph_errs,
graph_title=graph_title,
graph_axes=axes,
graphformat=self.graphformat,
do_errs=self.iserrorgraph,
ylabel=ecv_label)
elif self.graph_type == 'Variable':
graph_title = self.graph_title([0,1])
xlabel = '{} ({})'.format(self.ecvs[0], self.units[0])
ylabel = '{} ({})'.format(self.ecvs[1], self.units[1])
self.out_fig = od.output_two_var_graph(self.out_fig,
np.array(self.graph_data), np.array(self.graph_data_errs),
graph_title=graph_title,
graph_axes=GRAPH_FORMATS[figure_index][0],
do_errs=self.iserrorgraph,
do_bins=self.togglebins,
nbins=self.nbins,
xlabel=xlabel,
ylabel=ylabel)
else:
print('Error: Unrecognised format - {}'.format(self.graph_type))
def export_graph(self):
# Need to export:
# self.graph_data[ecv_type]
# self.graph_data_dates
# self.graph_data_errs
gdt = 'g'
# Dates nh3values-unit tpwvalues-unit nh3errs tpwerrs
for index in range(len(self.ecvs)):
ecv_type = self.ecvs[index]
label = self.labels[index]
daynight = self.daynights[index]
family = self.families[index]
landsea = self.landseas[index]
yrs_mths = str(self.year_arr[0]) + str(self.year_arr[1]) + '_' + str(self.month_arr[0]) + str(self.month_arr[1])
base_path = '/home/users/dwest77/Documents/ECV_Images/output_files/graph_texts/{}'.format(ecv_type+label)
if not os.path.isdir(base_path):
os.makedirs(base_path)
output_file = '/{}_{}_{}_{}_{}{}.txt'.format(family, ecv_type+label, daynight, landsea, yrs_mths, gdt)
os.system('touch {}{}'.format(base_path, output_file))
f = open(base_path+output_file, 'w')
outstring = 'Dates, {}-{}, {}_errs\n'.format(ecv_type,self.units[index], ecv_type)
for index2 in range(len(self.graph_data[index])):
outstring += str(self.graph_data_dates[index][index2]) + ', '
outstring += str(self.graph_data[index][index2]) + ', '