-
Notifications
You must be signed in to change notification settings - Fork 0
/
generate_AWS_plots.py
3374 lines (2580 loc) · 138 KB
/
generate_AWS_plots.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
import sys, os, shutil
import datetime, time, calendar
import numpy as np
import subprocess
import re, csv, glob
import itertools
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
from matplotlib.colors import LinearSegmentedColormap
from mpl_toolkits.axes_grid1.inset_locator import inset_axes
import dawsonpy
# Function to create final xml using template and multiple_replace function
def update_xml(jobtype,plottype,template_xml,updated_xml):
# Copy template to verf_job directory
os.system('cp '+template_xml+' '+temp_xml)
#############################################################################################
# Insert list of model values for batch jobs #
#############################################################################################
# Set list of model names
if str.upper(verf_job) == 'FV3CAM' and str.lower(verf_exp) == 'para_exp':
nam3_val = ' <val>'+nam3[domain_key]+'</val>\n'
lam_val = ' <val>'+lam[domain_key]+'</val>\n'
lamda_val = ' <val>'+lamda[domain_key]+'</val>\n'
lamx_val = ' <val>'+lamx[domain_key]+'</val>\n'
gfs_val = ' <val>'+gfs[domain_key]+'</val>\n'
hrrr_val = ' <val>'+hrrr[domain_key]+'</val>\n'
model_list = nam3_val + lam_val + lamda_val + lamx_val + gfs_val + hrrr_val
elif str.upper(verf_job) == 'FV3CAM' and str.lower(verf_exp) == 'da_exp':
lam_val = ' <val>'+lam[domain_key]+'</val>\n'
lamda_val = ' <val>'+lamda[domain_key]+'</val>\n'
lamdax_val = ' <val>'+lamdax[domain_key]+'</val>\n'
model_list = lam_val + lamda_val + lamdax_val
elif str.upper(verf_job) == 'FV3CAM' and str.lower(verf_exp) == 'lam_exp':
lam_val = ' <val>'+lam[domain_key]+'</val>\n'
lamx_val = ' <val>'+lamx[domain_key]+'</val>\n'
model_list = lam_val + lamx_val
elif (str.upper(verf_job) == 'FV3CAM' and
(str.lower(verf_exp) == 'sarda_exp' or str.lower(verf_exp) == 'sar_exp')):
sar_val = ' <val>'+sar[domain_key]+'</val>\n'
sarda_val = ' <val>'+sarda[domain_key]+'</val>\n'
sarx_val = ' <val>'+sarx[domain_key]+'</val>\n'
if str.lower(verf_exp) == 'sar_exp':
model_list = sar_val + sarx_val
elif str.lower(verf_exp) == 'sarda_exp':
model_list = sar_val + sarda_val
elif str.upper(verf_job) == 'HREF_MEM':
fv3_val = ' <val>'+hrwfv3[domain_key]+'</val>\n'
nmmb_val = ' <val>'+hrwnmmb[domain_key]+'</val>\n'
model_list = fv3_val + nmmb_val
elif str.upper(verf_job) == 'HREFV3':
# Precip plots comparing HREF PMMN, HREFX PMMN, and HREFX LPMM
if plottype[-4:] == 'lpmm':
href_pmmn_val = ' <val>'+href['pcp']+href['pmmn']+'</val>\n'
hrefx_lpmm_val = ' <val>'+hrefx['pcp']+hrefx['lpmm']+'</val>\n'
hrefx_pmmn_val = ' <val>'+hrefx['pcp']+hrefx['pmmn']+'</val>\n'
model_list = href_pmmn_val + hrefx_lpmm_val + hrefx_pmmn_val
# Precip plots comparing HREF AVRG, HREFX AVRG, and HREFX LAVG
elif plottype[-4:] == 'avrg':
href_avrg_val = ' <val>'+href['pcp']+href['avrg']+'</val>\n'
hrefx_avrg_val = ' <val>'+hrefx['pcp']+hrefx['avrg']+'</val>\n'
hrefx_lavg_val = ' <val>'+hrefx['pcp']+hrefx['lavg']+'</val>\n'
model_list = href_avrg_val + hrefx_avrg_val + hrefx_lavg_val
# Precip plots comparing HREFX AVRG, LAVG, LPMM, MEAN, PMMN
elif plottype[-7:] == 'v3prods':
hrefx_avrg_val = ' <val>'+hrefx['pcp']+hrefx['avrg']+'</val>\n'
hrefx_lavg_val = ' <val>'+hrefx['pcp']+hrefx['lavg']+'</val>\n'
hrefx_lpmm_val = ' <val>'+hrefx['pcp']+hrefx['lpmm']+'</val>\n'
hrefx_mean_val = ' <val>'+hrefx['pcp']+hrefx['mean']+'</val>\n'
hrefx_pmmn_val = ' <val>'+hrefx['pcp']+hrefx['pmmn']+'</val>\n'
model_list = hrefx_avrg_val + hrefx_lavg_val + hrefx_lpmm_val + hrefx_mean_val + hrefx_pmmn_val
# works for all other 24-h and 3-h precip plots
elif plottype[0:6] == '24hpcp' or plottype[0:5] == '3hpcp':
href_val = ' <val>'+href['pcp']+href[ensprod_key]+'</val>\n'
hrefx_val = ' <val>'+hrefx['pcp']+hrefx[ensprod_key]+'</val>\n'
model_list = href_val + hrefx_val
# All other HREFv3 stats from Binbin
elif plottype[0:3] == 'sfc' or plottype == 'cape' or plottype == 'ceiling' or plottype == 'vis':
hrefx_mean_val = ' <val>'+hrefx[domain_key]+'_'+hrefx['mean']+'</val>\n'
href_mean_val = ' <val>'+href[domain_key]+'_'+href['mean']+'</val>\n'
href_mean_val = ' <val>HREFMEAN</val>\n'
hrefx_mean_val = ' <val>HREFV3MEAN</val>\n'
model_list = href_mean_val + hrefx_mean_val
# Radar and surrogate severe stats
elif ensprod_key == 'nbmax':
hrefx_val = ' <val>'+hrefx[domain_key]+'_'+hrefx['prob']+'</val>\n'
href_val = ' <val>'+href[domain_key]+'_'+href['prob']+'</val>\n'
model_list = hrefx_val + href_val
else:
hrefx_val = ' <val>'+hrefx[domain_key]+'_'+hrefx[ensprod_key]+'</val>\n'
href_val = ' <val>'+href[domain_key]+'_'+href[ensprod_key]+'</val>\n'
model_list = hrefx_val + href_val
elif str.upper(verf_job) == 'CAM':
arw_val = ' <val>'+hrwarw[domain_key]+'</val>\n'
arw2_val = ' <val>'+hrwarw2[domain_key]+'</val>\n'
nam3_val = ' <val>'+nam3[domain_key]+'</val>\n'
nmmb_val = ' <val>'+hrwnmmb[domain_key]+'</val>\n'
hrrr_val = ' <val>'+hrrr[domain_key]+'</val>\n'
model_list = arw_val + arw2_val + nam3_val + nmmb_val + hrrr_val
elif str.upper(verf_job) == 'MESO':
gfs_val = ' <val>'+gfs[domain_key]+'</val>\n'
nam_val = ' <val>'+nam[domain_key]+'</val>\n'
rap_val = ' <val>'+rap[domain_key]+'</val>\n'
model_list = gfs_val + nam_val + rap_val
# Read lines of temp XML
with open(temp_xml,"r") as f:
data = f.readlines()
f.close()
# Find correct number and insert model list
insert_ind = data.index(' <field name=\"model\">\n')
data.insert(insert_ind+1,model_list)
# Write updated XML
f = open(temp_xml,"w")
data = "".join(data)
f.write(data)
f.close()
#############################################################################################
# Insert list of forecast hours for forecast lead jobs #
#############################################################################################
# Define x-axis for forecast lead plots
if str.lower(plot[0]) == 'fcstlead':
if plottype[0:5] == 'upper':
if cycle%12 == 0:
leads = np.arange(0,runlength+1,12)
elif cycle%12 == 6:
leads = np.arange(6,runlength+1,12)
elif plottype == 'cape':
leads = np.arange(0,runlength+1,6)
elif plottype[0:5] == 'radar':
ones = np.arange(0,12,1)
threes = np.arange(12,runlength+1,3)
leads = np.concatenate((ones,threes),axis=None)
else:
leads = np.arange(0,runlength+1,3)
# Loop over leads to build list to be inserted
lead_list = ' <val label=\"0\" plot_val=\"\">0</val>\n'
for lead in leads[1:]:
lead_list = lead_list + ' <val label=\"'+str(lead)\
+'\" plot_val=\"\">'+str(lead*10000)+'</val>\n'
# Read lines of temp XML
with open(temp_xml,"r") as f:
data = f.readlines()
f.close()
# Find correct number and insert lead list
insert_ind = data.index(' <indep equalize=\"true\" name=\"fcst_lead\">\n')
data.insert(insert_ind+1,lead_list)
# Write updated XML
f = open(temp_xml,"w")
data = "".join(data)
f.write(data)
f.close()
#############################################################################################
# Replacements #
#############################################################################################
replacements = {
"%VERF_JOB%" : str.lower(verf_job),
"%SUB_DIR%" : str.lower(sub_dir),
"%MV_DATABASE%" : str.lower(mv_database),
# subs for model names/labels in scorecard scripts
"%MODELX%" : str.upper(para),
"%MODEL%" : str.upper(prod),
"%MODELX_LABEL%" : para_label,
"%MODEL_LABEL%" : prod_label,
"%modelx%" : str.lower(para_label),
"%model%" : str.lower(prod_label),
"%TIME_PERIOD%" : str.lower(time_period),
"%VDAY1%" : vday1.strftime('%Y-%m-%d'),
"%DD1%" : vday1.strftime('%d'),
"%MMM1%" : vday1.strftime('%b'),
"%YYYY1%" : vday1.strftime('%Y'),
"%VDAY2%" : vday2.strftime('%Y-%m-%d'),
"%DD2%" : vday2.strftime('%d'),
"%MMM2%" : vday2.strftime('%b'),
"%YYYY2%" : vday2.strftime('%Y'),
"%CC%" : str(cycle).zfill(2),
"%F%" : str(fhr*10000),
"%FF%" : str(fhr).zfill(2),
"%ENSPROD%" : str.upper(ensprod_key),
"%FCST_VAR%" : str.upper(fcst_var),
"%PPP%" : str(plev),
"%THRESH%" : str(thresh),
"%THRESH2%" : str(imperial_thresh),
"%HREF_THRESH%" : '%.3f' % thresh,
"%INT_PTS%" : str(interp_pnts),
"%NBR%" : nbrhd,
"%GGG%" : vx_mask,
"%REGION%" : region_strings[str.lower(region)],
"%region%" : str.lower(region),
"%BOOT_REPL%" : str(boot_repl),
"%EVENT_EQ%" : event_eq,
# subs for plot settings in batch scripts with one line per model
"%CI_LIST%" : ci_list,
"%SIGNIF_LIST%" : signif_list,
"%DISP_LIST%" : disp_list,
"%COLORS_LIST%" : colors_list,
"%PCH_LIST%" : pch_list,
"%TYPE_LIST%" : type_list,
"%LTY_LIST%" : lty_list,
"%LWD_LIST%" : lwd_list,
"%CON_LIST%" : con_list,
"%ORDER_LIST%" : order_list,
"%LEGEND_LIST%" : legend_list,
# subs for plot settings in batch scripts with two lines per model
"%CI_LIST2%" : ci_list2,
"%SIGNIF_LIST2%" : signif_list2,
"%DISP_LIST2%" : disp_list2,
"%COLORS_LIST2%" : colors_list2,
"%PCH_LIST2%" : pch_list2,
"%TYPE_LIST2%" : type_list2,
"%LTY_LIST2%" : lty_list2,
"%LWD_LIST2%" : lwd_list2,
"%CON_LIST2%" : con_list2,
"%ORDER_LIST2%" : order_list2,
"%LEGEND_LIST2%" : legend_list2,
# subs for plot settings in batch scripts with two lines (vector scores) per model
"%PCH_LIST3%" : pch_list3,
"%LEGEND_LIST3%" : legend_list3,
# subs for plot settings in batch scripts with two lines per model
"%CI_LIST4%" : ci_list4,
"%SIGNIF_LIST4%" : signif_list4,
"%DISP_LIST4%" : disp_list4,
"%COLORS_LIST4%" : colors_list4,
"%PCH_LIST4%" : pch_list4,
"%LTY_LIST4%" : lty_list4,
"%LWD_LIST4%" : lwd_list4,
"%CON_LIST4%" : con_list4,
"%ORDER_LIST4%" : order_list4,
"%TYPE_LIST4%" : type_list4,
"%LEGEND_LIST4%" : legend_list4,
# subs for plot settings in batch scripts with two lines per model
"%CI_LIST5%" : ci_list5,
"%SIGNIF_LIST5%" : signif_list5,
"%DISP_LIST5%" : disp_list5,
"%COLORS_LIST5%" : colors_list5,
"%PCH_LIST5%" : pch_list5,
"%TYPE_LIST5%" : type_list5,
"%LTY_LIST5%" : lty_list5,
"%LWD_LIST5%" : lwd_list5,
"%CON_LIST5%" : con_list5,
"%ORDER_LIST5%" : order_list5,
"%LEGEND_LIST5%" : legend_list5,
# subs for plot settings in batch scripts with three lines total
"%CI_LIST6%" : ci_list6,
"%SIGNIF_LIST6%" : signif_list6,
"%DISP_LIST6%" : disp_list6,
"%COLORS_LIST6%" : colors_list6,
"%PCH_LIST6%" : pch_list6,
"%TYPE_LIST6%" : type_list6,
"%LTY_LIST6%" : lty_list6,
"%LWD_LIST6%" : lwd_list6,
"%CON_LIST6%" : con_list6,
"%ORDER_LIST6%" : order_list6,
"%LEGEND_LIST6%" : legend_list6,
# subs for plot settings in batch scripts with 5 lines total (HREFv3 five means)
"%CI_LIST7%" : ci_list7,
"%SIGNIF_LIST7%" : signif_list7,
"%DISP_LIST7%" : disp_list7,
"%COLORS_LIST7%" : colors_list7,
"%PCH_LIST7%" : pch_list7,
"%TYPE_LIST7%" : type_list7,
"%LTY_LIST7%" : lty_list7,
"%LWD_LIST7%" : lwd_list7,
"%CON_LIST7%" : con_list7,
"%ORDER_LIST7%" : order_list7,
"%LEGEND_LIST7%" : legend_list7,
# subs for plot settings in batch scripts with 10 lines total (HREFv3 five means with diurnal obs)
"%CI_LIST8%" : ci_list8,
"%SIGNIF_LIST8%" : signif_list8,
"%DISP_LIST8%" : disp_list8,
"%COLORS_LIST8%" : colors_list8,
"%PCH_LIST8%" : pch_list8,
"%TYPE_LIST8%" : type_list8,
"%LTY_LIST8%" : lty_list8,
"%LWD_LIST8%" : lwd_list8,
"%CON_LIST8%" : con_list8,
"%ORDER_LIST8%" : order_list8,
"%LEGEND_LIST8%" : legend_list8,
}
# Open template in verf_job directory and replace using dictionary keys above
with open(temp_xml) as f:
new_text = dawsonpy.multiple_replace(replacements, f.read())
f.close()
# Write updated XML
with open(updated_xml, "w") as result:
result.write(new_text)
result.close()
# Function to create final xml using template and multiple_replace function
def update_scorecard_xml(plottype,template_xml,updated_xml):
# Copy template to verf_job directory
os.system('cp '+template_xml+' '+temp_xml)
#############################################################################################
# Replacements #
#############################################################################################
replacements = {
"%VERF_JOB%" : str.lower(verf_job),
"%SUB_DIR%" : str.lower(sub_dir),
"%MV_DATABASE%" : str.lower(mv_database),
# subs for model names/labels in scorecard scripts
"%MODELX%" : str.upper(para),
"%MODEL%" : str.upper(prod),
"%MODELX_LABEL%" : para_label,
"%MODEL_LABEL%" : prod_label,
"%modelx%" : str.lower(para_label),
"%model%" : str.lower(prod_label),
"%TIME_PERIOD%" : str.lower(time_period),
"%VDAY1%" : vday1.strftime('%Y-%m-%d'),
"%DD1%" : vday1.strftime('%d'),
"%MMM1%" : vday1.strftime('%b'),
"%YYYY1%" : vday1.strftime('%Y'),
"%VDAY2%" : vday2.strftime('%Y-%m-%d'),
"%DD2%" : vday2.strftime('%d'),
"%MMM2%" : vday2.strftime('%b'),
"%YYYY2%" : vday2.strftime('%Y'),
"%CC%" : str(cycle).zfill(2),
"%F%" : str(fhr*10000),
"%FF%" : str(fhr).zfill(2),
"%ENSPROD%" : str.upper(ensprod_key),
"%FCST_VAR%" : str.upper(fcst_var),
"%PPP%" : str(plev),
"%THRESH%" : str(thresh),
"%THRESH2%" : str(imperial_thresh),
"%HREF_THRESH%" : '%.3f' % thresh,
"%INT_PTS%" : str(interp_pnts),
"%NBR%" : nbrhd,
"%GGG%" : vx_mask,
# "%REGION%" : region,
"%REGION%" : region_strings[str.lower(region)],
"%region%" : str.lower(region),
"%BOOT_REPL%" : str(boot_repl),
"%EVENT_EQ%" : event_eq,
}
# Open template in verf_job directory and replace using dictionary keys above
with open(temp_xml) as f:
new_text = dawsonpy.multiple_replace(replacements, f.read())
f.close()
# Write updated XML
with open(updated_xml, "w") as result:
result.write(new_text)
result.close()
# Function to specify METviewer database and most recent verification date
def update_db_vday2(verf_job,plottype):
# Precip databases
if plottype[0:6] == '24hpcp' or plottype[0:5] == '6hpcp' or plottype[0:5] == '3hpcp':
if str.upper(verf_job) == 'FV3CAM':
if str.lower(verf_exp) == 'da_exp' or str.lower(verf_exp) == 'lam_exp':
mv_database = 'mv_lam_pcp_2021_metplus'
else:
mv_database = 'mv_cam_pcp_2021_metplus,mv_lam_pcp_2021_metplus,mv_meso_pcp_2021_metplus'
elif str.upper(verf_job) == 'CAM':
mv_database = 'mv_cam_pcp_2021_metplus'
elif str.upper(verf_job) == 'MESO':
mv_database = 'mv_meso_pcp_2021_metplus'
elif str.upper(verf_job) == 'HREFV3':
mv_database = 'mv_met_hrefv2_v3_apcp'
else:
print("ERROR. Database not defined correctly.")
vday2 = now + datetime.timedelta(days=-2)
# Radar databases
elif plottype[:2] == 're' or plottype[0:5] == 'radar':
if str.upper(verf_job) == 'FV3CAM':
if str.lower(verf_exp) == 'da_exp' or str.lower(verf_exp) == 'lam_exp':
mv_database = 'mv_lam_radar_2021_metplus'
else:
mv_database = 'mv_cam_radar_2021_metplus,mv_lam_radar_2021_metplus'
elif str.upper(verf_job) == 'CAM':
mv_database = 'mv_cam_radar_2021_metplus,mv_href_radar_2021_metplus'
elif str.upper(verf_job) == 'HREFV3':
mv_database = 'mv_hrefv3_eval_radar_metplus'
else:
print("ERROR. Database not defined correctly.")
vday2 = now + datetime.timedelta(days=-2)
# Surrogate Severe databases
elif plottype[0:7] == 'surrsvr':
if str.upper(verf_job) == 'HREFV3':
mv_database = 'mv_hrefv3_eval_surrogatesvr_metplus'
elif str.upper(verf_job) == 'CAM':
mv_database = 'mv_cam_svr_20201_metplus'
if str.upper(verf_job) == 'FV3CAM':
if str.lower(verf_exp) == 'da_exp' or str.lower(verf_exp) == 'lam_exp':
mv_database = 'mv_lam_svr_20201_metplus'
else:
mv_database = 'mv_cam_svr_20201_metplus,mv_lam_svr_20201_metplus'
else:
print("ERROR. Database not defined correctly.")
vday2 = now + datetime.timedelta(days=-8)
# Grid2obs database(s)
else:
if str.upper(verf_job) == 'FV3CAM':
if str.lower(verf_exp) == 'da_exp' or str.lower(verf_exp) == 'lam_exp':
mv_database = 'mv_lam_grid2obs_2020_metplus,mv_lam_grid2obs_2021_metplus'
else:
mv_database = 'mv_cam_grid2obs_2021_metplus,mv_lam_grid2obs_2021_metplus,mv_meso_grid2obs_2021_metplus'
elif str.upper(verf_job) == 'CAM':
mv_database = 'mv_cam_grid2obs_2021_metplus,mv_href_grid2obs_2021_metplus'
elif str.upper(verf_job) == 'MESO':
mv_database = 'mv_meso_grid2obs_2021_metplus'
# HREFv3 upper air database from Logan
elif str.upper(verf_job) == 'HREFV3' and plottype[0:5] == 'upper':
mv_database = 'mv_hrefv3_eval_upperair_metplus'
# HREFv3 databases from Binbin
elif str.upper(verf_job) == 'HREFV3' and (plottype[0:3] == 'sfc' or plottype == 'cape' or plottype == 'ceiling' or plottype == 'vis'):
mv_database = 'mv_met_hrefv2_v3_sfc'
else:
print("ERROR. Database not defined correctly.")
vday2 = now + datetime.timedelta(days=-2)
# If working on a period with a predefined end date, use that
# Handles FV3CAM experiments, HREFV3/HREF_MEM experiments/eval periods
# Handles monthly periods
if 'exp_vday2' in globals():
vday2 = exp_vday2
elif 'month_vday2' in globals():
vday2 = month_vday2
return mv_database, vday2
# Function to specify METviewer database and most recent verification date
def update_vx_mask(jobtype,region):
# CONUS settings
if str.upper(region) == 'CONUS':
vx_mask = 'CONUS'
# if mv_database == 'mv_emc_g2o_met' and jobtype == 'batch':
# vx_mask = 'APL,GMC,GRB,LMV,MDW,NEC,NMT,NPL,NWC,SEC,SMT,SPL,SWC,SWD'
# elif mv_database == 'mv_emc_g2o_met' and jobtype == 'scorecard':
# vx_mask = 'FULL'
# else:
# vx_mask = 'CONUS'
# Eastern CONUS settings
elif str.upper(region) == 'EAST':
if str.upper(verf_job) == 'HREFV3' and mv_database[0:14] != 'mv_hrefv3_eval':
vx_mask = 'EAST'
else:
vx_mask = 'APL,GMC,LMV,MDW,NEC,SEC'
# Western CONUS settings
elif str.upper(region) == 'WEST':
if str.upper(verf_job) == 'HREFV3' and mv_database[0:14] != 'mv_hrefv3_eval':
# includes NPL and SPL
vx_mask = 'WEST'
else:
# excludes NPL and SPL
vx_mask = 'GRB,NMT,NWC,SMT,SWC,SWD'
# Plains settings
elif str.upper(region) == 'PLAINS':
vx_mask = 'NPL,SPL'
# Alaska settings
elif str.upper(region) == 'ALASKA':
if str.upper(verf_job) == 'HREFV3' and mv_database[0:14] != 'mv_hrefv3_eval':
vx_mask = 'Alaska'
else:
vx_mask = 'NAK,SAK'
# SPC settings
elif str.upper(region) == 'SPC':
vx_mask = 'DAY1_1200_MRGL,DAY2_1730_MRGL,DAY3_MRGL'
elif str.upper(region) == 'DAY 1':
vx_mask = 'DAY1_1200_MRGL'
elif str.upper(region) == 'DAY 2':
vx_mask = 'DAY2_1730_MRGL'
elif str.upper(region) == 'DAY 3':
vx_mask = 'DAY3_MRGL'
elif str.upper(region) == 'TSTM':
vx_mask = 'DAY1_1200_TSTM,DAY2_1730_TSTM,DAY3_TSTM'
elif str.upper(region) == 'MRGL':
vx_mask = 'DAY1_1200_MRGL,DAY2_1730_MRGL,DAY3_MRGL'
elif str.upper(region) == 'SLGT':
vx_mask = 'DAY1_1200_SLGT,DAY2_1730_SLGT,DAY3_SLGT'
elif str.upper(region) == 'ENH':
vx_mask = 'DAY1_1200_ENH,DAY2_1730_ENH,DAY3_ENH'
elif str.upper(region) == 'MOD':
vx_mask = 'DAY1_1200_MOD,DAY2_1730_MOD,DAY3_MOD'
elif str.upper(region) == 'HIGH':
vx_mask = 'DAY1_1200_HIGH,DAY2_1730_HIGH'
# Otherwise, use region that is previously defined
else:
vx_mask = str.upper(region)
return vx_mask
# Function to read METviewer data and replace performance diagram
def performance_diag(filename,plottype):
print('Remaking performance diagram with python')
# Read METviewer data file
with open(filename+'.data','r') as f:
reader = csv.reader(f)
data_list = []
thresh_list = []
model_list = []
far_list = []
pod_list = []
for row in reader:
row_list = row[0].split('\t')
# Build list of models to plot
if row_list[1] not in model_list and row_list[1] != 'model':
model_list.append(row_list[1])
# Build list of thresholds to plot
if row_list[1] not in thresh_list:
thresh_list.append(row_list[2])
# Build list for easier iteration later
if row_list[0] != 'fcst_var':
data_list.append(row_list)
# Get fcst_var to use for title keys
fcst_var = row_list[0]
# Build list of POD and FAR stats
for model in model_list:
model_far = []
model_pod = []
for row in data_list:
if row[1] == model and row[3][-3:] == 'FAR':
if row[4] == 'NA':
model_far.append(np.nan)
else:
model_far.append(float(row[4]))
elif row[1] == model and row[3][-4:] == 'PODY':
if row[4] == 'NA':
model_pod.append(np.nan)
else:
model_pod.append(float(row[4]))
far_list.append(model_far)
pod_list.append(model_pod)
# Begin plotting
fig = plt.figure(figsize=[8.5,8])
ax = plt.subplot(111)
# Define limits for diagram axes
ax.set_xlim([0,1])
ax.set_ylim([0,1])
x=y = np.arange(0.01,1.01,0.01)
X,Y = np.meshgrid(x,y)
# Define and add CSI lines to the diagram
bounds = np.arange(0,1.10,0.10)
norm = matplotlib.colors.BoundaryNorm(bounds, len(bounds))
colors=['#ffffff','#f0f0f0','#e3e3e3','#d6d6d6','#c9c9c9','#bdbdbd','#b0b0b0','#a3a3a3','#969696','#8a8a8a']
cm = LinearSegmentedColormap.from_list('percentdiff_cbar', colors, N=len(bounds))
CSI = ((1/X)+(1/Y)-1)**-1
CSI_lines = ax.contourf(X,Y,CSI,np.arange(0.0,1.1,0.1),cmap=cm)
# Define and add bias lines to the diagram
biases=[0.1,0.25,0.5,0.75,1.0,1.5,2.0,4.0,10.0]
bias_loc_x = [0.94,0.935,0.94,0.935,0.9,0.58,0.42,0.18,0.03]
bias_loc_y = [0.12,0.2625,0.5,0.74,0.95,0.95,0.95,0.95,0.95]
FBIAS = Y/X
FBIAS_lines = ax.contour(X,Y,FBIAS,biases,colors='black',linestyles='--')
for i,j in enumerate(biases):
ax.annotate(j,(bias_loc_x[i],bias_loc_y[i]),fontsize=12)
# Settings for CAM performance diagrams
if str.upper(verf_job) == 'CAM':
perf_legend = [hrwarw['name'],hrwarw2['name'],nam3['name'],hrwnmmb['name'],hrrr['name']]
perf_colors = [hrwarw['pycolor'],hrwarw2['pycolor'],nam3['pycolor'],hrwnmmb['pycolor'],hrrr['pycolor']]
perf_lines = ['solid','solid','solid','solid','solid']
perf_marks = ['o','o','o','o','o']
# Settings for MESO performance diagrams
elif str.upper(verf_job) == 'MESO':
perf_legend = [gfs['name'],nam['name'],rap['name']]
perf_colors = [gfs['pycolor'],nam['pycolor'],rap['pycolor']]
perf_lines = ['solid','solid','solid']
perf_marks = ['o','o','o']
# Settings for HREFv3 performance diagrams
elif str.upper(verf_job) == 'HREFV3':
# Precip plots comparing HREF PMMN, HREFX PMMN, and HREFX LPMM
if plottype == '24hpcp_lpmm':
perf_legend = [href['name']+' '+href['pmmn'],hrefx['name']+' '+hrefx['lpmm'],hrefx['name']+' '+hrefx['pmmn']]
perf_colors = [href['pycolor'],'blue',hrefx['pycolor']]
perf_lines = ['solid','solid','solid']
perf_marks = ['o','o','o']
# Precip plots comparing HREF AVRG, HREFX AVRG, and HREFX LAVG
elif plottype == '24hpcp_avrg':
perf_legend = [href['name']+' '+href['avrg'],hrefx['name']+' '+hrefx['avrg'],hrefx['name']+' '+hrefx['lavg']]
perf_colors = [href['pycolor'],hrefx['pycolor'],'blue']
perf_lines = ['solid','solid','solid']
perf_marks = ['o','o','o']
# Precip plots comparing HREFX AVRG, LAVG, LPMM, MEAN, PMMN
elif plottype == '24hpcp_v3prods':
perf_legend = [hrefx['name']+' '+hrefx['avrg'],hrefx['name']+' '+hrefx['lavg'],hrefx['name']+' '+hrefx['lpmm'],hrefx['name']+' '+hrefx['mean'],hrefx['name']+' '+hrefx['pmmn']]
perf_colors = [hrefx['pycolor'],'blue','blue',href['pycolor'],hrefx['pycolor']]
perf_lines = ['dashed','dashed','solid','solid','solid']
perf_marks = ['D','D','o','o','o']
# All other HREFv3 stats from Binbin
elif plottype == '24hpcp_mean' or plottype == 'cape' or plottype == 'ceiling' or plottype == 'vis':
perf_legend = [href['name']+' '+href[ensprod_key],hrefx['name']+' '+hrefx[ensprod_key]]
perf_colors = [href['pycolor'],hrefx['pycolor']]
perf_lines = ['solid','solid','solid']
perf_marks = ['o','o']
# Radar and surrogate severe stats
elif plottype[0:2] == 're' or plottype == 'surrsvr':
perf_legend = [hrefx['name']+' '+hrefx[ensprod_key],href['name']+' '+href[ensprod_key]]
perf_colors = [hrefx['pycolor'],href['pycolor']]
perf_lines = ['solid','solid']
perf_marks = ['o','o']
# Settings for HREF_MEM performance diagrams
elif str.upper(verf_job) == 'HREF_MEM':
perf_legend = [hrwfv3['name'],hrwnmmb['name']]
perf_colors = [hrwfv3['pycolor'],hrwnmmb['pycolor']]
perf_lines = ['solid','solid']
perf_marks = ['o','o']
# Settings for FV3-CAM performance diagrams
elif str.upper(verf_job) == 'FV3CAM' and str.lower(verf_exp) == 'para_exp':
perf_legend = [nam3['name'],lam['name'],lamda['name'],lamx['name'],gfs['name'],hrrr['name']]
perf_colors = [nam3['pycolor'],lam['pycolor'],lamda['pycolor'],lamx['pycolor'],gfs['pycolor'],hrrr['pycolor']]
perf_lines = ['solid','solid','solid','solid','solid','solid']
perf_marks = ['o','o','D','^','o','o']
# Settings for FV3-CAM LAM-X vs. LAM performance diagrams
elif str.upper(verf_job) == 'FV3CAM' and str.lower(verf_exp) == 'lam_exp':
perf_legend = [lam['name'],lamx['name']]
perf_colors = [lam['pycolor'],lamx['pycolor']]
perf_lines = ['solid','solid']
perf_marks = ['o','^']
# Settings for FV3-CAM LAM-DA vs. LAM performance diagrams
elif str.upper(verf_job) == 'FV3CAM' and str.lower(verf_exp) == 'da_exp':
perf_legend = [lam['name'],lamda['name']]
perf_colors = [lam['pycolor'],lamda['pycolor']]
perf_lines = ['solid','solid']
perf_marks = ['o','D']
# Add data lines
for model in model_list:
ind = model_list.index(model)
pod = pod_list[ind]
far = far_list[ind]
sr = [1 - x for x in far]
line, = ax.plot(sr,pod,color=perf_colors[ind],linestyle=perf_lines[ind],label=perf_legend[ind],linewidth=3)
pts = ax.plot(sr,pod,color=perf_colors[ind],marker=perf_marks[ind],markersize=7)
# Add title and axis labels
titlestr = var_strings[str.upper(fcst_var)]+' Performance Diagram \n'+ \
region_strings[str.lower(region)]+' - Valid from '+vday1.strftime('%d %B %Y')+' to '+vday2.strftime('%d %B %Y')
ax.set_xlabel('Success Ratio (1-FAR)')
ax.set_ylabel('Probability of Detection (POD)')
plt.title(titlestr, fontweight='bold')
ax.tick_params(axis='both',length=5,width=1,which='major')
# Add CSI colorbar
cax = fig.add_axes([0.917, 0.2, 0.015, 0.65])
fig.colorbar(CSI_lines,cax=cax,norm=norm,ticks=bounds,spacing='proportional',orientation='vertical',label='CSI')
# Shrink current axis height by 10% on the bottom
box = ax.get_position()
ax.set_position([box.x0, box.y0 + box.height * 0.1, box.width, box.height * 0.9])
# Put a legend below current axis
ax.legend(loc='upper center', numpoints=2, bbox_to_anchor=(0.5, -0.1), fancybox=True, shadow=True, ncol=2)
plt.savefig(filename+'.png',bbox_inches='tight')
plt.close()
# Function to read METviewer data and replace reliability diagram
def reliability_diag(filename,plottype):
print('Remaking reliability diagram with python')
# Read METviewer data file
with open(filename+'.data','r') as f:
reader = csv.reader(f)
data_list = []
model_list = []
baser_list = []
calib_list = []
efreq_list = []
for row in reader:
row_list = row[0].split('\t')
# Build list of models to plot
if row_list[1] not in model_list and row_list[1] != 'model':
model_list.append(row_list[1])
# Build list of sample climatologies to plot
if row_list[4] == 'PSTD_BASER' and row_list[5] not in baser_list:
if len(baser_list) >= 1 and row_list[5] == 'NA':
# pass
# baser_list.append(np.nan)
baser_list.append(baser_list[-1])
else:
baser_list.append(row_list[5])
# Build list for easier iteration later
if row_list[0] != 'fcst_var':
data_list.append(row_list)
# Get fcst_var to use for title keys
fcst_var_entry = row_list[0]
for var_string in var_strings:
if var_string in fcst_var_entry:
fcst_var = var_string
# Get threshold to use for title keys
for x in thresholds:
if str(x) in fcst_var_entry:
thresh = str(x)
# Build list of stats
for model in model_list:
model_calib = []
model_baser = []
model_efreq = []
for row in data_list:
if row[1] == model and row[4] == 'PSTD_CALIBRATION':
if row[5] == 'NA':
model_calib.append(np.nan)
else:
model_calib.append(float(row[5]))
elif row[1] == model and row[4] == 'PSTD_NI':
if row[5] == 'NA':
model_efreq.append(0) # setting to zero instead of nan to avoid error with yscale('log')
else:
model_efreq.append(int(row[5]))
calib_list.append(model_calib)
efreq_list.append(model_efreq)
# Define points for reliability lines
if plottype == 'surrsvr':
xcoord = [0.0,0.02,0.05,0.1,0.15,0.3,0.45,0.6]
# xcoord = [0.01,0.35,0.75,0.125,0.225,0.375,0.525]
else:
xcoord = [0.05,0.15,0.25,0.35,0.45,0.55,0.65,0.75,0.85,0.95]
# Begin plotting
fig = plt.figure(figsize=[8.5,8])
ax = plt.subplot(111)
# Add perfect reliability line
relx = [0,1]
rely = [0,1]
rel_line, = ax.plot(relx,rely,"k-",linewidth=2)
# Settings for HREFv3 reliability diagrams
if str.upper(verf_job) == 'HREFV3':
# Diagrams comparing HREF and HREFX for radar and surrogate svr
if plottype[0:2] == 're' or plottype == 'surrsvr':
rel_legend = [hrefx['name']+' '+hrefx['nbmax']+' Prob',href['name']+' '+href['nbmax']+' Prob']
rel_colors = [hrefx['pycolor'],href['pycolor']]
rel_lty = ['solid','solid']
# Diagrams comparing HREF and HREFX for precip probabilities
elif plottype[1:] == 'hpcp_prob':
rel_legend = [hrefx['name']+' '+hrefx['prob'],href['name']+' '+href['prob']]
rel_colors = [hrefx['pycolor'],href['pycolor']]
rel_lty = ['solid','solid']
# Add reliability data lines
for ind in range(len(model_list)):
rel_pts = calib_list[ind]
clim = float(baser_list[ind])
# Add no resolution line
resx = [0,1]
resy = [clim,clim]
res_line, = ax.plot(resx,resy,color=rel_colors[ind],linestyle="--",linewidth=2)
# Add no skill line
skillx = [0,clim,1]
skilly = [clim*0.5,clim,clim+((1-clim)*0.5)]
skill_line, = ax.plot(skillx,skilly,color=rel_colors[ind],linestyle="--",linewidth=2)
# Add reliability line
rel_line, = ax.plot(xcoord,rel_pts,color=rel_colors[ind],linestyle=rel_lty[ind],label=rel_legend[ind],linewidth=3)
rel_pts = ax.plot(xcoord,rel_pts,color=rel_colors[ind],marker="o",markersize=7)
# Add main title and axis labels
if plottype == 'surrsvr':
titlestr = 'Surrogate Severe Reliability Diagram \n'+ \
region_strings[str.lower(region)]+' - Valid from '+vday1.strftime('%d %B %Y')+' to '+vday2.strftime('%d %B %Y')
else:
titlestr = 'Probability of '+str.upper(fcst_var)+' > '+thresh+' '+units[str.upper(fcst_var)]+' Reliability Diagram \n'+ \
region_strings[str.lower(region)]+' - Valid from '+vday1.strftime('%d %B %Y')+' to '+vday2.strftime('%d %B %Y')
plt.axis([0,1,0,1])
plt.xticks([0,0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1.0])
plt.yticks([0,0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1.0])
plt.xlabel("Forecast Probability")
plt.ylabel("Observed Relative Frequency")
plt.title(titlestr, fontweight='bold')
# Define points for positive BSS shaded area
shadex = [clim,1]
shadey = [clim,clim+((1-clim)*0.5)]
# Define points for no resolution positive BSS shaded area
shadex2 = [0,clim]
shadey2 = [0,clim]
# Shade positive BSS areas
plt.fill_between(shadex,shadey,1,facecolor='gray',alpha=0.25)
plt.fill_between(shadex2,0,shadey2,facecolor='gray',alpha=0.25)
# Add event histogram on inset
axins = inset_axes(ax, width="100%", height="100%", bbox_to_anchor=(.085, .69, .45, .3), bbox_transform=ax.transAxes, loc=2)
axins.set_zorder(10)
axins.set_yscale('log')
# axins.axis([0,1,10,10000000])
axins.set_xticks([0,0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1.0])
axins.set_xticklabels(["0","","0.2","","0.4","","0.6","","0.8","","1.0"])
# axins.set_yticks([10,100,1000,10000,100000,1000000,10000000])
# Add event histogram data lines
for ind in range(len(model_list)):
if ind == 0:
xpts = [x - 0.005 for x in xcoord]
elif ind == 1:
xpts = [x + 0.005 for x in xcoord]
else:
xpts = xcoord
efreq = efreq_list[ind]
line, = axins.plot(xpts,efreq,color=rel_colors[ind],linestyle=rel_lty[ind],linewidth=3)
pts = axins.plot(xpts,efreq,color=rel_colors[ind],marker="o",markersize=7)
# Add inset axis labels
axins.set_xlabel("Forecast Probability")
axins.set_ylabel("# Forecasts")
axins.grid(color="k")
# Shrink current axis height by 10% on the bottom
box = ax.get_position()
ax.set_position([box.x0, box.y0 + box.height * 0.1, box.width, box.height * 0.9])