-
Notifications
You must be signed in to change notification settings - Fork 0
/
plots_revisions.py
1564 lines (1298 loc) · 52.7 KB
/
plots_revisions.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
"""
Created on Mon Aug 31 17:04:50 2020
@author: Tim Busker
"""
"""
- 1/5 jaar events zijn bijna allemaal in zomer, dus andere maanden eruit filteren.
- Hoe gaan we om met n=1 per pixel. Ruimtelijk poolen? Maar dan zitten we met onhafhneklijkheid
- voorstel: 1/1, 1/2, en 1/5 kaartje en kijken of ruimtelijke patronen houden
-
-
"""
# Reset all variables
%reset
# %%
import sys
import os
from os import listdir
import xarray as xr
import matplotlib.pyplot as plt
import numpy as np
import dask
from dask.diagnostics import ProgressBar
import regionmask
import geopandas as gpd
pbar = ProgressBar()
pbar.register()
import cartopy
import cartopy.crs as ccrs
import cartopy.feature as cfeature
import seaborn as sns
import colour
from colour import Color
import matplotlib.colors
from matplotlib.colors import LinearSegmentedColormap
from matplotlib.lines import Line2D
import matplotlib.patches as mpatches
import matplotlib.lines as mlines
import matplotlib.colors as mcolors
import matplotlib.colorbar as mcolorbar
import pandas as pd
# %%
###############################################################################################################################
##################################################### Setup ###################################################################
###############################################################################################################################
##################################### Paths #####################################
home = "/scistor/ivm/tbr910/" # \\scistor.vu.nl\shares\BETA-IVM-BAZIS\tbr910\ # /scistor/ivm/tbr910/
path_base = home + "precip_analysis"
path_obs = home + "precip_analysis/obs"
path_forecasts = home + "precip_analysis/forecasts"
path_obs_for = home + "precip_analysis/obs_for"
path_q = home + "precip_analysis/quantiles"
path_cont = home + "precip_analysis/cont_metrics"
path_efi = home + "ECMWF/files_efi/"
path_verif = home + "precip_analysis/verif_files"
path_obs_for_new = home + "precip_analysis/obs_for_new_LT"
path_figs = home + "precip_analysis/figures/revisions/"
path_return_periods = "/scistor/ivm/tbr910/precip_analysis/return_periods_europe"
##################################### Config #####################################
# General config
indicator = "efi" # efi, sot (or ES?)
shift = 1
resolution = "025"
day_month = "06_09" # day and month seperated by an underscore
# vars to load the area files
season = "_summer" # Empty for all seasons (extra desciption that was added to the input files in PEV.py (optional)). _season to select a specific season
addition='_FINAL5' # _description --> for Fval graphs seasonal thresholds are not yet supported (needs change in code)
loader=season+addition # loader for the area files
# vars to load the Europe map --> for European map
season_EU="_seasonal" # Empty for all seasons (extra desciption that was added to the input files in PEV.py (optional)). _season to select a specific season
addition_EU='_FINAL5' # _description
eu_map_loader=season_EU+addition_EU # loader for the EU files
# plot config
log_axis=True # if True, plot the x-axis on a log scale
# precipitation threshold
"""
Define precipitation threshold, options:
- Fixed percentiles: 0.95, 0.98, 0.99 (method var: quantile_extremes)
- Fixed rainfall amounts (mm): 40, 60, 90 (method var: threshold_method, not implemented yet?)
- Fixed return periods: 5RP, 10RP, 20RP (method var: return_periods)
"""
p_threshold = "5RP"
expected_CF= 1/(int(p_threshold.replace("RP",""))*365) # expected coverage factor for the return period
# C_L
find_C_L_max = False # if True, we want to find the PEV for the C_L ratio for which Fval is max. If false, we want to find the PEV for a specific C_L ratio (specified in C_L_best_estimate)
C_L_best_estimate = 0.08 # 0.08 used in paper.
C_L_min = 0.02
C_L_max = 0.18
##################################### Load data #####################################
os.chdir(path_verif)
# Europe files
file_accessor_EU_map = f'{day_month}_{str(p_threshold).replace(".","")}_S{shift}{eu_map_loader}.nc' # takes already the max Fval file
Fval_merged_efi = xr.open_dataset("Fval_merged_efi_%s" % (file_accessor_EU_map)) # load seasonal or non-seasonal map
Fval_merged_sot = xr.open_dataset("Fval_merged_sot_%s" % (file_accessor_EU_map)) # load seasonal or non-seasonal map
# save name for the figures
save_name_EU_map= f"{indicator}_{file_accessor_EU_map}" # save name for the figures
# specific area files
file_accessor= f'{day_month}_{str(p_threshold).replace(".","")}_S{shift}{loader}.nc' # file accessor for area files (no seasonal threshold)
Fval_region_efi = xr.open_dataset("Fval_area_merged_efi_%s" % (file_accessor))
Fval_region_sot = xr.open_dataset("Fval_area_merged_sot_%s" % (file_accessor))
# save name for the figures
save_name= f"{indicator}_{file_accessor}" # save name for the figures
################################## filter out the C_L of 1 or >1 ##################################
# Filter out the values of C_L that are equal to 1 or greater than 1
Fval_merged_efi = Fval_merged_efi.where((Fval_merged_efi.C_L < 1), drop=True)
Fval_merged_sot = Fval_merged_sot.where((Fval_merged_sot.C_L < 1), drop=True)
Fval_region_sot = Fval_region_sot.where((Fval_region_sot.C_L < 1), drop=True)
Fval_region_efi = Fval_region_efi.where((Fval_region_efi.C_L < 1), drop=True)
##################################### Retrieve lon lats for the ROI #####################################
"""
lon lat boxes
"[2.5, 14, 47.5, 55] --> large area Western Europe (used till now)
[3.95,7.8,49.3,51.3] --> Affected by 2021 floods
[-10, 20, 39, 55] --> much larger (rondom?) area
[1,7.8,48,52] --> area based on many events
[3.5,7.8,48,52] --> area based on many events (excluding coastal area of france) --> used in rev.
"""
# retrieve lon lat box as saved in the Fval_region file as attributes
lon_lat_box = Fval_region_efi.attrs["lon_slice"] + Fval_region_efi.attrs["lat_slice"]
lon_lat_box = (
lon_lat_box.replace("slice", "")
.replace("None", "")
.replace(",", "")
.replace("(", "")
.replace(")", "")
) # remove the words slice and None
lon_lat_box = [float(i) for i in (lon_lat_box.split())]
lon_lat_box[2], lon_lat_box[3] = (
lon_lat_box[3],
lon_lat_box[2],
) # switch last two numbers
print("lon_lat_box:", lon_lat_box)
lon_slice = slice(lon_lat_box[0], lon_lat_box[1]) # in case of area selection
lat_slice = slice(lon_lat_box[3], lon_lat_box[2]) # in case of area selection
################################### Load the cont metrics ###################################
# Load contingency metrics over all seasons
cont_efi_eu = xr.open_dataset("cont_metrics_merged_efi_%s" % (file_accessor_EU_map))
cont_sot_eu = xr.open_dataset("cont_metrics_merged_sot_%s" % (file_accessor_EU_map))
# Load contingency metrics for specific season (in loader)
cont_efi = xr.open_dataset("cont_metrics_merged_efi_%s" % (file_accessor)) # mostly for single season
cont_sot = xr.open_dataset("cont_metrics_merged_sot_%s" % (file_accessor)) # mostly for single season
n_event_mask=cont_efi_eu.isel(lead=0).isel(ew_threshold=0).n_events>0 # mask for pixels with at least one event
n_event_mask=n_event_mask.drop_vars("lead").drop_vars("ew_threshold") # drop lead and ew_threshold dimensions
os.chdir(path_base)
quality_mask = xr.open_dataset(
path_base + "/quality_mask_%s.nc" % resolution
) # includes land-sea and X% nan criteria
# mask the quality mask
cont_efi_eu = cont_efi_eu.where(quality_mask.rr == 0, np.nan)
cont_sot_eu = cont_sot_eu.where(quality_mask.rr == 0, np.nan)
cont_efi = cont_efi.where(quality_mask.rr == 0, np.nan)
cont_sot = cont_sot.where(quality_mask.rr == 0, np.nan)
############################################################ print n event statistics ################################################
print(
"average number of events per pixel in the whole area over all seasons :",
cont_efi_eu.n_events.mean().values,
)
print(
"average number of events per pixel on the ROI over all seasons:", Fval_region_efi.n_events.mean().values
)
print("total number of events on the ROI over all seasons:", Fval_region_efi.attrs)
################################### mask pixels with 0 events ###################################
#Fval_region_efi=Fval_region_efi.where(n_event_mask)
#Fval_region_sot=Fval_region_sot.where(n_event_mask)
cont_efi_eu=cont_efi_eu.where(n_event_mask)
cont_sot_eu=cont_sot_eu.where(n_event_mask)
cont_efi=cont_efi.where(n_event_mask)
cont_sot=cont_sot.where(n_event_mask)
######################################## save cont ROI for the figures ########################################
# select the cont metrics for the ROI
cont_efi_ROI=cont_efi.sel(longitude=lon_slice, latitude=lat_slice) # select the cont metrics for the ROI
cont_sot_ROI=cont_sot.sel(longitude=lon_slice, latitude=lat_slice) # select the cont metrics for the ROI
# %%
###############################################################################################################################
########################################### European Fval plot for EFI and SOT ################################################
###############################################################################################################################
########################## Select the right C_L ratio ##########################
if find_C_L_max == True: # Find and select max Fval
if indicator == "efi":
if 'seasonal' in eu_map_loader:
Fval_plot = Fval_merged_efi.max(dim=("C_L")).Fval
else:
Fval_plot = Fval_merged_efi.max(dim=("C_L", "ew_threshold")).Fval
elif indicator == "sot":
if 'seasonal' in eu_map_loader:
Fval_plot = Fval_merged_sot.max(dim=("C_L")).Fval
else:
Fval_plot = Fval_merged_sot.max(dim=("C_L", "ew_threshold")).Fval
else: # or select the Fval for a specific C_L ratio
if indicator == "efi":
Fval_plot = Fval_merged_efi.copy()
elif indicator == "sot":
Fval_plot = Fval_merged_sot.copy()
Fval_plot = Fval_plot.sel(C_L=C_L_best_estimate).Fval # select the Fval for the C_L ratio we want to plot
if 'seasonal' not in eu_map_loader:
Fval_plot = Fval_plot.max(dim="ew_threshold") # only needed if the max is not already calculated in the merger_seasons.py script
########################## Plot parameters ##########################
vmin = 0.0 # min value for the colorbar
vmax = 0.8 # max value for the colorbar
# red to green colormap
cmap_F = plt.cm.get_cmap("RdYlBu", 16) # colormap, colorblindfriendly
# cmap_F=plt.cm.get_cmap('Greens', 10) # alternative colormap
# cut the Fval plot on 40 degree east longitude
Fval_plot = Fval_plot.sel(longitude=slice(None, 40))
# latitude 35 degrees
Fval_plot = Fval_plot.sel(latitude=slice(None, 35))
########################## Start plotting ##########################
fig = plt.figure(figsize=(20, 9)) # (W,H)
proj0 = ccrs.PlateCarree(central_longitude=0)
# 5 subplots (in circle)
gs = fig.add_gridspec(2, 3, wspace=0.2, hspace=0.2)
ax1 = fig.add_subplot(
gs[:, 0], projection=proj0
) # ax1 over the first column stretching over 2 rows
ax2 = fig.add_subplot(gs[0, 1], projection=proj0)
ax3 = fig.add_subplot(gs[0, 2], projection=proj0)
ax4 = fig.add_subplot(gs[1, 2], projection=proj0)
ax5 = fig.add_subplot(gs[1, 1], projection=proj0)
# ax1
plot1 = Fval_plot.isel(lead=0).plot.pcolormesh(
ax=ax1,
transform=ccrs.PlateCarree(central_longitude=0),
add_colorbar=False,
vmin=vmin,
vmax=vmax,
cmap=cmap_F,
) # plot the first lead
lead = Fval_plot.isel(lead=0).lead.values
ax1.set_title("lead=%s " % (lead), size=20)
gl = ax1.gridlines(
crs=proj0, draw_labels=True, linewidth=2, color="gray", alpha=0.5, linestyle="--"
)
gl.top_labels = True
gl.right_labels = True
gl.left_labels = True
gl.bottom_labels = True
gl.xlabel_style = {"color": "gray"}
gl.ylabel_style = {"color": "gray"}
ax1.coastlines()
ax1.add_feature(cfeature.BORDERS)
# ax2
Fval_plot.isel(lead=1).plot.pcolormesh(
ax=ax2,
transform=ccrs.PlateCarree(central_longitude=0),
add_colorbar=False,
vmin=vmin,
vmax=vmax,
cmap=cmap_F,
) # plot the second lead
lead = Fval_plot.isel(lead=1).lead.values
ax2.set_title("lead=%s " % (lead), size=20)
gl = ax2.gridlines(
crs=proj0, draw_labels=True, linewidth=2, color="gray", alpha=0.5, linestyle="--"
)
gl.top_labels = True
gl.right_labels = False
gl.left_labels = True
gl.bottom_labels = False
gl.xlabel_style = {"color": "gray"}
gl.ylabel_style = {"color": "gray"}
ax2.coastlines()
ax2.add_feature(cfeature.BORDERS)
# ax3
Fval_plot.isel(lead=2).plot.pcolormesh(
ax=ax3,
transform=ccrs.PlateCarree(central_longitude=0),
add_colorbar=False,
vmin=vmin,
vmax=vmax,
cmap=cmap_F,
) # plot the third lead
lead = Fval_plot.isel(lead=2).lead.values
ax3.set_title("lead=%s " % (lead), size=20)
gl = ax3.gridlines(
crs=proj0, draw_labels=True, linewidth=2, color="gray", alpha=0.5, linestyle="--"
)
gl.top_labels = True
gl.right_labels = True
gl.left_labels = False
gl.bottom_labels = False
gl.xlabel_style = {"color": "gray"}
gl.ylabel_style = {"color": "gray"}
ax3.coastlines()
ax3.add_feature(cfeature.BORDERS)
# ax4
Fval_plot.isel(lead=3).plot.pcolormesh(
ax=ax4,
transform=ccrs.PlateCarree(central_longitude=0),
add_colorbar=False,
vmin=vmin,
vmax=vmax,
cmap=cmap_F,
) # plot the fourth lead
lead = Fval_plot.isel(lead=3).lead.values
ax4.set_title("lead=%s " % (lead), size=20)
gl = ax4.gridlines(
crs=proj0, draw_labels=True, linewidth=2, color="gray", alpha=0.5, linestyle="--"
)
gl.top_labels = False
gl.right_labels = True
gl.left_labels = False
gl.bottom_labels = True
gl.xlabel_style = {"color": "gray"}
gl.ylabel_style = {"color": "gray"}
ax4.coastlines()
ax4.add_feature(cfeature.BORDERS)
# ax5
Fval_plot.isel(lead=4).plot.pcolormesh(
ax=ax5,
transform=ccrs.PlateCarree(central_longitude=0),
add_colorbar=False,
vmin=vmin,
vmax=vmax,
cmap=cmap_F,
) # plot the fifth lead
lead = Fval_plot.isel(lead=4).lead.values
ax5.set_title("lead=%s " % (lead), size=20)
gl = ax5.gridlines(
crs=proj0, draw_labels=True, linewidth=2, color="gray", alpha=0.5, linestyle="--"
)
gl.top_labels = False
gl.right_labels = False
gl.left_labels = True
gl.bottom_labels = True
gl.xlabel_style = {"color": "gray"}
gl.ylabel_style = {"color": "gray"}
ax5.coastlines()
ax5.add_feature(cfeature.BORDERS)
# Add the ROI to each subplot
ax1.add_patch(
mpatches.Rectangle(
xy=[lon_lat_box[0], lon_lat_box[2]],
width=lon_lat_box[1] - lon_lat_box[0],
height=lon_lat_box[3] - lon_lat_box[2],
linewidth=2,
edgecolor="black",
facecolor="none",
transform=ccrs.PlateCarree(central_longitude=0),
)
)
ax2.add_patch(
mpatches.Rectangle(
xy=[lon_lat_box[0], lon_lat_box[2]],
width=lon_lat_box[1] - lon_lat_box[0],
height=lon_lat_box[3] - lon_lat_box[2],
linewidth=2,
edgecolor="black",
facecolor="none",
transform=ccrs.PlateCarree(central_longitude=0),
)
)
ax3.add_patch(
mpatches.Rectangle(
xy=[lon_lat_box[0], lon_lat_box[2]],
width=lon_lat_box[1] - lon_lat_box[0],
height=lon_lat_box[3] - lon_lat_box[2],
linewidth=2,
edgecolor="black",
facecolor="none",
transform=ccrs.PlateCarree(central_longitude=0),
)
)
ax4.add_patch(
mpatches.Rectangle(
xy=[lon_lat_box[0], lon_lat_box[2]],
width=lon_lat_box[1] - lon_lat_box[0],
height=lon_lat_box[3] - lon_lat_box[2],
linewidth=2,
edgecolor="black",
facecolor="none",
transform=ccrs.PlateCarree(central_longitude=0),
)
)
ax5.add_patch(
mpatches.Rectangle(
xy=[lon_lat_box[0], lon_lat_box[2]],
width=lon_lat_box[1] - lon_lat_box[0],
height=lon_lat_box[3] - lon_lat_box[2],
linewidth=2,
edgecolor="black",
facecolor="none",
transform=ccrs.PlateCarree(central_longitude=0),
)
)
################# Colorbar #################
cax1 = fig.add_axes([0.4, 0.05, 0.3, 0.03]) # [left, bottom, width, height]
cbar = plt.colorbar(plot1, pad=0.00, cax=cax1, orientation="horizontal", cmap=cmap_F)
cbar.set_label(label="PEV", size="20", weight="bold")
cbar.ax.tick_params(labelsize=15)
cbar.set_ticks(np.round(cbar.get_ticks(), 2))
########################################### save ################################################
# set title to plot
plt.suptitle(
f"Potential economic value (PEV) for {indicator} {eu_map_loader} {C_L_best_estimate} ",
size=20,
)
fig.tight_layout()
plt.savefig(path_figs + "PEV_MAP_%s_%s.pdf" % (save_name_EU_map,C_L_best_estimate), bbox_inches="tight")
plt.show()
plt.close()
#%%
###############################################################################################################################
########################################### Early-Warning Thresholds graph ####################################################
###############################################################################################################################
if indicator == "efi":
Fval_plot = Fval_region_efi.copy()
elif indicator == "sot":
Fval_plot = Fval_region_sot.copy()
os.chdir(path_verif)
###################### Retrieve thresholds for EFI and SOT ######################
thresholds_plot = Fval_plot.ew_threshold.values.tolist()
###################### Plotting parameters ######################
fig = plt.figure(figsize=(20, 30)) # H,W
# seaborn cool style
sns.set_style("darkgrid", {"axes.facecolor": ".9"})
gs = fig.add_gridspec(20, 20, wspace=3, hspace=1.5)
ax1 = fig.add_subplot(gs[0:6, 0:6]) # Y,X
ax2 = fig.add_subplot(gs[0:6, 6:12], sharey=ax1)
ax3 = fig.add_subplot(gs[0:6, 12:18], sharey=ax1)
ax4 = fig.add_subplot(gs[7:13, 0:6])
ax5 = fig.add_subplot(gs[7:13, 6:12])
plt.setp(ax2.get_yticklabels(), visible=False)
plt.setp(ax3.get_yticklabels(), visible=False)
plt.setp(ax5.get_yticklabels(), visible=False)
# plt.setp(ax6.get_yticklabels(), visible=False)
label_x = "Cost-loss ratio"
label_y = "Potential economic value (PEV)" # V$_{ECMWFseas5}$
label_x_size = 25
label_y_size = 25
label_fontsize = 25
x_ticks = np.arange(0, 0.7, 0.2) # [0.0,0.4,0.8]
y_ticks = np.arange(0.2, 0.8, 0.2) # [0.2, 0.6, 1.0] 0.2,1.1,0.2
y_lim = 0.75
if log_axis==True:
x_lim = [0.0, 1]
else:
x_lim = [0, 0.6]
tick_size = 15
title_size = 30
linewidth = 0.5
###################### Colormap ######################
# Define the thresholds you want to include in the legend
# legend_thresholds = [thresholds_plot[i] for i in [0, len(thresholds_plot)//4, len(thresholds_plot)//2, 3*len(thresholds_plot)//4, -1]]
# get a list of rgb colors from yellow to orange to red, with length of the number of efi thresholds
colors = colour.Color("yellow").range_to(colour.Color("red"), len(thresholds_plot))
hex_colors = [color.hex for color in colors]
cmap = mcolors.LinearSegmentedColormap.from_list("my_colormap", hex_colors)
###################### Generate the plot ######################
# Define a function to plot the data
def plot_data(
ax,
lead,
hex_colors,
thresholds_plot,
linewidth,
label_x,
label_x_size,
label_y,
label_y_size,
x_lim,
y_lim,
x_ticks,
y_ticks,
tick_size,
label_fontsize,
):
Fval_lead = Fval_plot.isel(lead=lead)
Fval_lead = Fval_lead.mean(
dim=("latitude", "longitude")
) # new, because before the PEV script already calculated the spatial average
C_L = Fval_lead.C_L.values
for ew_threshold in thresholds_plot:
Fval = Fval_lead.sel(ew_threshold=ew_threshold).Fval.values
ax.plot(
C_L,
Fval,
label="efi threshold= %s" % (str(ew_threshold)),
color=hex_colors[thresholds_plot.index(ew_threshold)],
linewidth=linewidth,
)
lead = str(Fval_lead.lead.values)
ax.set_title("lead=%s" % (lead), size=title_size)
#ax.set_xlabel(label_x, size=label_x_size, weight="bold")
# ax.set_xlim(x_lim)
ax.set_ylim([0, y_lim])
#ax.set_xticks(x_ticks)
ax.set_yticks(y_ticks)
ax.tick_params(axis="both", which="major", labelsize=tick_size)
ax.tick_params(axis="both", which="minor", labelsize=tick_size)
if log_axis==True:
# Set the x-axis to a logarithmic scale
ax.set_xscale('log')
# Set the x-ticks and x-tick labels
x_ticks = [0.00001, 0.0001, 0.001, 0.01, 0.1,1]
ax.set_xticks(x_ticks)
ax.set_xticklabels([str(tick) for tick in x_ticks])
# rotate x-tick labels
ax.tick_params(axis='x', rotation=45)
ax.grid(True, which="major", linestyle="--", linewidth=0.7, alpha=0.6, color="black")
ax.tick_params(
axis="both",
which="major",
direction="out",
length=6,
labelsize=13,
colors="black",
)
# Call the function for each subplot
plot_data(
ax1,
0,
hex_colors,
thresholds_plot,
linewidth,
label_x,
label_x_size,
label_y,
label_y_size,
x_lim,
y_lim,
x_ticks,
y_ticks,
tick_size,
label_fontsize,
)
plot_data(
ax2,
1,
hex_colors,
thresholds_plot,
linewidth,
label_x,
label_x_size,
label_y,
label_y_size,
x_lim,
y_lim,
x_ticks,
y_ticks,
tick_size,
label_fontsize,
)
plot_data(
ax3,
2,
hex_colors,
thresholds_plot,
linewidth,
label_x,
label_x_size,
label_y,
label_y_size,
x_lim,
y_lim,
x_ticks,
y_ticks,
tick_size,
label_fontsize,
)
plot_data(
ax4,
3,
hex_colors,
thresholds_plot,
linewidth,
label_x,
label_x_size,
label_y,
label_y_size,
x_lim,
y_lim,
x_ticks,
y_ticks,
tick_size,
label_fontsize,
)
plot_data(
ax5,
4,
hex_colors,
thresholds_plot,
linewidth,
label_x,
label_x_size,
label_y,
label_y_size,
x_lim,
y_lim,
x_ticks,
y_ticks,
tick_size,
label_fontsize,
)
# Set ylabel for ax4
ax4.set_ylabel(label_y, size=label_y_size, weight="bold")
# Create custom legend
# legend_elements = [Line2D([0], [0], color=hex_colors[thresholds_plot.index(threshold)], lw=linewidth, label='efi threshold= %s'%(str(threshold))) for threshold in legend_thresholds]
# ax5.legend(handles=legend_elements, fontsize=label_fontsize, loc='lower right', bbox_to_anchor=(2, 0))
###################### Colorbar ######################
cax = fig.add_axes(
[0.25, 0.33, 0.4, 0.02]
) # Adjust these values to position the colorbar
norm = mcolors.Normalize(
vmin=min(thresholds_plot), vmax=max(thresholds_plot)
) # Normalize the colorbar
cb = mcolorbar.ColorbarBase(
cax, cmap=cmap, norm=norm, orientation="horizontal"
) # Create the colorbar
cb.set_label(
f"{indicator} Threshold", size=label_fontsize, weight="bold"
) # Set the label
cb.ax.tick_params(labelsize=label_fontsize) # Set tick label size
# Set ticks at the minimum, maximum, and some middle thresholds
middle_values = [
thresholds_plot[i]
for i in [
len(thresholds_plot) // 4,
len(thresholds_plot) // 2,
3 * len(thresholds_plot) // 4,
]
]
cb.set_ticks([min(thresholds_plot)] + middle_values + [max(thresholds_plot)])
# legend and show/save
# ax5.legend(fontsize=label_fontsize, loc='lower right', bbox_to_anchor=(2, 0))
# plt.savefig(path_figs+'/C_L.pdf', bbox_inches='tight')
plt.show()
# %%
###############################################################################################################################
########################################### PEV graph + warning thresholds ####################################################
###############################################################################################################################
os.chdir(path_verif)
################# Load area data from the ROI #################
# efi
Fval_efi = Fval_region_efi.Fval # defined in beginning script
# Fval_efi = Fval_efi.mean(
# dim=("longitude","latitude")
# ) # new in this revisions version, because before the PEV script already calculated the spatial average
# # sot
Fval_sot = Fval_region_sot.Fval
#Fval_sot = Fval_sot.mean(dim=("longitude","latitude")) # also new, see above
################################## STEP 1: Find ew thresholds per C/L value which generate maximum PEV ############################################
# these lines first identify the ew thresholds used to get the max PEV, then calculate the max PEV and attach the ew thresholds to this dataset
############ SOT #############
Fval_sot_max_index = Fval_sot.argmax(dim=("ew_threshold"))
ew_threshold_max = Fval_sot.ew_threshold[
Fval_sot_max_index
] # get the ew_thresholds for which the PEV is max
Fval_sot = Fval_sot.max(dim=("ew_threshold")) # get the max PEV for each C/L
Fval_sot = Fval_sot.to_dataset(name="Fval")
Fval_sot["ew_threshold_max"] = (
ew_threshold_max # add the ew_thresholds for which the PEV is max to the dataset
)
############ EFI #############
Fval_efi_max_index = Fval_efi.argmax(dim=("ew_threshold"))
ew_threshold_max = Fval_efi.ew_threshold[
Fval_efi_max_index
] # get the ew_thresholds for which the PEV is max
Fval_efi = Fval_efi.max(dim=("ew_threshold")) # get the max PEV for each C/L
Fval_efi = Fval_efi.to_dataset(name="Fval")
Fval_efi["ew_threshold_max"] = (
ew_threshold_max # add the ew_thresholds for which the PEV is max to the dataset
)
#################################### Step 2: retrieve the cont metrics for these ew thresholds (for C/L we want to calculate, either specific value or the one giving heighest PEV) ##################################
lead_cont = "5 days" # lead time for which we want to calculate the cont metrics
######### EFI #########
Fval_efi_lead = Fval_efi.sel(lead=lead_cont)
# 2.1: Select PEV and find/select C/L ratio
if find_C_L_max == True:
PEV_cont_efi = Fval_efi_lead.where(
Fval_efi_lead.Fval == Fval_efi_lead.Fval.max(), drop=True
) # select PEV max
C_L_best_estimate_efi = (
PEV_cont_efi.C_L.values
) # get the C_L ratio for which the PEV is max
else:
C_L_best_estimate_efi = (
C_L_best_estimate
) # use the C_L ratio specified in the config
PEV_cont_efi = Fval_efi_lead.sel(
C_L=C_L_best_estimate_efi
) # select the PEV for this C_L ratio
# 2.2 Retrieve early warning threshold that gives this max PEV
ew_max_efi = PEV_cont_efi.ew_threshold_max.values
# 2.3 use this ew threshold to select the cont metrics for this ew threshold
cont_max_efi = (
cont_efi_ROI.sel(ew_threshold=ew_max_efi)
.sel(lead=lead_cont)
.sum(dim=("latitude", "longitude"))
) # before it was mean, now sum to get the total number of events
n_fa_efi = float(cont_max_efi.false_alarms.values) # false alarms
n_hits_efi = float(cont_max_efi.hits.values) # hits
n_misses_efi = float(cont_max_efi.misses.values) # misses
n_cn_efi = float(cont_max_efi.correct_negatives.values) # correct negatives
far_efi = n_fa_efi / (n_fa_efi + n_cn_efi) # false alarm rate
hr_efi = n_hits_efi / (n_hits_efi + n_misses_efi) # hit rate
######### SOT #########
Fval_sot_lead = Fval_sot.sel(lead=lead_cont)
# 2.1: Select PEV and find/select C/L ratio
if find_C_L_max == True:
PEV_cont_sot = Fval_sot_lead.where(
Fval_sot_lead.Fval == Fval_sot_lead.Fval.max(), drop=True
)
C_L_best_estimate_sot = PEV_cont_sot.C_L.values
else:
C_L_best_estimate_sot = C_L_best_estimate
PEV_cont_sot = Fval_sot_lead.sel(C_L=C_L_best_estimate_sot)
# 2.2 Retrieve early warning threshold that gives this max PEV
ew_max_sot = PEV_cont_sot.ew_threshold_max.values
# 2.3 use this ew threshold to select the cont metrics for this ew threshold
cont_max_sot = (
cont_sot_ROI.sel(ew_threshold=ew_max_sot)
.sel(lead=lead_cont)
.sum(dim=("latitude", "longitude"))
) # before it was mean, now sum to get the total number of events
n_fa_sot = float(cont_max_sot.false_alarms.values) # false alarms
n_hits_sot = float(cont_max_sot.hits.values) # hits
n_misses_sot = float(cont_max_sot.misses.values) # misses
n_cn_sot = float(cont_max_sot.correct_negatives.values) # correct negatives
far_sot = n_fa_sot / (n_fa_sot + n_cn_sot) # false alarm rate
hr_sot = n_hits_sot / (n_hits_sot + n_misses_sot) # hit rate
print(
f"there are {n_fa_efi/n_hits_efi} and {n_fa_sot/n_hits_sot} false alarms per hit for EFI and SOT, respectively"
)
######################################## PEVmax graph ########################################################
# get data for the plot
Fval_sot_plot = Fval_sot.Fval
Fval_efi_plot = Fval_efi.Fval
#Reset to matplotlib's default style
matplotlib.rcParams.update(matplotlib.rcParamsDefault)
lead_times = Fval_efi.lead.values
# Create 2 subplots
fig, axs = plt.subplots(1, 2, figsize=(10, 5), sharey=True)
# adjust widthspace
plt.subplots_adjust(wspace=0.2)
if log_axis==True:
x_lim = [0.0, 1]
else:
x_lim = [0, 0.6]
y_lim = 1
# Custom color palette
colors = sns.color_palette("mako", 5)
# Plot the data
for ax, Fval, title, n_hits, n_fa, n_misses, n_cn, hr, far, ew_threshold in zip(
axs,
[Fval_efi_plot, Fval_sot_plot],
["EFI", "SOT"],
[n_hits_efi, n_hits_sot],
[n_fa_efi, n_fa_sot],
[n_misses_efi, n_misses_sot],
[n_cn_efi, n_cn_sot],
[hr_efi, hr_sot],
[far_efi, far_sot],
[float(ew_max_efi), float(ew_max_sot)],
):
legend_handles = []
for i in range(5):
(line,) = ax.plot(
Fval.C_L, Fval.isel(lead=i), color=colors[i], linewidth=3, alpha=0.7
)
ax.fill_between(
Fval.C_L, 0, Fval.isel(lead=i), color=line.get_color(), alpha=0.1
)
# Highlight the peak of the curve
max_pev = Fval.isel(lead=i).max()
max_cl = Fval.C_L[Fval.isel(lead=i).argmax()]
ax.plot(max_cl, max_pev, "o", color=line.get_color())
# Add a horizontal line at the peak
# ax.hlines(max_pev, ax.get_xlim()[0], ax.get_xlim()[1], colors=line.get_color(), linestyles='dashed', alpha=0.5)
# Create a custom legend handle
legend_handles.append(
mlines.Line2D(
[],
[],
color=line.get_color(),
marker="o",
markersize=5,
label=f"Lead: {i+1} days",
)
)
ax.set_xlabel("Action costs / prevented damage (C/L)", size=13, weight="bold")
ax.set_ylabel("Forecast Value (PEV)", size=13, weight="bold")
ax.set_ylim([0, y_lim])
ax.set_yticks(np.arange(0.2, 0.8, 0.2))
if log_axis==True:
# Set the x-axis to a logarithmic scale
ax.set_xscale('log')
# Set the x-ticks and x-tick labels
x_ticks = [0.00001, 0.0001, 0.001, 0.01, 0.1,1]
ax.set_xticks(x_ticks)
ax.set_xticklabels([str(tick) for tick in x_ticks])
# rotate x-tick labels
ax.tick_params(axis='x', rotation=45)
ax.grid(True, which="major", linestyle="--", linewidth=0.7, alpha=0.6, color="black")
ax.tick_params(
axis="both",
which="major",
direction="out",
length=6,
labelsize=13,
colors="black",
)
else:
ax.set_xticks(np.arange(0, 0.7, 0.2))
ax.grid(True, which="both", linestyle="--", linewidth=0.7, alpha=0.6, color="black")
ax.tick_params(
axis="both",
which="both",
direction="out",
length=6,
labelsize=13,
colors="black",
)
# Add minor ticks
# ax.minorticks_on()
ax.set_xlim(x_lim)
# Add grid for both major and minor ticks
############################################# Add table with cont metrics #############################################
row_labels = ["Early Warning \n Early Action", "No Warning \n No Action"]
col_labels = [" Extreme Rainfall \n Observed", " Extreme Rainfall \n Not Observed"]
cell_text = [
[f"Hits \n(n={int(round(n_hits,2))})", f"False Alarms \n(n={int(round(n_fa,2))})"],
[
f"Misses \n(n={int(round(n_misses,2))})",
f"Correct Negatives \n(n={int(round(n_cn,2))})",
],
]
bbox = [-0.2, 1.1, 1, 0.4] if title == "EFI" else [0.4, 1.1, 1, 0.4]
# Get the color of the line that corresponds to a lead of 1 day
table_color = colors[1]
# Change the color of the table lines
table = ax.table(
cellText=cell_text,
rowLabels=row_labels,
colLabels=col_labels,
cellLoc="center",
loc="upper center",
bbox=bbox,
)
table.auto_set_font_size(False)
table.set_fontsize(13)
for (row, col), cell in table.get_celld().items():
if (row == 0) or (col == -1):
cell.set_fontsize(13)
cell.set_text_props(weight="bold")