-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfuncs.py
3228 lines (2223 loc) · 204 KB
/
funcs.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
# -*- coding: utf-8 -*-
"""
Created on Tue Aug 10 11:06:38 2021
@author: Derrick Muheki
"""
import os
import xarray as xr
import pandas as pd
import numpy as np
import re
import matplotlib.pyplot as plt
from matplotlib.patches import Ellipse
from matplotlib.patches import Patch
from matplotlib.lines import Line2D
import matplotlib.transforms as transforms
import matplotlib.gridspec as gridspec
import matplotlib.ticker as ticker
import matplotlib.colors as mcolors
import cartopy.crs as ccrs
import cartopy.feature as cfeature
from cartopy.mpl.ticker import LongitudeFormatter, LatitudeFormatter
from matplotlib import gridspec
from scipy import stats
from scipy.special import logsumexp
from scipy.stats import spearmanr
import seaborn as sns
from numpy.linalg import inv, det
from statistics import mean
from fractions import Fraction
#%% SETTING UP THE CURRENT WORKING DIRECTORY; for both the input and output folders
cwd = os.getcwd()
#%% Function to extract starting year from file name to use in the next function for the start period of the data
def read_start_year(file):
""" Read the starting year of the data from the file name
Parameters
----------
file : files in data directory (string)
Returns
-------
start_year (integer)
"""
# find the first consecutive 4 digits in the file name; which in our case represents the starting year of the data
years = re.findall('\\d{4}', file)
start_year = int(years.pop(0))
return start_year #returns start year that is used in decoding the times for the xarray data
#%% Function for reading NetCDF4 data
def nc_read(file, start_year, type_of_extreme_climate_event, time_dim):
""" Reading netcdfs based on occurrence variable & Clip out data for the study area: The East African Region
Parameters
----------
file : files in data directory (string)
occurrence_variable : target variable name (string)
Returns
-------
Xarray data array
"""
# initiate as dataset
ds = xr.open_dataset(file,decode_times=False)
# convert to data array for target variable
da = ds['exposure']
if time_dim:
# manually decode times from integer to datetime series
new_dates = pd.date_range(start=str(start_year)+'-1-1', periods=da.sizes['time'], freq='YS')
da['time'] = new_dates
# Clip out data for East African Region that lies between LATITUDES 24N and 13S & LONGITUDES 18E and 55E
latitude_bounds, longitude_bounds =[23.75, -12.75], [18.25, 54.75]
clipped_da = da.sel(lat=slice(*latitude_bounds), lon=slice(*longitude_bounds)) #Clipped dataset
return clipped_da
#%% Function for returning array showing the occurence of an extreme climate event at a location per year
def extreme_event(extreme_event_data):
""" Investigates the occurrence of an extreme event in a grid (location) per year
Parameters
----------
extreme_event_data : Xarray data array
Returns
Xarray data array (boolean where 1 means the extreme event was recorded in that location during that year)
"""
extreme_event = xr.where(extreme_event_data>0.005, 1, (xr.where(np.isnan(extreme_event_data), np.nan, 0))) #returns 1 where extreme event was recorded in that location during that year
return extreme_event
#%% Select from a list of Global Impact Models e.g. GHMs, GGCMS, GVMs etc. for which the Global Climate Models are based on
def impact_model(extreme_event, gcm):
""" Select from a list of Global Impact Models e.g. GHMs, GGCMS, GVMs etc. driven by the same Global Climate Models (GCMs)
Parameters
----------
extreme_event: String
gcm: String
Returns
-------
filtered_dataset: Global impact model' files driven by the same Global Climate Model and directories for the files (dataset).
"""
# List of Global Impact Models e.g. GHMs, GGCMS, GVMs etc.
list_of_gms = os.path.join(cwd, extreme_event)
all_available_of_impact_model_data_files_under_gcm = [] # List of available impact models per extreme event category
for gm in os.listdir(list_of_gms):
gms = os.path.join(list_of_gms, gm)
for file in os.listdir(gms):
impact_model_files_directory = os.path.join(gms, file)
all_available_of_impact_model_data_files_under_gcm.append(impact_model_files_directory)
# Filter out datasets to include only impact models driven by the same GCM
filter_data_with_gcm = re.compile('.*{}*'.format(gcm))
filtered_dataset = list(filter(filter_data_with_gcm.match,all_available_of_impact_model_data_files_under_gcm))
#print(filtered_dataset)
return filtered_dataset
#%% Function for returning extreme event occurrence per grid for a given scenario and given time period considering an ensemble of GCMs
def extreme_event_occurrence(type_of_extreme_climate_event, list_of_impact_models_driven_by_same_gcm, scenario_of_dataset):
""" Function for returning extreme event occurrence per grid for a given scenario and given time period considering an ensemble of GCMs
Parameters
----------
type_of_extreme_climate_event : String
list_of_impact_models_driven_by_same_gcm : List
scenario_of dataset : String
Returns
-------
Tuple (with [0] & [1] Xarray (Extreme event occurrences for respective time period))
"""
# Creating list for all available data files according to selected criteria: Extreme Event Type, Impact Model, Global Climate Model and Time Period/Scenario/RCP
extreme_event_datasets_in_the_scenario =[]
for gcm in list_of_impact_models_driven_by_same_gcm:
if('landarea' in gcm): #Selecting only the land area datafiles (exposure on land), thus excluding the available population datafiles within the dataset
if(scenario_of_dataset in gcm): #Selecting data for only the selected time period/scenario/RCP
#data_files = os.path.join(impact_model_list_of_gcms[1], gcm)
extreme_event_datasets_in_the_scenario.append(gcm)
print('The following files from their respective Global Climate Models (GCMs) are available for the time scenario and Global Impact Model selected: \n \n ')
print(*extreme_event_datasets_in_the_scenario, sep='\n')
print('------------------------------------------------------------------------------------------------------------------------------------')
print('')
print('*********PROCESSING DATA************PLEASE WAIT*********** \n')
# Filtering the extreme event datasets in the scenario for the different time periods (1661-1860, 1861-2005, 2006-2099 and 2100-2299)
# Filter out datasets for the period from 1661 until 1860
#filter_data_from_1661_until_1860 = re.compile('.*_1661_*') # start year of the period = 1661
#extreme_event_data_from_1661_until_1860 =list(filter(filter_data_from_1661_until_1860.match,extreme_event_datasets_in_the_scenario))
# Filter out datasets for the period from 1861 until 2005
filter_data_from_1861_until_2005 = re.compile('.*_1861_*') # start year of the period = 1861
extreme_event_data_from_1861_until_2005 =list(filter(filter_data_from_1861_until_2005.match,extreme_event_datasets_in_the_scenario))
# Filter out datasets for the period from 2006 until 2099
filter_data_from_2006_until_2099 = re.compile('.*_2006_*') # start year of the period = 2006
extreme_event_data_from_2006_until_2099 =list(filter(filter_data_from_2006_until_2099.match,extreme_event_datasets_in_the_scenario))
# Filter out datasets for the period from 2100 until 2299
# filter_data_from_2100_until_2299 = re.compile('.*_2100_*') # start year of the period = 2100
# extreme_event_data_from_2100_until_2299 =list(filter(filter_data_from_2100_until_2299.match,extreme_event_datasets_in_the_scenario))
# =============================================================================
# OCCURRENCE OF EXTREME EVENT WITHIN SCENARIO CONSIDERING THE MAXIMUM/EXTREME VALUES PER GRID FROM AN ENSEMBLE OF GCMS
# =============================================================================
# OCCURRENCE OF EXTREME EVENT FROM 1861 UNTIL 2005
occurrence_of_extreme_event_datasets_from_1861_until_2005 =[]
for file in extreme_event_data_from_1861_until_2005:
start_year_of_the_data = read_start_year(file) # function to get the starting year of the data from file name
extreme_event_from_1861_until_2005 = nc_read(file, start_year_of_the_data,type_of_extreme_climate_event, time_dim=True) # function to read the NetCDF4 files based on occurrence variable
# occurence of an extreme event...as a boolean...true or false
occurrence_of_extreme_event_from_1861_until_2005 = extreme_event(extreme_event_from_1861_until_2005) #returns 1 where an extreme event was recorded in that location during that year
# add the array with occurrences per GCM for same time period to list (that shall be iterated to get the extremes from the ENSEMBLE of these different GCMs)
occurrence_of_extreme_event_datasets_from_1861_until_2005.append(occurrence_of_extreme_event_from_1861_until_2005)
if len(occurrence_of_extreme_event_datasets_from_1861_until_2005) == 0: # check for empty data set list
print('No data available for the selected extreme events for the selected GCM scenario during the period from 1861 until 2015 \n *********PROCESSING DATA************PLEASE WAIT*********** \n')
occurrence_of_extreme_event_considering_ensemble_of_gcms_from_1861_until_2005 = xr.DataArray([]) #create empty array
else: # occurrence of extreme event in arrays for each available impact model driven by the same GCM
occurrence_of_extreme_event_considering_ensemble_of_gcms_from_1861_until_2005 = occurrence_of_extreme_event_datasets_from_1861_until_2005
# OCCURRENCE OF EXTREME EVENT FROM 2006 UNTIL 2099
occurrence_of_extreme_event_datasets_from_2006_until_2099 =[]
for file in extreme_event_data_from_2006_until_2099:
start_year_of_the_data = read_start_year(file) # function to get the starting year of the data from file name
extreme_event_from_2006_until_2099 = nc_read(file, start_year_of_the_data, type_of_extreme_climate_event, time_dim=True) # function to read the NetCDF4 files based on occurrence variable
# occurence of an extreme event...as a boolean...true or false
occurrence_of_extreme_event_from_2006_until_2099 = extreme_event(extreme_event_from_2006_until_2099) #returns 1 where an extreme event was recorded in that location during that year
# add the array with occurrences per GCM for ame time period to list (that shall be iterated to get the extremes from the ENSEMBLE of these different GCMs)
occurrence_of_extreme_event_datasets_from_2006_until_2099.append(occurrence_of_extreme_event_from_2006_until_2099)
if len(occurrence_of_extreme_event_datasets_from_2006_until_2099) == 0: # check for empty data set list
print('No data available for the selected extreme events for the selected GCM scenario during the period from 2006 until 2099 \n *********PROCESSING DATA************PLEASE WAIT*********** \n')
occurrence_of_extreme_event_considering_ensemble_of_gcms_from_2006_until_2099 = xr.DataArray([]) #create empty array
else: # occurrence of extreme event in arrays for each available impact model driven by the same GCM
occurrence_of_extreme_event_considering_ensemble_of_gcms_from_2006_until_2099 = occurrence_of_extreme_event_datasets_from_2006_until_2099
print('\n *******************PROCESSING************************ \n')
return occurrence_of_extreme_event_considering_ensemble_of_gcms_from_1861_until_2005, occurrence_of_extreme_event_considering_ensemble_of_gcms_from_2006_until_2099
#%% Function for returning array showing locations with the occurrence of compound events within the same location in the same year
def compound_event_occurrence(occurrence_of_event_1, occurrence_of_event_2):
""" Compare two arrays with occurrence of extreme climate events at the same locations and during the same years
Parameters
----------
occurrence_of_event_1 & occurrence_of_event_2 : Xarray data arrays for occurrence of extreme events
Returns
-------
Xarray data array (boolean with true for locations with the occurrence of both events within the same year)
"""
compound_event = np.logical_and(occurrence_of_event_1==1, occurrence_of_event_2==1)
compound_bin = xr.where(compound_event == True, 1, 0)#returns True for locations with occurence of compound events within same location in same year
nanq = np.logical_and(np.isnan(occurrence_of_event_1),np.isnan(occurrence_of_event_2)) #returns array where nan is true for both event 1 and event 2
compound_event_bin = xr.where(nanq==True, np.nan, compound_bin) #returns 1 where extreme event was recorded in that location during that year
return compound_event_bin
#%% Function for changing event names from the original Lange et. al (2020) dataset folder names
def event_name(type_of_extreme_climate_event_selected):
""" changing event names from the original Lange et. al (2020) dataset folder names
Parameters
----------
type_of_extreme_climate_event_selected : String
Returns
-------
String (Extreme Event name)
"""
if type_of_extreme_climate_event_selected == 'floodedarea':
event_name = 'River Floods'
if type_of_extreme_climate_event_selected == 'driedarea':
event_name = 'Droughts'
if type_of_extreme_climate_event_selected == 'heatwavedarea':
event_name = 'Heatwaves'
if type_of_extreme_climate_event_selected == 'cropfailedarea':
event_name = 'Crop Failures'
if type_of_extreme_climate_event_selected =='burntarea':
event_name = 'Wildfires'
if type_of_extreme_climate_event_selected == 'tropicalcyclonedarea':
event_name ='Tropical Cyclones'
return event_name
#%% Function for calculating the total number of years per location that experienced compound events.
def total_no_of_years_with_compound_event_occurrence(occurrence_of_compound_event):
""" Determine the total number of years throught the data period per location for which a compound extreme event was experienced
Parameters
----------
occurrence of compound extreme event : Xarray data array (boolean with true for locations with the occurrence of both events within the same year)
Returns
-------
Xarray with the total number of years throught the data period per location for which a compound extreme event was experienced
"""
# Number of years per region that experienced compound events
no_of_years_with_compound_events = (occurrence_of_compound_event).sum('time',skipna=False)
return no_of_years_with_compound_events
#%% Function for plotting map showing the total number of years per location that experienced compound events. FOR VISUALIZATION
def plot_total_no_of_years_with_compound_event_occurrence(no_of_years_with_compound_events, event_1_name, event_2_name, time_period, gcm, scenario):
""" Plot a map showing the total number of years throught the data period per location for which a compound extreme event was experienced
Parameters
----------
occurrence of compound extreme event : Xarray data array (boolean with true for locations with the occurrence of both events within the same year)
event_1_name, event_2_name : String (Extreme Events)
gcm: String (Driving GCM)
time_period: String
scenario: String
Returns
-------
Plot (Figure) showing the total number of years throught the data period per location for which a compound extreme event was experienced
"""
# Setting the projection of the map to cylindrical / Mercator
ax = plt.axes(projection=ccrs.PlateCarree())
# Add the background map to the plot
#ax.stock_img()
# Set the extent of the plot, in this case the East African Region
ax.set_extent([19,54,-12,23])
# Plot the coastlines along the continents on the map
ax.coastlines(color='dimgrey', linewidth=0.7)
# Plot features: lakes, rivers and boarders
ax.add_feature(cfeature.LAKES, alpha =0.5)
ax.add_feature(cfeature.RIVERS)
ax.add_feature(cfeature.OCEAN)
ax.add_feature(cfeature.LAND, facecolor ='lightgrey')
#ax.add_feature(cfeature.BORDERS, linestyle=':')
# Coordinates longitude and latitude ticks...These can be manipulated depending on study area chosen
ax.set_xticks([20, 30, 40, 50], crs=ccrs.PlateCarree()) # 20E up to 50E
ax.set_yticks([20, 10, 0, -10], crs=ccrs.PlateCarree()) # 20N up to 10S
lon_formatter = LongitudeFormatter()
lat_formatter = LatitudeFormatter()
ax.xaxis.set_major_formatter(lon_formatter)
ax.yaxis.set_major_formatter(lat_formatter)
# Plot the gridlines for the coordinate system on the map
#grid= ax.gridlines(draw_labels = False, dms = True )
#grid.top_labels = False #Removes the grid labels from the top of the plot
#grid.right_labels= False #Removes the grid labels from the right of the plot
# Plot number of years with occurrence of compound extreme events per location with the extent of the East African Region; Specified as (left, right, bottom, right)
plt.imshow(no_of_years_with_compound_events, origin = 'upper' , extent=(18.25, 54.75, -12.75, 23.75), cmap = plt.cm.get_cmap('viridis', 12))
# Text outside the plot to display the time period & scenario (top-right) and the two Global Impact Models used (bottom left)
plt.gcf().text(0.55,0.9,'{}, {}'.format(time_period, scenario), fontsize = 8)
plt.gcf().text(0.25,0.03,'{}'.format(gcm), fontsize= 6)
# Add the title and legend to the figure and show the figure
plt.title('Occurrence of Compound {} and {} \n'.format(event_1_name, event_2_name),fontsize=10) #Plot title
# discrete color bar legend
#bounds = [0,5,10,15,20,25,30]
plt.clim(0,30)
plt.colorbar(orientation = 'vertical', extend = 'max').set_label(label = 'Number of years', size = 9) #Plots the legend color bar
plt.xticks(fontsize=8, color = 'dimgrey') # color and size of longitude labels
plt.yticks(fontsize=8, color = 'dimgrey') # color and size of latitude labels
plt.show()
#plt.close()
return no_of_years_with_compound_events
#%% Function for calculating the Probability of joint occurrence of the extreme events in one grid cell over the entire dataset period
def probability_of_occurrence_of_compound_events(no_of_years_with_compound_events, occurrence_of_compound_event):
""" Determine the probability of occurrence of a compound extreme climate event over the entire dataset time period
Parameters
----------
occurrence of compound extreme event : Xarray data array (boolean with true for locations with the occurrence of both events within the same year)
Returns
-------
Xarray with the probability of joint occurrence of two extreme climate events over the entire dataset time period
"""
# Total number of years in the dataset
total_no_of_years_in_dataset = len(occurrence_of_compound_event)
# Probability of occurrence
probability_of_occurrence_of_the_compound_event = no_of_years_with_compound_events/total_no_of_years_in_dataset
return probability_of_occurrence_of_the_compound_event
#%% Function for plotting map showing the Probability of joint occurrence of the extreme events in one grid cell over the entire dataset period
def plot_probability_of_occurrence_of_compound_events(no_of_years_with_compound_events, event_1_name, event_2_name, time_period, gcm, scenario):
""" Plot a map showing the probability of occurrence of a compound extreme climate event over the entire dataset time period
Parameters
----------
occurrence of compound extreme event : Xarray data array (boolean with true for locations with the occurrence of both events within the same year)
event_1_name, event_2_name : String (Extreme Events)
gcm : String (Driving GCM)
time_period: String
scenario: String
Returns
-------
Plot (Figure) showing the probability of joint occurrence of two extreme climate events over the entire dataset time period
"""
# Probability of occurrence
probability_of_occurrence_of_the_compound_event = no_of_years_with_compound_events/50 # as 50 years were considered to determine the probability
# Setting the projection of the map to cylindrical / Mercator
ax = plt.axes(projection=ccrs.PlateCarree())
# Add the background map to the plot
#ax.stock_img()
# Set the extent of the plot, in this case the East African Region
ax.set_extent([19,54,-12,23])
# Plot the coastlines along the continents on the map
ax.coastlines(color='dimgrey', linewidth=0.7)
# Plot features: lakes, rivers and boarders
ax.add_feature(cfeature.LAKES, alpha =0.5)
ax.add_feature(cfeature.RIVERS)
ax.add_feature(cfeature.OCEAN)
ax.add_feature(cfeature.LAND, facecolor ='lightgrey')
#ax.add_feature(cfeature.BORDERS, linestyle=':')
# Coordinates longitude and latitude ticks...These can be manipulated depending on study area chosen
ax.set_xticks([20, 30, 40, 50], crs=ccrs.PlateCarree()) # 20E up to 50E
ax.set_yticks([20, 10, 0, -10], crs=ccrs.PlateCarree()) # 20N up to 10S
lon_formatter = LongitudeFormatter()
lat_formatter = LatitudeFormatter()
ax.xaxis.set_major_formatter(lon_formatter)
ax.yaxis.set_major_formatter(lat_formatter)
# Plot the gridlines for the coordinate system on the map
#grid= ax.gridlines(draw_labels = True, dms = True )
#grid.top_labels = False #Removes the grid labels from the top of the plot
#grid.right_labels= False #Removes the grid labels from the right of the plot
# Plot probability of occurrence of compound extreme events per location with the extent of the East African Region; Specified as (left, right, bottom, right)
plt.imshow(probability_of_occurrence_of_the_compound_event, origin = 'upper' , extent=(18.25, 54.75, -12.75, 23.75), cmap = plt.cm.get_cmap('viridis', 10))
# Text outside the plot to display the time period & scenario (top-right) and the two Global Impact Models used (bottom left)
plt.gcf().text(0.50,0.9,'{}, {}'.format(time_period, scenario), fontsize = 10)
plt.gcf().text(0.25,0.03,'{}'.format(gcm), fontsize= 10)
# Add the title and legend to the figure and show the figure
plt.title('Probability of joint occurrence of {} and {} \n'.format(event_1_name, event_2_name),fontsize=11) #Plot title
# discrete color bar legend
#bounds = [0, 0.2, 0.4, 0.6, 0.8, 1.0]
plt.colorbar( orientation = 'vertical').set_label(label = 'Probability of joint occurrence', size = 11) #Plots the legend color bar
plt.clim(0,1)
plt.xticks(fontsize=8, color = 'dimgrey') # color and size of longitude labels
plt.yticks(fontsize=8, color = 'dimgrey') # color and size of latitude labels
plt.show()
#plt.close()
return probability_of_occurrence_of_the_compound_event
#%% Function for plotting map showing the Probability Ration (PR) of joint occurrence of the extreme events in one grid cell over the entire dataset period
def plot_probability_ratio_of_occurrence_of_compound_events(probability_of_occurrence_of_the_compound_event_in_scenario, probability_of_occurrence_of_the_compound_event_in_historical_early_industrial_scenario, event_1_name, event_2_name, time_period, gcm, scenario):
""" Plot a map showing the probability of occurrence of a compound extreme climate event over the entire dataset time period
Parameters
----------
probability_of_occurrence_of_the_compound_event_in_scenario : Xarray data array (probability of joint occurrence of two extreme climate events over the entire dataset time period in new scenario)
probability_of_occurrence_of_the_compound_event_in_historical_early_industrial_scenario : Xarray data array (probability of joint occurrence of two extreme climate events over the entire dataset time period in historical early industrial time period)
event_1_name, event_2_name : String (Extreme Events)
gcm : String (Driving GCM)
time_period: String
scenario: String
Returns
-------
Plot (Figure) showing the Probability Ratio (PR) of joint occurrence of two extreme climate events to compare the change in new scenario from the historical early industrial times
"""
# Probability Ratio (PR) of occurrence: ratio between probability of occurrence of compound event in new situation (scenario) to the probability of occurrence in the reference situtaion (historical early industrial times)
probability_of_ratio_of_occurrence_of_the_compound_event = probability_of_occurrence_of_the_compound_event_in_scenario/probability_of_occurrence_of_the_compound_event_in_historical_early_industrial_scenario
# Setting the projection of the map to cylindrical / Mercator
ax = plt.axes(projection=ccrs.PlateCarree())
# Add the background map to the plot
#ax.stock_img()
# Set the extent of the plot, in this case the East African Region
ax.set_extent([19,54,-12,23])
# Plot the coastlines along the continents on the map
ax.coastlines(color='dimgrey', linewidth=0.7)
# Plot features: lakes, rivers and boarders
ax.add_feature(cfeature.LAKES, alpha =0.5)
ax.add_feature(cfeature.RIVERS)
ax.add_feature(cfeature.OCEAN)
ax.add_feature(cfeature.LAND, facecolor ='lightgrey')
#ax.add_feature(cfeature.BORDERS, linestyle=':')
# Coordinates longitude and latitude ticks...These can be manipulated depending on study area chosen
ax.set_xticks([20, 30, 40, 50], crs=ccrs.PlateCarree()) # 20E up to 50E
ax.set_yticks([20, 10, 0, -10], crs=ccrs.PlateCarree()) # 20N up to 10S
lon_formatter = LongitudeFormatter()
lat_formatter = LatitudeFormatter()
ax.xaxis.set_major_formatter(lon_formatter)
ax.yaxis.set_major_formatter(lat_formatter)
# Plot the gridlines for the coordinate system on the map
#grid= ax.gridlines(draw_labels = True, dms = True )
#grid.top_labels = False #Removes the grid labels from the top of the plot
#grid.right_labels= False #Removes the grid labels from the right of the plot
# Plot probability of occurrence of compound extreme events per location with the extent of the East African Region; Specified as (left, right, bottom, right)
plt.imshow(probability_of_ratio_of_occurrence_of_the_compound_event, origin = 'upper' , extent=(18.25, 54.75, -12.75, 23.75), cmap = plt.cm.get_cmap('viridis', 12))
# Text outside the plot to display the time period & scenario (top-right) and the two Global Impact Models used (bottom left)
plt.gcf().text(0.23,0.9,'Comparing {} ({}) to 1861-1890 (historical)'.format(time_period, scenario), fontsize = 9)
plt.gcf().text(0.25,0.03,'{}'.format(gcm), fontsize= 9)
# Add the title and legend to the figure and show the figure
plt.title('Average Probability Ratio of Joint Occurrence of {} and {} events \n'.format(event_1_name, event_2_name),fontsize=10) #Plot title
# discrete color bar legend
#bounds = [0, 0.2, 0.4, 0.6, 0.8, 1.0]
plt.colorbar( orientation = 'vertical', extend = 'max').set_label(label = 'Probability Ratio', size = 9) #Plots the legend color bar
plt.clim(0,30)
plt.xticks(fontsize=8, color = 'dimgrey') # color and size of longitude labels
plt.yticks(fontsize=8, color = 'dimgrey') # color and size of latitude labels
plt.show()
#plt.close()
return probability_of_ratio_of_occurrence_of_the_compound_event
#%% Plot average probability of compound events accross all impact models and all their driving GCMs
def plot_average_probability_of_occurrence_of_compound_events(average_probability_of_occurrence_of_compound_events_across_the_gcms, event_1_name, event_2_name, time_period, scenario):
""" Plot a map showing the probability of occurrence of a compound extreme climate event over the entire dataset time period
Parameters
----------
occurrence of compound extreme event : Xarray data array (boolean with true for locations with the occurrence of both events within the same year)
event_1_name, event_2_name : String (Extreme Events)
time_period: String
scenario: String
Returns
-------
Plot (Figure) showing the probability of joint occurrence of two extreme climate events over the entire dataset time period
"""
# Setting the projection of the map to cylindrical / Mercator
ax = plt.axes(projection=ccrs.PlateCarree())
# Add the background map to the plot
#ax.stock_img()
# Set the extent of the plot, in this case the East African Region
ax.set_extent([19,54,-12,23])
# Plot the coastlines along the continents on the map
ax.coastlines(color='dimgrey', linewidth=0.7)
# Plot features: lakes, rivers and boarders
ax.add_feature(cfeature.LAKES, alpha =0.5)
ax.add_feature(cfeature.RIVERS)
ax.add_feature(cfeature.OCEAN)
ax.add_feature(cfeature.LAND, facecolor ='lightgrey')
#ax.add_feature(cfeature.BORDERS, linestyle=':')
# Coordinates longitude and latitude ticks...These can be manipulated depending on study area chosen
ax.set_xticks([20, 30, 40, 50], crs=ccrs.PlateCarree()) # 20E up to 50E
ax.set_yticks([20, 10, 0, -10], crs=ccrs.PlateCarree()) # 20N up to 10S
lon_formatter = LongitudeFormatter()
lat_formatter = LatitudeFormatter()
ax.xaxis.set_major_formatter(lon_formatter)
ax.yaxis.set_major_formatter(lat_formatter)
# Plot the gridlines for the coordinate system on the map
#grid= ax.gridlines(draw_labels = True, dms = True )
#grid.top_labels = False #Removes the grid labels from the top of the plot
#grid.right_labels= False #Removes the grid labels from the right of the plot
# Plot probability of occurrence of compound extreme events per location with the extent of the East African Region; Specified as (left, right, bottom, right)
plt.imshow(average_probability_of_occurrence_of_compound_events_across_the_gcms, origin = 'upper' , extent=(18.25, 54.75, -12.75, 23.75), cmap = plt.cm.get_cmap('viridis', 12))
# Average probability across the entire region (1 value for the whole region per scenario)
average_probability_across_the_entire_region = average_probability_of_occurrence_of_compound_events_across_the_gcms.mean()
plt.gcf().text(0.25,0.01,'Average Probability across the entire region = {}'.format(round(average_probability_across_the_entire_region.item(), 3)), fontsize = 8)
# Text outside the plot to display the time period & scenario (top-right) and the two Global Impact Models used (bottom left)
plt.gcf().text(0.252,0.9,'{}, {}'.format(time_period, scenario), fontsize = 8)
# Incase you want to add the title to the plot
#plt.title('Average probability of joint occurrence of {} and {} considering all impact models and their respective driving GCMs'.format(event_1_name, event_2_name),fontsize=11) #Plot title
# discrete color bar legend
#bounds = [0, 0.2, 0.4, 0.6, 0.8, 1.0]
plt.colorbar( orientation = 'vertical', extend = 'max').set_label(label = 'Probability of joint occurrence', size = 11) #Plots the legend color bar
plt.clim(0,0.6)
plt.xticks(fontsize=11, color = 'black') # color and size of longitude labels
plt.yticks(fontsize=11, color = 'black') # color and size of latitude labels
# Change this directory to save the plots to your desired directory
#plt.savefig('C:/Users/dmuheki/OneDrive/PhD/Masters_thesis_paper/Ongoing_results/Average probability of joint occurrence of {} and {} under the {} scenario considering all impact models and their respective driving GCMs.pdf'.format(event_1_name, event_2_name, scenario), dpi = 300)
plt.show()
#plt.close()
return average_probability_of_occurrence_of_compound_events_across_the_gcms
#%% Function for plotting map showing the maximum number of years with consecutive compound events in the same location during the entire dataset period
def maximum_no_of_years_with_consecutive_compound_events(occurrence_of_compound_event):
"""Determine the maximum number of years with consecutive compound extreme events in the same location over the entire dataset period
Parameters
----------
occurrence of compound extreme event : Xarray data array (boolean with true for locations with the occurrence of both events within the same year)
Returns
-------
Xarray with the maximum number of years with consecutive compound extreme events in the same location over the entire dataset period
"""
# Calculates the cumulative sum and whenever a false is met, it resets the sum to zero. thus the .max() returns the maximum cummumlative sum along the entire time dimension
maximum_no_of_years_with_consecutive_compound_events = (occurrence_of_compound_event.cumsum('time',skipna=False) - occurrence_of_compound_event.cumsum('time',skipna=False).where(occurrence_of_compound_event.values == False).ffill('time').fillna(0)).max('time')
return maximum_no_of_years_with_consecutive_compound_events
#%% Function for plotting map showing the maximum number of years with consecutive compound events in the same location during the entire dataset period
def plot_maximum_no_of_years_with_consecutive_compound_events(average_maximum_no_of_years_with_consecutive_compound_events, event_1_name, event_2_name, time_period, gcm, scenario):
"""Plot a map showing the maximum number of years with consecutive compound extreme events in the same location over the entire dataset period
Parameters
----------
average_maximum_no_of_years_with_consecutive_compound_events : Xarray data array (with the maximum number of years with consecutive compound extreme events in the same location over the entire dataset period)
event_1_name, event_2_name : String (Extreme Events)
gcm : String (Driving GCM)
time_period: String
scenario: String
Returns
-------
Plot (Figure) showing the maximum number of years with consecutive compound extreme events in the same location over the entire dataset period
"""
# Setting the projection of the map to cylindrical / Mercator
ax = plt.axes(projection=ccrs.PlateCarree())
# Add the background map to the plot
#ax.stock_img()
# Set the extent of the plot, in this case the East African Region
ax.set_extent([19,54,-12,23])
# Plot the coastlines along the continents on the map
ax.coastlines(color='dimgrey', linewidth=0.7)
# Plot features: lakes, rivers and boarders
ax.add_feature(cfeature.LAKES, alpha =0.5)
ax.add_feature(cfeature.RIVERS)
ax.add_feature(cfeature.OCEAN)
ax.add_feature(cfeature.LAND, facecolor ='lightgrey')
#ax.add_feature(cfeature.BORDERS, linestyle=':')
# Coordinates longitude and latitude ticks...These can be manipulated depending on study area chosen
ax.set_xticks([20, 30, 40, 50], crs=ccrs.PlateCarree()) # 20E up to 50E
ax.set_yticks([20, 10, 0, -10], crs=ccrs.PlateCarree()) # 20N up to 10S
lon_formatter = LongitudeFormatter()
lat_formatter = LatitudeFormatter()
ax.xaxis.set_major_formatter(lon_formatter)
ax.yaxis.set_major_formatter(lat_formatter)
# Plot the gridlines for the coordinate system on the map
# grid= ax.gridlines(draw_labels = True, dms = True )
# grid.top_labels = False #Removes the grid labels from the top of the plot
# grid.right_labels= False #Removes the grid labels from the right of the plot
# Plot probability of occurrence of compound extreme events per location with the extent of the East African Region; Specified as (left, right, bottom, right)
plt.imshow(average_maximum_no_of_years_with_consecutive_compound_events, origin = 'upper' , extent=(18.25, 54.75, -12.75, 23.75), cmap = plt.cm.get_cmap('YlOrRd', 10))
# Text outside the plot to display the time period & scenario (top-right) and the two Global Impact Models used (bottom left)
plt.gcf().text(0.252,0.9,'{}, {}'.format(time_period, scenario), fontsize = 10)
plt.gcf().text(0.25,0.03,'{}'.format(gcm), fontsize= 10)
# Add the title and legend to the figure and show the figure
plt.title('Maximum no. of consecutive years with Joint occurrence of \n{} and {} \n '.format(event_1_name, event_2_name),fontsize=11) #Plot title
# discrete color bar legend
#bounds = [0,5,10,15,20,25,30]
plt.colorbar(orientation = 'vertical').set_label(label = 'Number of years', size = 11) #Plots the legend color bar
plt.clim(0,50)
plt.xticks(fontsize=8, color = 'dimgrey') # color and size of longitude labels
plt.yticks(fontsize=8, color = 'dimgrey') # color and size of latitude labels
plt.show()
plt.close()
return average_maximum_no_of_years_with_consecutive_compound_events
#%% Function for plotting map showing the averAGE maximum number of years with consecutive compound events in the same location during the entire dataset period CONSIDERING ALL IMPACT MODELS AND THIER RESPECTIVE DRIVING GCMS
def plot_average_maximum_no_of_years_with_consecutive_compound_events_considering_all_impact_models_and_their_driving_gcms(average_max_no_of_consecutive_years_with_compound_events, event_1_name, event_2_name, time_period, scenario):
"""Plot a map showing the maximum number of years with consecutive compound extreme events in the same location over the entire dataset period
Parameters
----------
average_max_no_of_consecutive_years_with_compound_events : Xarray data array (with the maximum number of years with consecutive compound extreme events in the same location over the entire dataset period)
event_1_name, event_2_name : String (Extreme Events)
time_period: String
scenario: String
Returns
-------
Plot (Figure) showing the average maximum number of years with consecutive compound extreme events in the same location over the entire dataset period
"""
# Setting the projection of the map to cylindrical / Mercator
ax = plt.axes(projection=ccrs.PlateCarree())
# Add the background map to the plot
#ax.stock_img()
# Set the extent of the plot, in this case the East African Region
ax.set_extent([19,54,-12,23])
# Plot the coastlines along the continents on the map
ax.coastlines(color='dimgrey', linewidth=0.7)
# Plot features: lakes, rivers and boarders
ax.add_feature(cfeature.LAKES, alpha =0.5)
ax.add_feature(cfeature.RIVERS)
ax.add_feature(cfeature.OCEAN)
ax.add_feature(cfeature.LAND, facecolor ='lightgrey')
#ax.add_feature(cfeature.BORDERS, linestyle=':')
# Coordinates longitude and latitude ticks...These can be manipulated depending on study area chosen
ax.set_xticks([20, 30, 40, 50], crs=ccrs.PlateCarree()) # 20E up to 50E
ax.set_yticks([20, 10, 0, -10], crs=ccrs.PlateCarree()) # 20N up to 10S
lon_formatter = LongitudeFormatter()
lat_formatter = LatitudeFormatter()
ax.xaxis.set_major_formatter(lon_formatter)
ax.yaxis.set_major_formatter(lat_formatter)
# Plot the gridlines for the coordinate system on the map
# grid= ax.gridlines(draw_labels = True, dms = True )
# grid.top_labels = False #Removes the grid labels from the top of the plot
# grid.right_labels= False #Removes the grid labels from the right of the plot
# Plot probability of occurrence of compound extreme events per location with the extent of the East African Region; Specified as (left, right, bottom, right)
plt.imshow(average_max_no_of_consecutive_years_with_compound_events, origin = 'upper' , extent=(18.25, 54.75, -12.75, 23.75), cmap = plt.cm.get_cmap('YlOrRd', 12))
# Text outside the plot to display the time period & scenario (top-right) and the two Global Impact Models used (bottom left)
plt.gcf().text(0.252,0.9,'{}, {}'.format(time_period, scenario), fontsize = 10)
# Incase you want to add the title and legend to the figure and show the figure
#plt.title('Maximum no. of consecutive years with Joint occurrence of \n{} and {} \n '.format(event_1_name, event_2_name),fontsize=11) #Plot title
# discrete color bar legend
#bounds = [0,5,10,15,20,25,30]
plt.colorbar(orientation = 'vertical', extend = 'max').set_label(label = 'Number of years', size = 11) #Plots the legend color bar
plt.clim(0,30)
plt.xticks(fontsize=11, color = 'black') # color and size of longitude labels
plt.yticks(fontsize=11, color = 'black') # color and size of latitude labels
# Change this directory to save the plots to your desired directory
#plt.savefig('C:/Users/dmuheki/OneDrive/PhD/Masters_thesis_paper/Ongoing_results/Average maximum number of years with concurrent {} and {} demonstrated by multi model ensembles under the {} scenario.pdf'.format(event_1_name, event_2_name, scenario), dpi = 300)
plt.show()
#plt.close()
return average_max_no_of_consecutive_years_with_compound_events
#%% A timeseries showing the fraction of the area affected by an extreme event across full timescale in the scenario
def timeseries_fraction_of_area_affected(occurrence_of_extreme_event, entire_globe_grid_cell_areas_in_xarray):
""" A timeseries showing the fraction of the area affected (AS A PERCENTAGE) by an extreme event OR compound extreme event
Parameters
----------
occurrence_of_extreme_event : Xarray
Returns
-------
Timeseries (Xarray)
"""
# Clip out cell grid area data for East African Region that lies between LATITUDES 24N and 13S & LONGITUDES 18E and 55E
latitude_bounds, longitude_bounds =[23.75, -12.75], [18.25, 54.75]
east_africa_grid_cell_areas = entire_globe_grid_cell_areas_in_xarray.sel(lat=slice(*latitude_bounds), lon=slice(*longitude_bounds)) #Clipped dataset
# mask area with nan values e.g. over the ocean
masked_area_affected_by_occurrence_of_extreme_event = xr.where(np.isnan(occurrence_of_extreme_event), np.nan, east_africa_grid_cell_areas)
# mask area without occurrence of compound events
area_affected_by_occurrence_of_extreme_event = xr.where(occurrence_of_extreme_event == 1, masked_area_affected_by_occurrence_of_extreme_event, np.nan)
# total area affected by occurrence of compound events per year
total_area_affected_by_occurrence_of_extreme_event = area_affected_by_occurrence_of_extreme_event.sum(dim=['lon', 'lat'], skipna=True)
# total area of the region (excluding the ocean)
total_area_of_the_region = masked_area_affected_by_occurrence_of_extreme_event.sum(dim=['lon','lat'], skipna= True)
# percentage of area affected
percentage_of_area_affected_by_occurrence_of_extreme_event = (total_area_affected_by_occurrence_of_extreme_event/total_area_of_the_region)*100
return percentage_of_area_affected_by_occurrence_of_extreme_event
#%% Plot timeseries showing the fraction of the area affected by the compound extreme event across full timescale in the scenario
def plot_timeseries_fraction_of_area_affected_by_compound_events(timeseries_of_joint_occurrence_of_compound_events, event_1_name, event_2_name, gcm):
""" Plot timeseries showing the fraction of the area affected by the compound extreme event across full timescale in the scenario
Parameters
----------
timeseries_of_joint_occurrence_of_compound_events : Tuple
Returns
Time series plot
"""
colors = [(0.996, 0.89, 0.569), (0.996, 0.769, 0.31), (0.996, 0.6, 0.001), (0.851, 0.373, 0.0549), (0.6, 0.204, 0.016)] # color palette
plt.figure(figsize = (5.5,4))
# Considering a 10-year moving average window to reduce the noise in the timeseries plots
# historical plot #considering historical starting from 1930
all_impact_model_historical_timeseries = xr.concat(timeseries_of_joint_occurrence_of_compound_events[0], dim='impact_model').mean(dim='impact_model', skipna= True) # Mean accross all impact models driven by the same GCM
historical_timeseries = (all_impact_model_historical_timeseries[69:]).rolling(time=10, min_periods=1).mean()
std_historical_timeseries = (all_impact_model_historical_timeseries[69:]).rolling(time=10, min_periods=1).std() # standard deviation accross all impact models driven by the same GCM
lower_line_historical_timeseries = (historical_timeseries - 2 * std_historical_timeseries) # lower 95% confidence interval
upper_line_historical_timeseries = (historical_timeseries + 2 * std_historical_timeseries) # upper 95% confidence interval
plot1 = historical_timeseries.plot.line(x ='time', color=(0.996, 0.89, 0.569), add_legend='False') # plot line
plot1_fill = plt.fill_between(np.ravel(np.array((historical_timeseries.time), dtype = 'datetime64[ns]')), xr.where((lower_line_historical_timeseries.squeeze())<0,0,(lower_line_historical_timeseries.squeeze())), xr.where((upper_line_historical_timeseries.squeeze())>100,100,(upper_line_historical_timeseries.squeeze())), color=(0.996, 0.89, 0.569), alpha = 0.1) # plot the uncertainty bands #np.ravel() to avoid arrays in arrays e.g [[]]
# rcp26 plot
all_impact_model_rcp26_timeseries = xr.concat(timeseries_of_joint_occurrence_of_compound_events[1], dim='impact_model').mean(dim='impact_model', skipna= True) # Mean accross all impact models driven by the same GCM
rcp26_timeseries = (all_impact_model_rcp26_timeseries).rolling(time=10, min_periods=1).mean()
std_rcp26_timeseries = (all_impact_model_rcp26_timeseries).rolling(time=10, min_periods=1).std() # standard deviation accross all impact models driven by the same GCM
lower_line_rcp26_timeseries = (rcp26_timeseries - 2 * std_rcp26_timeseries) # lower 95% confidence interval
upper_line_rcp26_timeseries = (rcp26_timeseries + 2 * std_rcp26_timeseries) # upper 95% confidence interval
plot2 = rcp26_timeseries.plot.line(x = 'time', color=(0.996, 0.6, 0.001), add_legend='False') # plot line
plot2_fill = plt.fill_between(np.ravel(np.array((rcp26_timeseries.time), dtype = 'datetime64[ns]')), xr.where((lower_line_rcp26_timeseries.squeeze())<0,0,(lower_line_rcp26_timeseries.squeeze())), xr.where((upper_line_rcp26_timeseries.squeeze())>100,100,(upper_line_rcp26_timeseries.squeeze())), color=(0.996, 0.6, 0.001), alpha = 0.1) # plot the uncertainty bands
# rcp60 plot
all_impact_model_rcp60_timeseries = xr.concat(timeseries_of_joint_occurrence_of_compound_events[2], dim='impact_model').mean(dim='impact_model', skipna= True) # Mean accross all impact models driven by the same GCM
rcp60_timeseries = (all_impact_model_rcp60_timeseries).rolling(time=10, min_periods=1).mean()
std_rcp60_timeseries = (all_impact_model_rcp60_timeseries).rolling(time=10, min_periods=1).std() # standard deviation accross all impact models driven by the same GCM
lower_line_rcp60_timeseries = (rcp60_timeseries - 2 * std_rcp60_timeseries) # lower 95% confidence interval
upper_line_rcp60_timeseries = (rcp60_timeseries + 2 * std_rcp60_timeseries) # upper 95% confidence interval
plot3 = rcp60_timeseries.plot.line(x= 'time', color= (0.851, 0.373, 0.0549), add_legend='False') # plot line
plot3_fill = plt.fill_between(np.ravel(np.array((rcp60_timeseries.time), dtype = 'datetime64[ns]')), xr.where((lower_line_rcp60_timeseries.squeeze())<0,0,(lower_line_rcp60_timeseries.squeeze())), xr.where((upper_line_rcp60_timeseries.squeeze())>100,100,(upper_line_rcp60_timeseries.squeeze())), color=(0.851, 0.373, 0.0549), alpha = 0.1) # plot the uncertainty bands
# legend in order of plots: historical, rcp2.6, rcp6.0
plt.legend([(plot1[0],plot1_fill), (plot2[0],plot2_fill), (plot3[0],plot3_fill)],['historical','rcp2.6','rcp6.0'], loc = 'upper left', frameon= False, fontsize = 12)
if len(timeseries_of_joint_occurrence_of_compound_events) == 4:
#rcp85 plot
all_impact_model_rcp85_timeseries = xr.concat(timeseries_of_joint_occurrence_of_compound_events[3], dim='impact_model').mean(dim='impact_model', skipna= True) # Mean accross all impact models driven by the same GCM
rcp85_timeseries = (all_impact_model_rcp85_timeseries).rolling(time=10, min_periods=1).mean()
std_rcp85_timeseries = (all_impact_model_rcp85_timeseries).rolling(time=10, min_periods=1).std() # standard deviation accross all impact models driven by the same GCM
lower_line_rcp85_timeseries = (rcp85_timeseries - (2 * std_rcp85_timeseries)) # lower 95% confidence interval
upper_line_rcp85_timeseries = (rcp85_timeseries + (2 * std_rcp85_timeseries)) # upper 95% confidence interval
plot4 = rcp85_timeseries.plot.line(x= 'time', color= (0.6, 0.204, 0.016), add_legend='False') # plot line
plot4_fill = plt.fill_between(np.ravel(np.array((rcp85_timeseries.time), dtype = 'datetime64[ns]')), xr.where((lower_line_rcp85_timeseries.squeeze())<0,0,(lower_line_rcp85_timeseries.squeeze())), xr.where((upper_line_rcp85_timeseries.squeeze())>100,100,(upper_line_rcp85_timeseries.squeeze())), color=(0.6, 0.204, 0.016), alpha = 0.1) # plot the uncertainty bands
# legend in order of plots: historical, rcp2.6, rcp6.0, rcp8.5
plt.legend([(plot1[0],plot1_fill), (plot2[0],plot2_fill), (plot3[0],plot3_fill), (plot4[0],plot4_fill)],['historical','rcp2.6','rcp6.0', 'rcp8.5'], loc = 'upper left', frameon= False, fontsize = 12)
# Add the title and legend to the figure and show the figure
plt.title('Timeseries showing the fraction of region with Joint occurrence of \n {} and {} '.format(event_1_name, event_2_name),fontsize=12) #Plot title
plt.ylim(0,70)
plt.xlabel('Years', fontsize = 10)
plt.ylabel('Percentage of area', fontsize =10)
plt.tight_layout()
plt.gcf().text(0.12,0.03,'{}'.format(gcm), fontsize= 10)
plt.show()
return timeseries_of_joint_occurrence_of_compound_events
#%% Plot comparison timeseries showing the fraction of the area affected by extreme events across a 50 year timescale in the scenario
def plot_comparison_timeseries_fraction_of_area_affected_by_extreme_events(timeseries_of_occurrence_of_extreme_event_1, timeseries_of_occurrence_of_extreme_event_2, timeseries_of_fraction_of_area_with_occurrence_of_compound_events_during_same_time_period, event_1_name, event_2_name, time_period, gcm, scenario):
""" Plot comparison timeseries showing the fraction of the area affected by the extreme events across 50 year timescale in the scenario
Parameters
----------
timeseries_of_occurrence_of_extreme_event_1, timeseries_of_occurrence_of_extreme_event_2, timeseries_of_fraction_of_area_with_occurrence_of_compound_events_during_same_time_period : Arrays
Returns
Time series plot
"""
plt.figure(figsize = (5.5,4))
# extreme event 1
timeseries_of_occurrence_of_extreme_event_1.plot.line(x = 'time', color='blue', add_legend='False')
# extreme event 2
timeseries_of_occurrence_of_extreme_event_2.plot.line(x ='time', color='green', add_legend='False')
# joint occurrence
timeseries_of_fraction_of_area_with_occurrence_of_compound_events_during_same_time_period.plot.line(x ='time', color='red', add_legend='False')
# legend in order of plots: historical, rcp2.6, rcp6.0
plt.legend([event_1_name,event_2_name,'Joint occurrence'], loc = 'upper left', frameon= False)
plt.title('Timeseries showing the percentage of the region with \n Occurrence of {} and {} \n '.format(event_1_name, event_2_name),fontsize=11) #Plot title
plt.gcf().text(0.68,0.85,'{}, {}'.format(time_period, scenario), fontsize = 10)
plt.gcf().text(0.12,0.03,'{}'.format(gcm), fontsize= 10)
plt.ylim(0,100)
plt.xlabel('Years', fontsize = 12)
plt.ylabel('Percentage of area', fontsize = 12)
plt.tight_layout()
plot_comparison = plt.show()
return plot_comparison
#%% Function for plotting the confidence ellipse of the covariance of two extreme event occurrences
def confidence_ellipse(x, y, ax, **kwargs):
"""
Create a plot of the covariation confidence ellipse op `x` and `y`
Parameters
----------
x, y : array_like, shape (n, )
Input data
Returns
-------
float: the Pearson Correlation Coefficient for `x` and `y`.