-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgeosplot.py
More file actions
1325 lines (1106 loc) · 57.4 KB
/
geosplot.py
File metadata and controls
1325 lines (1106 loc) · 57.4 KB
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/bin/env python3
# Complete Automated testing framework script for the GEOS-Chem-hyd manuscript
import numpy as np
import xarray as xr
import matplotlib.pyplot as plt
from netCDF4 import Dataset
from matplotlib.backends.backend_pdf import PdfPages
from matplotlib import cm
from matplotlib.ticker import ScalarFormatter
from scipy import stats
import warnings
import gcpy.plot as gcplot
from cmcrameri import cm
# from gcpy.units import check_units, data_unit_is_mol_per_mol
import os
from joblib import Parallel, delayed
from matplotlib import colors
from matplotlib.colors import BoundaryNorm
from matplotlib.colors import ListedColormap
from matplotlib.colors import LinearSegmentedColormap
# Ignore warnings
warnings.filterwarnings("ignore")
# Reading Files
root_path = '/glade/work/sakinjole/rundirs/gc_4x5_merra2_fullchem'
species = 'NO'
specie1 = 'NO'
specie2 = 'O3'
duration = '1hr'
mechanism = 'fullchem_20_isop'
mechanism2 = 'fullchem_quad'
pert_layer = '/allcells' # else ground layer
#ptype = 'H'
ptype = 'S'
h1 = 0.20
hc = 0.20
h2 = 0.0001
print(mechanism)
# A dictionary for species variables and indices to plot (This serves as the numerator)
# Only for the species concentration diagnostic
# plot_species = {'CO':251, 'CO2':86, 'SO4':94, 'SO2':95, 'NO2':131, 'NO':132, 'O3':127, 'NH4': 135, 'NH3': 136}
#plot_species = {'CO': 251, 'SO4': 94, 'SO2': 95, 'NO2': 131, 'NO': 132, 'O3': 127,
# 'NH4': 135, 'NH3': 136, 'NIT': 134, 'HNO3': 217, 'HCl': 224, 'ISOP': 173}
plot_species = {'NO2': 131, 'O3': 127, 'NH4': 135, 'NIT': 134, 'HNO3': 217}
#hemco_species = {'EmisSO4_Total': 3, 'EmisNO2_Total': 10, 'EmisNO_Total': 11,
# 'EmisNH3_Total': 12, 'EmisCO_Total': 20}
hemco_species = {'EmisO3_Total': 10, 'EmisNO2_Total': 11, 'EmisNO_Total': 12, 'EmisHNO3_Total': 19}
# Avoid using gcpy for this:
def data_unit_is_mol_per_mol(da):
"""
Check if the units of an xarray DataArray are mol/mol based on a set
list of unit strings mol/mol may be.
Args:
da: xarray DataArray
Data array containing a units attribute
Returns:
is_molmol: bool
Whether input units are mol/mol
"""
conc_units = ["mol mol-1 dry", "mol/mol", "mol mol-1"]
is_molmol = False
if da.units.strip() in conc_units:
is_molmol = True
return is_molmol
def default_path(mechanism):
# Folder paths default run
real_path1 = root_path + '/default/' + mechanism2 + '/' + \
duration + '/GEOSChem.SpeciesConc.20190701_0000z.nc4'
hyd_path1 = root_path + '/default_hyd/' + mechanism2 + '/' + \
duration + '/GEOSChem.SpeciesConc.20190701_0000z.nc4'
real_path2 = root_path + '/default/' + mechanism2 + '/' + \
duration + '/GEOSChem.AerosolMass.20190701_0000z.nc4'
hyd_path2 = root_path + '/default_hyd/' + mechanism2 + '/' + \
duration + '/GEOSChem.AerosolMass.20190701_0000z.nc4'
# Read the arrays:
real1 = xr.open_dataset(real_path1)
hyd1 = xr.open_dataset(hyd_path1)
real2 = xr.open_dataset(real_path2)
hyd2 = xr.open_dataset(hyd_path2)
return real1, hyd1, real2, hyd2
def def_path(mechanism):
# Folder paths default run
real_path = root_path + '/first_output/' + mechanism + '/' + \
duration + pert_layer + '/def' + specie1 + '/HEMCO_diagnostics.201907010000.nc'
# Read the arrays:
real = xr.open_dataset(real_path)
return real
def main_path(ty, layer=''): # where ty stands for the order of operation
if ty == 'first':
if layer == '/allcells':
# Folder paths first order - updated to central difference
real_path = '/first_output/' + mechanism + '/' + \
duration + layer + '/dec' + specie1 + '/'
# pertreal_path = '/first_output/incNO/'
pertreal_path = '/first_output/' + mechanism + \
'/' + duration + layer + '/inc' + specie1 + '/'
# perthyd_path = '/second_output_hyd/perturbedNO_boxN/'
perthyd_path = '/first_output_hyd/' + mechanism + \
'/' + duration + layer + '/hyd' + specie1 + '/'
else:
# Folder paths first order - updated to central difference
real_path = '/first_output/' + mechanism + '/' + \
duration + '/ground/dec' + specie1 + '/'
# pertreal_path = '/first_output/incNO/'
pertreal_path = '/first_output/' + mechanism + \
'/' + duration + '/ground/inc' + specie1 + '/'
# perthyd_path = '/second_output_hyd/perturbedNO_boxN/'
perthyd_path = '/first_output_hyd/' + mechanism + \
'/' + duration + '/ground/hyd' + specie1 + '/'
elif ty == 'second':
if layer == '/allcells':
# Folder paths second order
real_path = '/second_output/' + mechanism + '/' + \
duration + layer + '/dec' + specie1 + '/'
pertreal_path = '/second_output/' + mechanism + \
'/' + duration + layer + '/inc' + specie1 + '/'
perthyd_path = '/second_output_hyd/' + mechanism + \
'/' + duration + layer + '/hyd' + specie1 + '/'
else:
# Folder paths second order
real_path = '/second_output/' + mechanism + \
'/' + duration + '/ground/dec' + specie1 + '/'
pertreal_path = '/second_output/' + mechanism + \
'/' + duration + '/gound/inc' + specie1 + '/'
perthyd_path = '/second_output_hyd/' + mechanism + \
'/' + duration + '/ground/hyd' + specie1 + '/'
elif ty == 'cross':
# Folder paths hybrid
if layer == '/allcells':
real_path = '/cross_output/' + mechanism + '/' + \
duration + layer + '/dec' + specie1 + '_' + specie2 + '/'
# hyd_path = '/hybrid_output_hyd/default'
pertreal_path = '/cross_output/' + mechanism + '/' + \
duration + layer + '/inc' + specie1 + '_' + specie2 + '/'
perthyd_path = '/cross_output_hyd/' + mechanism + '/' + \
duration + layer + '/hyd' + specie1 + '_' + specie2 + '/'
return real_path, pertreal_path, perthyd_path
# File paths
def file(ty, pt): # where ty is the diagnostic type, pt is the required path
if ty == 'A':
if pt == 'real':
return 'GEOSChem.AerosolMass.20190701_0000z.nc4'
elif pt == 'dx1':
return 'GEOSChem.AerosolMassdx1.20190701_0000z.nc4'
elif pt == 'dx2':
return 'GEOSChem.AerosolMassdx2.20190701_0000z.nc4'
elif pt == 'dx1x2':
return 'GEOSChem.AerosolMassdx1x2.20190701_0000z.nc4'
elif pt == 'isens':
return 'GEOSChem.Sensitivity.20190701_0000z.nc4'
elif ty == 'S':
if pt == 'real':
return 'GEOSChem.SpeciesConc.20190701_0000z.nc4'
elif pt == 'dx1':
return 'GEOSChem.SpeciesConcdx1.20190701_0000z.nc4'
elif pt == 'dx2':
return 'GEOSChem.SpeciesConcdx2.20190701_0000z.nc4'
elif pt == 'dx1x2':
return 'GEOSChem.SpeciesConcdx1x2.20190701_0000z.nc4'
elif pt == 'isens':
return 'GEOSChem.Sensitivity.20190701_0000z.nc4'
elif ty == 'H':
if pt == 'real':
return 'HEMCO_diagnostics.201907010000.nc'
elif pt == 'dx1':
return 'HEMCOdx1_diagnostics.201907010000.nc'
elif pt == 'dx2':
return 'HEMCOdx2_diagnostics.201907010000.nc'
elif pt == 'dx1x2':
return 'HEMCOdx1x2_diagnostics.201907010000.nc'
def read_file(loc):
'''Read the real files with xarray'''
return xr.open_dataset(loc)
# gets all file paths for a particular diagnostic
def get_file(array, order, real_path, pertreal_path, perthyd_path):
if array == 'A':
if order == 'first':
ref_real = read_file(root_path + real_path + file('A', 'real'))
ref_pert = read_file(root_path + pertreal_path + file('A', 'real'))
hyd_dx1 = read_file(root_path + perthyd_path + file('A', 'dx1'))
hyd_dx2 = read_file(root_path + perthyd_path + file('A', 'dx2'))
hyd_dx1x2 = read_file(
root_path + perthyd_path + file('A', 'dx1x2'))
# ipercent = read_file(root_path + perthyd_path + file('A', 'isens'))
elif order == 'second':
ref_real = read_file(root_path + real_path + file('A', 'dx2'))
ref_pert = read_file(root_path + pertreal_path + file('A', 'dx2'))
hyd_dx1 = read_file(root_path + perthyd_path + file('A', 'dx1'))
hyd_dx2 = read_file(root_path + perthyd_path + file('A', 'dx2'))
hyd_dx1x2 = read_file(
root_path + perthyd_path + file('A', 'dx1x2'))
# ipercent = read_file(root_path + perthyd_path + file('A', 'isens'))
elif array == 'S':
if order == 'first':
ref_real = read_file(root_path + real_path + file('S', 'real'))
ref_pert = read_file(root_path + pertreal_path + file('S', 'real'))
hyd_dx1 = read_file(root_path + perthyd_path + file('S', 'dx1'))
hyd_dx2 = read_file(root_path + perthyd_path + file('S', 'dx2'))
hyd_dx1x2 = read_file(
root_path + perthyd_path + file('S', 'dx1x2'))
# ipercent = read_file(root_path + perthyd_path + file('S', 'isens'))
# ipercentb = read_file(root_path + real_path + file('S', 'isens'))
# ipercentf = read_file(root_path + pertreal_path + file('S', 'isens'))
elif order == 'second':
ref_real = read_file(root_path + real_path + file('S', 'dx2'))
ref_pert = read_file(root_path + pertreal_path + file('S', 'dx2'))
hyd_dx1 = read_file(root_path + perthyd_path + file('S', 'dx1'))
hyd_dx2 = read_file(root_path + perthyd_path + file('S', 'dx2'))
hyd_dx1x2 = read_file(
root_path + perthyd_path + file('S', 'dx1x2'))
# ipercent = read_file(root_path + perthyd_path + file('S', 'isens'))
# ipercentb = read_file(root_path + real_path + file('S', 'isens'))
# ipercentf = read_file(root_path + pertreal_path + file('S', 'isens'))
elif order == 'cross':
ref_real = read_file(root_path + real_path + file('S', 'dx2'))
ref_pert = read_file(root_path + pertreal_path + file('S', 'dx2'))
hyd_dx1 = read_file(root_path + perthyd_path + file('S', 'dx1'))
hyd_dx2 = read_file(root_path + perthyd_path + file('S', 'dx2'))
hyd_dx1x2 = read_file(
root_path + perthyd_path + file('S', 'dx1x2'))
# ipercent = read_file(root_path + perthyd_path + file('S', 'isens'))
# ipercentb = read_file(root_path + real_path + file('S', 'isens'))
# ipercentf = read_file(root_path + pertreal_path + file('S', 'isens'))
elif array == 'H':
if order == 'first':
ref_real = read_file(root_path + real_path + file('H', 'real'))
ref_pert = read_file(root_path + pertreal_path + file('H', 'real'))
hyd_dx1 = read_file(root_path + perthyd_path + file('H', 'dx1'))
hyd_dx2 = read_file(root_path + perthyd_path + file('H', 'dx2'))
hyd_dx1x2 = read_file(
root_path + perthyd_path + file('H', 'dx1x2'))
elif order == 'second':
ref_real = read_file(root_path + real_path + file('H', 'dx2'))
ref_pert = read_file(root_path + pertreal_path + file('H', 'dx2'))
hyd_dx1 = read_file(root_path + perthyd_path + file('H', 'dx1'))
hyd_dx2 = read_file(root_path + perthyd_path + file('H', 'dx2'))
hyd_dx1x2 = read_file(
root_path + perthyd_path + file('H', 'dx1x2'))
return ref_real, ref_pert, hyd_dx1, hyd_dx2, hyd_dx1x2
# return ref_real, ref_pert, hyd_dx1, hyd_dx2, hyd_dx1x2, ipercent, ipercentb, ipercentf
def full_path(order, array):
if order == 'first':
real_path, pertreal_path, perthyd_path = main_path('first', pert_layer)
elif order == 'second':
real_path, pertreal_path, perthyd_path = main_path(
'second', pert_layer)
elif order == 'cross':
real_path, pertreal_path, perthyd_path = main_path('cross', pert_layer)
# save the paths to be used later for the one to one plots
ref_real, ref_pert, hyd_dx1, hyd_dx2, hyd_dx1x2 = get_file(
array, order, real_path, pertreal_path, perthyd_path)
# ref_real, ref_pert, hyd_dx1, hyd_dx2, hyd_dx1x2 = get_file(array, order, real_path, pertreal_path, perthyd_path)
# ref_real, ref_pert, hyd_dx1, hyd_dx2, hyd_dx1x2, ipercent, ipercentb, ipercentf = get_file(array, order, real_path, pertreal_path, perthyd_path)
# return ref_real, ref_pert, hyd_dx1, hyd_dx2, hyd_dx1x2, real_path, pertreal_path, perthyd_path
return ref_real, ref_pert, hyd_dx1, hyd_dx2, hyd_dx1x2, perthyd_path
# return ref_real, ref_pert, hyd_dx1, hyd_dx2, hyd_dx1x2, perthyd_path, ipercent, ipercentb, ipercentf
# Run the main path here:
# Running all plots sequentially:
if ptype == 'S':
# ref_realf, ref_pertf, hyd_dx1f, hyd_dx2f, hyd_dx1x2f, real_pathf, pertreal_pathf, perthyd_pathf = full_path('first', 'S')
# ref_realf, ref_pertf, hyd_dx1f, hyd_dx2f, hyd_dx1x2f, perthyd_pathf, ipercent, ipercentb, ipercentf = full_path('first', 'S')
ref_realf, ref_pertf, hyd_dx1f, hyd_dx2f, hyd_dx1x2f, perthyd_pathf = full_path(
'first', 'S')
# ref_realfa, ref_pertfa, hyd_dx1fa, hyd_dx2fa, hyd_dx1x2fa, perthyd_pathfa, ipercenta = full_path('first', 'A')
# ref_reals, ref_perts, hyd_dx1s, hyd_dx2s, hyd_dx1x2s, perthyd_paths, ipercent2, ipercent2b, ipercent2f = full_path('second', 'S')
ref_reals, ref_perts, hyd_dx1s, hyd_dx2s, hyd_dx1x2s, perthyd_paths = full_path(
'second', 'S')
# ref_realc, ref_pertc, hyd_dx1c, hyd_dx2c, hyd_dx1x2c, real_pathc, pertreal_pathc, perthyd_pathc = full_path('cross', 'S')
elif ptype == 'A':
# ref_realf, ref_pertf, hyd_dx1f, hyd_dx2f, hyd_dx1x2f, perthyd_pathf, ipercent = full_path('first', 'A')
ref_realf, ref_pertf, hyd_dx1f, hyd_dx2f, hyd_dx1x2f, perthyd_pathf = full_path(
'first', 'A')
# ref_reals, ref_perts, hyd_dx1s, hyd_dx2s, hyd_dx1x2s, perthyd_paths, ipercent2 = full_path('second', 'A')
ref_reals, ref_perts, hyd_dx1s, hyd_dx2s, hyd_dx1x2s, perthyd_paths = full_path(
'second', 'A')
elif ptype == 'H':
ref_realf, ref_pertf, hyd_dx1f, hyd_dx2f, hyd_dx1x2f, perthyd_pathf = full_path(
'first', 'H')
ref_reals, ref_perts, hyd_dx1s, hyd_dx2s, hyd_dx1x2s, perthyd_paths = full_path(
'second', 'H')
#Run again with the new denominator, only needed once:
# old = specie1
# specie1 = specie2
# mechanism = 'fullchem_hemco_0.01'
# ref_realf2, ref_pertf2, hyd_dx1f2, hyd_dx2f2, hyd_dx1x2f2, perthyd_pathf2 = full_path(
# 'first', 'H')
# ref_reals2, ref_perts2, hyd_dx1s2, hyd_dx2s2, hyd_dx1x2s2, perthyd_paths2 = full_path(
# 'second', 'H')
#
# #Reassign specie1 to old name
# specie1 = old
#Default file path
#ref_reald = def_path(mechanism)
# full_path('second', 'A')
# full_path('hybrid', 'A')
# Get the default files
# default_file1, hyd_file1, default_file2, hyd_file2 = default_path(mechanism)
# add unit conversions to pbb from mol/mol
def unit_convert(ref_real, ref_pert, hyd_dx1, hyd_dx2, hyd_dx1x2, useless):
for i in ref_real:
if i in useless:
continue
else:
if data_unit_is_mol_per_mol(ref_real[i]):
ref_real[i].values = ref_real[i].values * 1e9
ref_real[i].attrs["units"] = "ppb"
for i in ref_pert:
if i in useless:
continue
else:
if data_unit_is_mol_per_mol(ref_pert[i]):
ref_pert[i].values = ref_pert[i].values * 1e9
ref_pert[i].attrs["units"] = "ppb"
for i in hyd_dx1:
if i in useless:
continue
else:
if data_unit_is_mol_per_mol(hyd_dx1[i]):
hyd_dx1[i].values = hyd_dx1[i].values * 1e9
hyd_dx1[i].attrs["units"] = "ppb"
for i in hyd_dx2:
if i in useless:
continue
else:
if data_unit_is_mol_per_mol(hyd_dx2[i]):
hyd_dx2[i].values = hyd_dx2[i].values * 1e9
hyd_dx2[i].attrs["units"] = "ppb"
for i in hyd_dx1x2:
if i in useless:
continue
else:
if data_unit_is_mol_per_mol(hyd_dx1x2[i]):
hyd_dx1x2[i].values = hyd_dx1x2[i].values * 1e9
hyd_dx1x2[i].attrs["units"] = "ppb"
return ref_real, ref_pert, hyd_dx1, hyd_dx2, hyd_dx1x2
# add unit conversions to pbb from mol/mol for one argument
def units_convert(array, useless):
for i in array:
if i in useless:
continue
else:
if data_unit_is_mol_per_mol(array[i]):
array[i].values = array[i].values * 1e9
array[i].attrs["units"] = "ppb"
return array
# Calculate finite differences
# Calculating the defined perturbation size for a variable
# To create an array of 0s to map each variable and iterate through
lev = 72
lat = 46
lon = 72
# Applies for both Species_Conc and aerosolMass
# useless variables in the array:
useless = ['lat_bnds', 'lon_bnds', 'hyam',
'hybm', 'hyai', 'hybi', 'P0', 'AREA']
num_var = len(ref_realf) - 8
# num_var = len(ref_reals) - 8
# comment out if not needed
# ref_real, ref_pert, hyd_dx1, hyd_dx2, hyd_dx1x2 = unit_convert(ref_real, ref_pert, hyd_dx1, hyd_dx2, hyd_dx1x2, useless)
# Running all sequentially:
ref_realf, ref_pertf, hyd_dx1f, hyd_dx2f, hyd_dx1x2f = unit_convert(
ref_realf, ref_pertf, hyd_dx1f, hyd_dx2f, hyd_dx1x2f, useless)
ref_reals, ref_perts, hyd_dx1s, hyd_dx2s, hyd_dx1x2s = unit_convert(
ref_reals, ref_perts, hyd_dx1s, hyd_dx2s, hyd_dx1x2s, useless)
# ref_realc, ref_pertc, hyd_dx1c, hyd_dx2c, hyd_dx1x2c = unit_convert(ref_realc, ref_pertc, hyd_dx1c, hyd_dx2c, hyd_dx1x2c, useless)
# Convert the default files to ppb:
# default_file1 = units_convert(default_file1, useless)
# default_file2 = units_convert(default_file2, useless)
# hyd_file1 = units_convert(hyd_file1, useless)
# hyd_file2 = units_convert(hyd_file2, useless)
def first_order_finite(base, pert, h, pert_specie, ptype, useless, mode):
# Index to the species of interest
# where h is the perturbation, pert_specie is the perturbed variable
if ptype == 'H':
# number of variables, ignore useless variables
species_num = len(base) - 4
else:
# number of variables, ignore useless variables
species_num = len(base) - 8
time, lev, lat, lon = base[pert_specie].shape
# array holding all variables
array = np.zeros([species_num, time, lev, lat, lon])
shape = array.shape
ct = 0 # counter
specie = [] # list of species names
for i in base:
if i in useless:
continue
# if mode == 'A': #post process for units to ug/m3
else:
if mode == 'semi':
array[ct, :, :, :, :] = (
pert[i] - base[i]) / (h-1) # multiplicative
elif mode == 'normal':
array[ct, :, :, :, :] = (pert[i] - base[i]) / h
# add variable name to list:
specie.append(i)
ct += 1
return array, shape, specie
def central_first_order(dec, inc, h, pert_specie, ptype, useless, mode):
# Index to the species of interest
# where h is the perturbation, pert_specie is the perturbed variable
species_num = 0
if ptype == 'H':
# First, count the number of variables that satisfy the constraints
for i in dec:
# Skip useless variables
if i in useless:
continue
# For 'H' type, only consider variables with 'Total' in the name, or consider only ship
#if ptype == 'H' and 'Total' not in i:
# if ptype == 'H' and 'Ship' not in i:
# continue
# # Count only 4D variables
# if base[i].ndim == 4:
# Count only 3D variables
if dec[i].ndim == 4:
species_num += 1
else:
# # number of variables, ignore useless variables
# if ptype == 'H':
# species_num = len(base) - 4
# else:
species_num = len(dec) - 8
time, lev, lat, lon = dec[pert_specie].shape
# array holding all variables
array = np.zeros([species_num, time, lev, lat, lon])
# time, lat, lon = base[pert_specie].shape
# # array holding all variables
# array = np.zeros([species_num, time, lat, lon])
shape = array.shape
ct = 0 # counter
specie = [] # list of species names
for i in dec:
if i in useless:
continue
elif dec[i].ndim == 4:
if mode == 'semi':
array[ct, :, :, :, :] = (
inc[i] - dec[i]) / (2 * h) # multiplicative
elif mode == 'normal':
array[ct, :, :, :, :] = (inc[i] - dec[i]) / h
# add variable name to list:
specie.append(i)
ct += 1
return array, shape, specie
# Calculating Hyperdual sensitivities
def hyd_first_order(base, pert_specie, ptype, mode, useless, hyd_pert=1):
species_num = 0
if ptype == 'H':
# First, count the number of variables that satisfy the constraints
for i in base:
# Skip useless variables
if i in useless:
continue
# # Count only 4D variables
# if base[i].ndim == 4:
if base[i].ndim == 4:
species_num += 1
else:
species_num = len(base) - 8
time, lev, lat, lon = base[pert_specie].shape
# array holding all variables
array = np.zeros([species_num, time, lev, lat, lon])
shape = array.shape
ct = 0 # counter
specie = [] # list of species names
for i in base:
if i in useless:
continue
elif base[i].ndim == 4:
array[ct, :, :, :, :] = base[i][:, :, :, :] / \
hyd_pert # semi normalization (multiplicative)
# add variable name to list:
specie.append(i)
ct += 1
return array, shape, specie
def hybrid_second_order(base, pert, pert_specie, ptype, mode, useless, hc, h=1):
# where pert represents the diagnostic with both real and dual perturbation, while base is the
# only dual perturbation
if ptype == 'H':
# number of variables, ignore useless variables
species_num = len(base) - 4
else:
# number of variables, ignore useless variables
species_num = len(base) - 8
time, lev, lat, lon = base[pert_specie].shape
# array holding all variables
array = np.zeros([species_num, time, lev, lat, lon])
shape = array.shape
# perturbation size
ct = 0 # counter
specie = [] # list of species names
for i in base:
if i in useless:
continue
else:
if mode == 'semi':
# array[ct, :, :, :, :] = (pert[i][:,:,:,:] - base[i][:,:,:,:]) /((hc-1)*h)
array[ct, :, :, :, :] = (
pert[i][:, :, :, :] / (hc*h*(hc-1))) - (base[i][:, :, :, :] / ((hc-1)*h))
elif mode == 'normal additive':
array[ct, :, :, :, :] = (
(pert[i][:, :, :, :] / h) - (base[i][:, :, :, :] / h)) / h1
# add variable name to list:
specie.append(i)
ct += 1
return array, shape, specie
#dec: the netcdf array corresponding to the dx2 component of the decreased case
#inc: the netcdf array corresponding to the dx2 component of the increased case
#pert_specie: a variable name of the array
def central_hybrid_second_order(dec, inc, pert_specie, ptype, mode, useless, hc, h=1):
# where pert represents the diagnostic with both real and dual perturbation, while base is the
# only dual perturbation
species_num = 0
if ptype == 'H':
# First, count the number of variables that satisfy the constraints
for i in dec:
# Skip useless variables
if i in useless:
continue
if dec[i].ndim == 4:
species_num += 1
else:
species_num = len(dec) - 8
time, lev, lat, lon = dec[pert_specie].shape
# array holding all variables
array = np.zeros([species_num, time, lev, lat, lon])
# time, lat, lon = base[pert_specie].shape
# # array holding all variables
# array = np.zeros([species_num, time, lat, lon])
shape = array.shape
# perturbation size
ct = 0 # counter
specie = [] # list of species names
for i in dec:
if i in useless:
continue
elif dec[i].ndim == 4:
if mode == 'semi':
array[ct, :, :, :, :] = (
inc[i][:, :, :, :] / (2*hc*h*(1+hc))) - (dec[i][:, :, :, :] / (2*h*hc*(1-hc)))
# elif mode == 'normal additive':
# array[ct, :, :, :, :] = ((pert[i][:,:,:,:] / h) - (base[i][:,:,:,:] /h)) / h1
# add variable name to list:
specie.append(i)
ct += 1
return array, shape, specie
def central_finite_second_order(dec, base, inc, pert_specie, ptype, mode, useless, hc, h=1):
# where pert represents the diagnostic with both real and dual perturbation, while base is the
# only dual perturbation
species_num = 0
if ptype == 'H':
# First, count the number of variables that satisfy the constraints
for i in dec:
# Skip useless variables
if i in useless:
continue
# # Count only 4D variables
# if base[i].ndim == 4:
if dec[i].ndim == 4:
species_num += 1
else:
# number of variables, ignore useless variables
species_num = len(dec) - 8
time, lev, lat, lon = dec[pert_specie].shape
# array holding all variables
array = np.zeros([species_num, time, lev, lat, lon])
shape = array.shape
# perturbation size
ct = 0 # counter
specie = [] # list of species names
for i in dec:
if i in useless:
continue
elif dec[i].ndim == 4:
if mode == 'semi':
# array[ct, :, :, :, :] = (pert[i][:,:,:,:] - base[i][:,:,:,:]) /((hc-1)*h)
array[ct, :, :, :, :] = (inc[i][:,:,:,:] - (2*base[i][:,:,:,:]) + dec[i][:,:,:,:]) / (hc*hc)
# elif mode == 'normal additive':
# array[ct, :, :, :, :] = ((pert[i][:,:,:,:] / h) - (base[i][:,:,:,:] /h)) / h1
# add variable name to list:
specie.append(i)
ct += 1
return array, shape, specie
def hyd_second_order(base, pert_specie, ptype, mode, useless, hyd_pert=1):
# Index to the species of interest
# bspecies = base['PM25dx1x2']
species_num = 0
if ptype == 'H':
# First, count the number of variables that satisfy the constraints
for i in base:
# Skip useless variables
if i in useless:
continue
# # Count only 4D variables
if base[i].ndim == 4:
species_num += 1
else:
# number of variables, ignore useless variables
species_num = len(base) - 8
time, lev, lat, lon = base[pert_specie].shape
# array holding all variables
array = np.zeros([species_num, time, lev, lat, lon])
# time, lat, lon = base[pert_specie].shape
# # array holding all variables
# array = np.zeros([species_num, time, lat, lon])
shape = array.shape
ct = 0 # counter
specie = [] # list of species names
for i in base:
if i in useless:
continue
elif base[i].ndim == 4:
if mode == 'semi':
array[ct, :, :, :, :] = base[i][:, :, :, :] / (hyd_pert**2.0)
elif mode == 'normal additive':
array[ct, :, :, :, :] = base[i][:, :, :, :] / (hyd_pert**2.0)
# add variable name to list:
specie.append(i)
ct += 1
return array, shape, specie
def hybrid_cross_sensitivity(base, pert, pert_specie, ptype, mode, useless, hc, h=1):
# Index to the species of interest
if ptype == 'H':
# number of variables, ignore useless variables
species_num = len(base) - 4
else:
# number of variables, ignore useless variables
species_num = len(base) - 8
time, lev, lat, lon = base[pert_specie].shape
# array holding all variables
array = np.zeros([species_num, time, lev, lat, lon])
shape = array.shape
# perturbation size
ct = 0 # counter
specie = [] # list of species names
for i in base:
if i in useless:
continue
else:
array[ct, :, :, :, :] = (
(pert[i][:, :, :, :] / h) - (base[i][:, :, :, :] / h)) / ((hc - 1)*h)
# add variable name to list:
specie.append(i)
ct += 1
return array, shape, specie
def central_hybrid_cross_sensitivity(base, pert, pert_specie, ptype, mode, useless, hc, h=1):
# where pert represents the diagnostic with both real and dual perturbation, while base is the
# only dual perturbation
if ptype == 'H':
# number of variables, ignore useless variables
species_num = len(base) - 4
# Use number of 'total' variables instead
species_num = 32
else:
# number of variables, ignore useless variables
species_num = len(base) - 8
time, lev, lat, lon = base[pert_specie].shape
# array holding all variables
array = np.zeros([species_num, time, lev, lat, lon])
shape = array.shape
# perturbation size
ct = 0 # counter
specie = [] # list of species names
for i in base:
if i in useless:
continue
else:
if mode == 'semi':
# array[ct, :, :, :, :] = (pert[i][:,:,:,:] - base[i][:,:,:,:]) /((hc-1)*h)
array[ct, :, :, :, :] = (
pert[i][:, :, :, :] / (2*hc*h)) - (base[i][:, :, :, :] / (2*h*hc))
# elif mode == 'normal additive':
# array[ct, :, :, :, :] = ((pert[i][:,:,:,:] / h) - (base[i][:,:,:,:] /h)) / h1
# add variable name to list:
specie.append(i)
ct += 1
return array, shape, specie
def hyd_cross_sensitivity(base, pert_specie, ptype, useless, hyd_pert=1):
# Index to the species of interest
# bspecies = base['PM25dx1x2']
if ptype == 'H':
# number of variables, ignore useless variables
species_num = len(base) - 4
# Use number of 'total' variables instead
species_num = 32
else:
# number of variables, ignore useless variables
species_num = len(base) - 8
time, lev, lat, lon = base[pert_specie].shape
# array holding all variables
array = np.zeros([species_num, time, lev, lat, lon])
shape = array.shape
ct = 0 # counter
specie = [] # list of species names
for i in base:
if i in useless:
continue
else:
array[ct, :, :, :, :] = base[i][:, :, :, :] / (hyd_pert**2.0)
# add variable name to list:
specie.append(i)
ct += 1
return array, shape, specie
def analytical_second_order(base, pert_specie, useless):
# number of variables, ignore useless variables
species_num = len(base) - 8
time, lev, lat, lon = base[pert_specie].shape
array = np.zeros([species_num, time, lev, lat, lon])
shape = array.shape
ct = 0 # counter
specie = [] # list of species names
for i in base:
if i in useless:
continue
else:
array[ct, :, :, :, :] = base[i][:, :, :, :] * 6.0
# Then convert to ppb:
array[ct, :, :, :, :] = array[ct, :, :, :, :] * 1e9
# semi-normalize:
array[ct, :, :, :, :] = array[ct, :, :, :, :] * \
(base[i][:, :, :, :] ** 2.0)
specie.append(i)
ct += 1
return array, shape, specie
# def one_to_one(fd, hyd, mean, meanb, meanf, utype, fname, pert, t, sensitivity, x, y, z='', base='conc'): #x
# x and y are strings for bottom and up, t is simulation time
def one_to_one1(ax, fd, hyd, utype, fname, pert, t, sensitivity, x, y, z='', base='conc', color='blue', lab=None):
# Flatten the arrays:
fd = fd.flatten()
hyd = hyd.flatten()
# if data is not None:
# data = data.flatten()
# t = '20min'
rangemin = min(np.nanmin(fd), np.nanmin(hyd))
rangemax = max(np.nanmax(fd), np.nanmax(hyd))
v = [rangemin, rangemax, rangemin, rangemax]
print(f'The maximum is {rangemax:1.6f}.')
print(f'The minimum is {rangemin:1.6f}.')
ax.axis(v)
# to plot the 1 to 1 line
ax.plot([rangemin, rangemax], [rangemin, rangemax], 'k-')
# retrieving the axis to ax
#ax = plt.gca()
#Scatterplot with specified colors and markers
ax.scatter(fd, hyd, c=color, marker='o', alpha=0.6)
# setting axis conditions
ax.ticklabel_format(style='sci', axis='x', scilimits=(0, 0))
ax.ticklabel_format(style='sci', axis='y', scilimits=(0, 0))
# # Create the scatterplot with the colors based on the 'data' array
# #cplot = ax.scatter(fd, hyd, c=colors, cmap=cm.batlow, norm=norm)
# cplot = ax.scatter(fd, hyd, c=colors.reshape(-1,4))
# Scatter plot with specified color and markers
# ax.scatter(fd[~mask_c], hyd[~mask_c], c='blue', label='Ship emission', marker='o', alpha=0.6)
# ax.scatter(fd[mask_c], hyd[mask_c], c='white', label='No ship emission', marker='o', alpha=0.6)
# ax.legend(shadow=True, loc="upper left")
# Mask of nan numbers and infinite numbers
# Using isfinte to mask for the two scenarios
mask = ~np.isnan(fd) & ~np.isnan(hyd)
slope, intercept, r_value, p_value, std_err = stats.linregress(
fd[mask], hyd[mask])
# slope, intercept, r_value, p_value, std_err = stats.linregress(fd, hyd)
# defining axis and notations
ax.minorticks_on()
ax.yaxis.grid(True, which='major', color='black',
linestyle='--', linewidth='0.4')
ax.yaxis.grid(True, which='minor', color='gray',
linestyle=':', linewidth='0.3',)
ax.xaxis.grid(True, which='major', color='black',
linestyle='--', linewidth='0.4')
ax.xaxis.grid(True, which='minor', color='gray',
linestyle=':', linewidth='0.3')
if base == 'conc':
if sensitivity == 'first':
if pert == '/allcells':
# ax.set_xlabel(r'finite difference $\frac{{\partial ' + y.replace("_", "\_") + '}_{(x,y,z,t=1)}}{{\partial ' + x.replace("_", "\_") + '}_{(x,y,z,t=1)}}$') #r treats as raw strings, escape code ignored
# ax.set_ylabel(r'Hyd $\frac{{\partial ' + y.replace("_", "\_") + '}_{(x,y,z,t=1)}}{{\partial ' + x.replace("_", "\_") + '}_{(x,y,z,t=1)}}$')
xlabel = (r'$\frac{{\partial [' + y.replace("SpeciesConc_", "") + ']}_{(x,y,z,t=' + t + ')}}{{\partial [' + x.replace(
# r treats as raw strings, escape code ignored
"SpeciesConc_", "") + ']}_{(x,y,z,t=0hr)}} [' + x.replace("SpeciesConc_", "") + ']$')
ylabel = (r'$\frac{{\partial [' + y.replace("SpeciesConc_", "") + ']}_{(x,y,z,t=' + t + ')}}{{\partial [' + x.replace(
"SpeciesConc_", "") + ']}_{(x,y,z,t=0hr)}} [' + x.replace("SpeciesConc_", "") + ']$')
else: # ground layer perturbation
xlabel = (r'$\frac{{\partial [' + y.replace("SpeciesConc_", "") + ']}_{(x,y,z,t=' + t + ')}}{{\partial [' + x.replace(
# r treats as raw strings, escape code ignored
"SpeciesConc_", "") + ']}_{(x,y,z=1,t=0hr)}} [' + x.replace("SpeciesConc_", "") + ']$')
ylabel = (r'$\frac{{\partial [' + y.replace("SpeciesConc_", "") + ']}_{(x,y,z,t=' + t + ')}}{{\partial [' + x.replace(
"SpeciesConc_", "") + ']}_{(x,y,z=1,t=0hr)}} [' + x.replace("SpeciesConc_", "") + ']$')
elif sensitivity == 'second':
if pert == '/allcells':
if utype == 'A':
xlabel = (r'$\frac{{{\partial}^2 [' + y.replace("dx2", "") + ']}_{(x,y,z,t=' + t + ')}}{{{\partial [' + x.replace(
"SpeciesConc_", "") + ']}^2}_{(x,y,z,t=0hr)}} {[' + x.replace("SpeciesConc_", "") + ']}^2$')
ylabel = (r'$\frac{{{\partial}^2 [' + y.replace("dx2", "") + ']}_{(x,y,z,t=' + t + ')}}{{{\partial [' + x.replace(
"SpeciesConc_", "") + ']}^2}_{(x,y,z,t=0hr)}} {[' + x.replace("SpeciesConc_", "") + ']}^2$')
else:
# ax.set_xlabel(r'Hybrid finite difference $\frac{{\partial}^2 ' + y.replace("_", "\_").replace("dx2", "") + '}{{\partial ' + x.replace("_", "\_") + '}^2}$')
# ax.set_ylabel(r'Hyd $\frac{{\partial}^2 ' + y.replace("_", "\_").replace("dx2", "") + '}{{\partial ' + x.replace("_", "\_") + '}^2}$')
xlabel = (r'$\frac{{{\partial}^2 [' + y.replace("SpeciesConcdx2_", "") + ']}_{(x,y,z,t=' + t + ')}}{{{\partial [' + x.replace(
"SpeciesConc_", "") + ']}^2}_{(x,y,z,t=0hr)}} {[' + x.replace("SpeciesConc_", "") + ']}^2$')
ylabel = (r'$\frac{{{\partial}^2 [' + y.replace("SpeciesConcdx2_", "") + ']}_{(x,y,z,t=' + t + ')}}{{{\partial [' + x.replace(
"SpeciesConc_", "") + ']}^2}_{(x,y,z,t=0hr)}} {[' + x.replace("SpeciesConc_", "") + ']}^2$')
else:
xlabel = (r'$\frac{{{\partial}^2 [' + y.replace("SpeciesConcdx2_", "") + ']}_{(x,y,z,t=' + t + ')}}{{{\partial [' + x.replace(
"SpeciesConc_", "") + ']}^2}_{(x,y,z=1,t=0hr)}} {[' + x.replace("SpeciesConc_", "") + ']}^2$')
ylabel = (r'$\frac{{{\partial}^2 [' + y.replace("SpeciesConcdx2_", "") + ']}_{(x,y,z,t=' + t + ')}}{{{\partial [' + x.replace(
"SpeciesConc_", "") + ']}^2}_{(x,y,z=1,t=0hr)}} {[' + x.replace("SpeciesConc_", "") + ']}^2$')
elif sensitivity == 'cross':
if pert == '/allcells':
# ax.set_xlabel(r'finite difference Sensitivities $\frac{{\partial}^2 ' + y.replace("_", "\_") + '}{{\partial ' + x.replace("_", "\_") + '}\partial ' + z + '}$')
xlabel = (r'$\frac{{{\partial}^2 [' + y.replace("SpeciesConcdx2_", "") + ']}_{(x,y,z,t=' + t + ')}}{{\partial [' + x.replace(
"SpeciesConc_", "") + ']}_{(x,y,z,t=0hr)}{\partial [' + z.replace("SpeciesConc_", "") + ']}_{(x,y,z=1,t=0hr)}} [' + x.replace("SpeciesConc_", "") + '][' + z.replace("SpeciesConc_", "") + ']$')
ylabel = (r'$\frac{{{\partial}^2 [' + y.replace("SpeciesConcdx2_", "") + ']}_{(x,y,z,t=' + t + ')}}{{\partial [' + x.replace(
"SpeciesConc_", "") + ']}_{(x,y,z,t=0hr)}{\partial [' + z.replace("SpeciesConc_", "") + ']}_{(x,y,z=1,t=0hr)}} [' + x.replace("SpeciesConc_", "") + '][' + z.replace("SpeciesConc_", "") + ']$')
else:
xlabel = (r'$\frac{{{\partial}^2 [' + y.replace("SpeciesConcdx2_", "") + ']}_{(x,y,z,t=' + t + ')}}{{\partial [' + x.replace(
"SpeciesConc_", "") + ']}_{(x,y,z=1,t=0hr)}{\partial [' + z.replace("SpeciesConc_", "") + ']}_{(x,y,z=1,t=0hr)}} [' + x.replace("SpeciesConc_", "") + '][' + z.replace("SpeciesConc_", "") + ']$')
ylabel = (r'$\frac{{{\partial}^2 [' + y.replace("SpeciesConcdx2_", "") + ']}_{(x,y,z,t=' + t + ')}}{{\partial [' + x.replace(
"SpeciesConc_", "") + ']}_{(x,y,z=1,t=0hr)}{\partial [' + z.replace("SpeciesConc_", "") + ']}_{(x,y,z=1,t=0hr)}} [' + x.replace("SpeciesConc_", "") + '][' + z.replace("SpeciesConc_", "") + ']$')
# ax.set_ylabel(r'Hyd $\frac{{\partial}^2 ' + y.replace("SpeciesConcdx2_", "") + '}{{\partial ' + x.replace("SpeciesConc_", "") + '}\partial ' + z.replace("SpeciesConc_", "") + '}$')
elif base == 'emis':
if sensitivity == 'first':
xlabel = (r'$\frac{{\partial [' + y.replace("SpeciesConc_", "") + ']}_{(x,y,z,t=' + t + ')}}'
r'{{\partial (E_{' + x.replace("SpeciesConc_",
"") + '})}_{(x,y,z,t=0)}} '
r'(E_{' + x.replace("SpeciesConc_", "") + '})$')
ylabel = (r'$\frac{{\partial [' + y.replace("SpeciesConc_", "") + ']}_{(x,y,z,t=' + t + ')}}'
r'{{\partial (E_{' + x.replace("SpeciesConc_",
"") + '})}_{(x,y,z,t=0)}} '
r'(E_{' + x.replace("SpeciesConc_", "") + '})$')
elif sensitivity == 'second':
xlabel = (r'$\frac{{{\partial}^2 [' + y.replace("SpeciesConcdx2_", "") + ']}_{(x,y,z,t=' + t + ')}}'