-
Notifications
You must be signed in to change notification settings - Fork 0
/
global_funcs.py
6687 lines (4871 loc) · 375 KB
/
global_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 Thu Aug 10 10:00:00 2023
@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 matplotlib as mpl
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
import itertools
#%% SETTING UP THE CURRENT WORKING DIRECTORY; for both the input and output folders
cwd = os.getcwd()
#%% SETTING MAP EXTENT
# Entire globe
map_extent = [-180, 180, -60, 90] # (longitude min, longitude max, latitude min, latitude max)
#%% 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 Specific Region that lies between LATITUDES ##N and ##S & LONGITUDES ##E and ##E
latitude_bounds, longitude_bounds =[90, -60], [-180, 180]
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 and O where false, as well as NaN values e.g., over the ocean
return extreme_event
#%% 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 plotting map showing the length of spell with impacts (years with consecutive occurrence of an extreme event) in the same location over the entire dataset period
def length_of_spell_with_occurrence_of_extreme_event(occurrence_of_extreme_event):
"""Determine the length of spell with impacts (years with consecutive occurrence of an extreme event) 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 an extreme event within the same year)
Returns
-------
Xarray with the length of spell with impacts (years with consecutive occurrence of an extreme event) 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
length_of_spell_with_occurrence_of_extreme_event = (occurrence_of_extreme_event.cumsum('time',skipna=False) - occurrence_of_extreme_event.cumsum('time',skipna=False).where(occurrence_of_extreme_event.values == False).ffill('time').fillna(0))
return length_of_spell_with_occurrence_of_extreme_event
#%% Function for plotting map showing the maximum number of years with consecutive occurrence of an extreme event in the same location during the entire dataset period
def maximum_no_of_years_with_consecutive_ocuurence_of_an_extreme_event(length_of_spell_with_occurrence_of_extreme_event):
"""Determine the maximum number of years with consecutive occurrence of an extreme event 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 an extreme event within the same year)
Returns
-------
Xarray with the maximum number of years with consecutive occurrence of an extreme event 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_ocuurence_of_an_extreme_event = length_of_spell_with_occurrence_of_extreme_event.max('time')
return maximum_no_of_years_with_consecutive_ocuurence_of_an_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 driven by the same Global Climate Model and Time Period/Scenario/RCP
extreme_event_datasets_in_the_scenario =[]
for impact_model in list_of_impact_models_driven_by_same_gcm:
if('landarea' in impact_model): #Selecting only the land area datafiles (exposure on land), thus excluding the available population datafiles within the dataset
if(scenario_of_dataset in impact_model): #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(impact_model)
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 calculating the total number of years per location that experienced extreme events.
def total_no_of_years_with_occurrence_of_extreme_event(occurrence_of_extreme_event):
""" Determine the total number of years throught the data period per location for which an extreme event was experienced
Parameters
----------
occurrence of compound extreme event : Xarray data array (boolean with true for locations with the occurrence of an extreme event within the same year)
Returns
-------
Xarray with the total number of years throught the data period per location for which an extreme event was experienced
"""
# Number of years per region that experienced compound events
total_no_of_years_with_occurrence_of_extreme_event = (occurrence_of_extreme_event).sum('time',skipna=False)
return total_no_of_years_with_occurrence_of_extreme_event
#%% 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 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 plotn
ax.set_extent([-180, 180, 90, -60], crs=ccrs.PlateCarree())
# 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([-180, -120, -60, 0, 60, 120, 180], crs=ccrs.PlateCarree()) # 20E up to 50E
ax.set_yticks([90, 60, 30, 0, -30, -60], 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= map_extent, 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.65,0.85,'{}, {}'.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 = 'horizontal', extend = 'max', shrink = 0.5).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 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_considering_all_gcms(average_no_of_years_with_compound_events_per_scenario_and_gcm, event_1_name, event_2_name, gcms):
""" Plot a map showing the total number of years throught the data period per location for which a compound extreme event was experienced
Parameters
----------
average_no_of_years_with_compound_events_per_scenario_and_gcm : Xarray data array
event_1_name, event_2_name : String (Extreme Events)
gcms: List of gcms (Driving GCM)
time_period: String
scenarios: List of gcms
Returns
-------
Plot (Figure) showing the total number of years throught the data period per location for which a compound extreme event was experienced
"""
#average_no_of_years_with_compound_events_per_scenario_and_gcm = [[],[],[],[],[]] # Where order of list is early industrial, present day, rcp 2.6, rcp6.0 and rcp 8.5
for scenario in range(len(average_no_of_years_with_compound_events_per_scenario_and_gcm)):
if scenario == 0:
scenario_name = 'Early-industrial'
if scenario == 1:
scenario_name = 'Present-Day'
if scenario == 2:
scenario_name = 'RCP2.6'
if scenario == 3:
scenario_name = 'RCP6.0'
if scenario == 4:
scenario_name = 'RCP8.5'
average_no_of_years_with_compound_events_per_gcm = average_no_of_years_with_compound_events_per_scenario_and_gcm[scenario]
# Setting the projection of the map to cylindrical / Mercator
fig, axs = plt.subplots(2,2, figsize=(10, 6.5), subplot_kw = {'projection': ccrs.PlateCarree()}) # , constrained_layout=True
# since axs is a 2 dimensional array of geozaxes, we have to flatten it into 1D; as explained on a similar example on this page: https://kpegion.github.io/Pangeo-at-AOES/examples/multi-panel-cartopy.html
axs=axs.flatten()
# Add the background map to the plot
#ax.stock_img()
if scenario == 4 and event_1_name == 'Crop Failures' or scenario == 4 and event_2_name == 'Crop Failures':
print('No data available for the crop failures for the selected GCM scenario under RCP8.5')
plt.close()
else:
for gcm in range(len(average_no_of_years_with_compound_events_per_gcm)):
# Plot per GCM in a subplot
plot = axs[gcm].imshow(average_no_of_years_with_compound_events_per_gcm[gcm], origin = 'upper' , extent= map_extent, cmap = plt.cm.get_cmap('viridis', 12), vmin = 0, vmax =30)
# Add the background map to the plot
#ax.stock_img()
# Set the extent of the plotn
axs[gcm].set_extent([-180, 180, 90, -60], crs=ccrs.PlateCarree())
# Plot the coastlines along the continents on the map
axs[gcm].coastlines(color='dimgrey', linewidth=0.7)
# Plot features: lakes, rivers and boarders
axs[gcm].add_feature(cfeature.LAKES, alpha =0.5)
axs[gcm].add_feature(cfeature.RIVERS)
axs[gcm].add_feature(cfeature.OCEAN)
axs[gcm].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
xticks = [-180, -120, -60, 0, 60, 120, 180] # Longitudes
axs[gcm].set_xticks(xticks, crs=ccrs.PlateCarree()) # 20E up to 50E
axs[gcm].set_xticklabels(xticks, fontsize = 8)
yticks = [90, 60, 30, 0, -30, -60]
axs[gcm].set_yticks(yticks, crs=ccrs.PlateCarree()) # 20N up to 10S
axs[gcm].set_yticklabels(yticks, fontsize = 8)
lon_formatter = LongitudeFormatter()
lat_formatter = LatitudeFormatter()
axs[gcm].xaxis.set_major_formatter(lon_formatter)
axs[gcm].yaxis.set_major_formatter(lat_formatter)
# Subplot labels
# label
subplot_labels = ['a.','b.','c.','d.']
axs[gcm].text(0, 1.06, subplot_labels[gcm], transform=axs[gcm].transAxes, fontsize=9, ha='left')
# GCM
gcm_name = gcms[gcm] # GCM
if gcm_name == 'gfdl-esm2m':
gcm_title = 'GFDL-ESM2M'
if gcm_name == 'hadgem2-es':
gcm_title = 'HadGEM2-ES'
if gcm_name == 'ipsl-cm5a-lr':
gcm_title = 'IPSL-CM5A-LR'
if gcm_name == 'miroc5':
gcm_title = 'MIROC5'
axs[gcm].set_title(gcm_title, fontsize = 9, loc = 'right')
# Add the title and legend to the figure and show the figure
fig.suptitle('Occurrence of Compound {} and {} \n'.format(event_1_name, event_2_name),fontsize=10) #Plot title
# Discrete color bar legend
fig.subplots_adjust(bottom=0.1, top=1.1, left=0.1, right=0.9, wspace=0.2, hspace=-0.5)
cbar_ax = fig.add_axes([0.35, 0.2, 0.3, 0.02])
cbar = fig.colorbar(plot, cax=cbar_ax, orientation='horizontal', extend='max', shrink = 0.5) #Plots the legend color bar
cbar.ax.tick_params(labelsize=9) # Text size on legend color bar
cbar.set_label(label = 'Number of years', size = 9)
# Text outside the plot to display the scenario (top-center)
fig.text(0.5,0.935,'{}'.format(scenario_name), fontsize = 8, ha = 'center', va = 'center')
# Change this directory to save the plots to your desired directory
plt.savefig('C:/Users/dmuheki/OneDrive - Vrije Universiteit Brussel/Concurrent_climate_extremes_global/CR/Occurrence of Compound {} and {} under the {} scenario.pdf'.format(event_1_name, event_2_name, scenario_name), dpi = 300)
plt.show()
#plt.close()
return average_no_of_years_with_compound_events_per_scenario_and_gcm
#%% 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 compound events per location. FOR VISUALIZATION
def plot_probability_of_occurrence_of_compound_events_considering_all_gcms(average_probability_of_occurrence_of_the_compound_events_considering_all_gcms_and_impact_models, event_1_name, event_2_name, gcms):
""" Plot a map showing the average probability of compound events per location
Parameters
----------
average_probability_of_occurrence_of_the_compound_events_considering_all_gcms_and_impact_models : Xarray data array
event_1_name, event_2_name : String (Extreme Events)
gcms: List of gcms (Driving GCM)
time_period: String
scenarios: List of gcms
Returns
-------
Plot (Figure) showing the probability per location for which a compound extreme event was experienced
"""
#average_no_of_years_with_compound_events_per_scenario_and_gcm = [[],[],[],[],[]] # Where order of list is early industrial, present day, rcp 2.6, rcp6.0 and rcp 8.5
for scenario in range(len(average_probability_of_occurrence_of_the_compound_events_considering_all_gcms_and_impact_models)):
if scenario == 0:
scenario_name = 'Early-industrial'
if scenario == 1:
scenario_name = 'Present-Day'
if scenario == 2:
scenario_name = 'RCP2.6'
if scenario == 3:
scenario_name = 'RCP6.0'
if scenario == 4:
scenario_name = 'RCP8.5'
average_probability_of_occurrence_of_the_compound_events_per_gcm = average_probability_of_occurrence_of_the_compound_events_considering_all_gcms_and_impact_models[scenario]
# Setting the projection of the map to cylindrical / Mercator
fig, axs = plt.subplots(2,2, figsize=(10, 6.5), subplot_kw = {'projection': ccrs.PlateCarree()}) # , constrained_layout=True
# since axs is a 2 dimensional array of geozaxes, we have to flatten it into 1D; as explained on a similar example on this page: https://kpegion.github.io/Pangeo-at-AOES/examples/multi-panel-cartopy.html
axs=axs.flatten()
# Add the background map to the plot
#ax.stock_img()
if scenario == 4 and event_1_name == 'Crop Failures' or scenario == 4 and event_2_name == 'Crop Failures':
print('No data available for the crop failures for the selected GCM scenario under RCP8.5')
plt.close()
else:
for gcm in range(len(average_probability_of_occurrence_of_the_compound_events_per_gcm)):
# Plot per GCM in a subplot
plot = axs[gcm].imshow(average_probability_of_occurrence_of_the_compound_events_per_gcm[gcm], origin = 'upper' , extent= map_extent, cmap = plt.cm.get_cmap('viridis', 12), vmin = 0, vmax =0.6)
# Add the background map to the plot
#ax.stock_img()
# Set the extent of the plotn
axs[gcm].set_extent([-180, 180, 90, -60], crs=ccrs.PlateCarree())
# Plot the coastlines along the continents on the map
axs[gcm].coastlines(color='dimgrey', linewidth=0.7)
# Plot features: lakes, rivers and boarders
axs[gcm].add_feature(cfeature.LAKES, alpha =0.5)
axs[gcm].add_feature(cfeature.RIVERS)
axs[gcm].add_feature(cfeature.OCEAN)
axs[gcm].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
xticks = [-180, -120, -60, 0, 60, 120, 180] # Longitudes
axs[gcm].set_xticks(xticks, crs=ccrs.PlateCarree()) # 20E up to 50E
axs[gcm].set_xticklabels(xticks, fontsize = 8)
yticks = [90, 60, 30, 0, -30, -60]
axs[gcm].set_yticks(yticks, crs=ccrs.PlateCarree()) # 20N up to 10S
axs[gcm].set_yticklabels(yticks, fontsize = 8)
lon_formatter = LongitudeFormatter()
lat_formatter = LatitudeFormatter()
axs[gcm].xaxis.set_major_formatter(lon_formatter)
axs[gcm].yaxis.set_major_formatter(lat_formatter)
# Subplot labels
# label
subplot_labels = ['a.','b.','c.','d.']
axs[gcm].text(0, 1.06, subplot_labels[gcm], transform=axs[gcm].transAxes, fontsize=9, ha='left')
# GCM
gcm_name = gcms[gcm] # GCM
if gcm_name == 'gfdl-esm2m':
gcm_title = 'GFDL-ESM2M'
if gcm_name == 'hadgem2-es':
gcm_title = 'HadGEM2-ES'
if gcm_name == 'ipsl-cm5a-lr':
gcm_title = 'IPSL-CM5A-LR'
if gcm_name == 'miroc5':
gcm_title = 'MIROC5'
axs[gcm].set_title(gcm_title, fontsize = 9, loc = 'right')
# Add the title and legend to the figure and show the figure
fig.suptitle('Average Probability of Occurrence of Compound {} and {} \n'.format(event_1_name, event_2_name),fontsize=10) #Plot title
# Discrete color bar legend
fig.subplots_adjust(bottom=0.1, top=1.1, left=0.1, right=0.9, wspace=0.2, hspace=-0.5)
cbar_ax = fig.add_axes([0.35, 0.2, 0.3, 0.02])
cbar = fig.colorbar(plot, cax=cbar_ax, orientation='horizontal', extend='max', shrink = 0.5) #Plots the legend color bar
cbar.ax.tick_params(labelsize=9) # Text size on legend color bar
cbar.set_label(label = 'Probability of occurrence', size = 9)
# Text outside the plot to display the scenario (top-center)
fig.text(0.5,0.935,'{}'.format(scenario_name), fontsize = 8, ha = 'center', va = 'center')
# Change this directory to save the plots to your desired directory
plt.savefig('C:/Users/dmuheki/OneDrive - Vrije Universiteit Brussel/Concurrent_climate_extremes_global/CR/Probability of Occurrence of Compound {} and {} under the {} scenario.pdf'.format(event_1_name, event_2_name, scenario_name), dpi = 300)
plt.show()
#plt.close()
return average_probability_of_occurrence_of_the_compound_events_considering_all_gcms_and_impact_models
#%%
def plot_average_frequency_of_compound_events_considering_all_gcms_and_showing_all_compound_events(
average_frequency_of_all_compound_events,
compound_events_names,
selected_indices):
"""
Plot a map showing the average frequency of compound events for selected scenarios.
Parameters
----------
average_frequency_of_all_compound_events : List of Xarray data arrays
The average frequency of all possible combinations of extreme events considering
all the gcms and scenarios.
compound_events_names : List of Strings
Names of the compound events.
selected_indices : List of integers
Indices of the selected compound events to plot.
Returns
-------
Plot (Figure) showing the average frequency of compound events.
"""
# Mapping event names to acronyms
event_acronyms = {
'floodedarea': 'RF',
'driedarea': 'DR',
'heatwavedarea': 'HW',
'cropfailedarea': 'CF',
'burntarea': 'WF',
'tropicalcyclonedarea': 'TC'
}
list_of_compound_event_acronyms = []
for compound_event in compound_events_names:
event_1_name = event_acronyms.get(compound_event[0], compound_event[0])
event_2_name = event_acronyms.get(compound_event[1], compound_event[1])
compound_event_acronyms = '{} & {}'.format(event_1_name, event_2_name)
list_of_compound_event_acronyms.append(compound_event_acronyms)
selected_compound_events_names = [list_of_compound_event_acronyms[i] for i in selected_indices]
# Scenarios for the main figure:
scenarios_main = ['Present day', 'RCP6.0', 'Difference']
# Calculate the difference between Present day and RCP6.0
difference = calculate_difference(
average_frequency_of_all_compound_events[1],
average_frequency_of_all_compound_events[3]
)
main_scenarios_data = [
average_frequency_of_all_compound_events[1], # Present day
average_frequency_of_all_compound_events[3], # RCP6.0
difference # Difference
]
# Supplementary scenarios
scenarios_supplementary = ['Early-industrial', 'RCP2.6', 'RCP8.5']
supplementary_scenarios_data = [
average_frequency_of_all_compound_events[0], # Early-industrial
average_frequency_of_all_compound_events[2], # RCP2.6
average_frequency_of_all_compound_events[4] # RCP8.5
]
subplot_labels = 'abcdefghijklmnopqrstuvwxyz'
# Setting the projection of the map to cylindrical / Mercator
fig_main, axs_main = plt.subplots(len(selected_indices), 3, figsize=(10, 8), subplot_kw={'projection': ccrs.PlateCarree()})
# Flatten the 2D array of axes into 1D
axs_main = axs_main.flatten()
# Setting up the discrete color bar scheme
cmap = plt.cm.get_cmap('viridis', 12)
norm = mpl.colors.BoundaryNorm([0, 0.05, 0.10, 0.15, 0.20, 0.25, 0.3], cmap.N, extend='both')
# Diverging color map for the difference plot
cmap_diff = plt.cm.get_cmap('bwr')
norm_diff = mpl.colors.TwoSlopeNorm(vmin=-0.2, vcenter=0, vmax=0.2)
# Add maps to the main figure
for col in range(3):
for row in range(len(selected_indices)):
index = row * 3 + col
ax = axs_main[index]
ax.set_extent([-180, 180, 90, -60], crs=ccrs.PlateCarree())
ax.coastlines(color='dimgrey', linewidth=0.7)
ax.add_feature(cfeature.LAND, facecolor='lightgrey')
ax.spines['geo'].set_visible(False) # Remove border
if col == 2: # For the difference column
plot = ax.imshow(
main_scenarios_data[col][selected_indices[row]],
origin='lower',
extent=[-180, 180, 90, -60],
cmap=cmap_diff,
norm=norm_diff
)
else:
plot = ax.imshow(
main_scenarios_data[col][selected_indices[row]],
origin='lower',
extent=[-180, 180, 90, -60],
cmap=cmap,
norm=norm
)
if row == 0:
ax.set_title(scenarios_main[col], fontsize=10)
if col == 0:
ax.text(-0.2, 0.5, selected_compound_events_names[row], transform=ax.transAxes, fontsize=10, ha='center', va='center', rotation=90)
# Add subplot label
ax.text(0.02, 1.05, subplot_labels[index], transform=ax.transAxes, fontsize=9, va='top', ha='left')
fig_main.subplots_adjust(wspace=0.1, hspace=-0.5)
cbar_ax_main = fig_main.add_axes([0.3, 0.18, 0.2, 0.015])
cbar_main = fig_main.colorbar(mpl.cm.ScalarMappable(norm=norm, cmap=cmap), cax=cbar_ax_main, orientation='horizontal', extend='max')
cbar_main.ax.tick_params(labelsize=8)
cbar_main.set_label(label='Probability of joint occurrence', size=8)
# Color bar for the difference column
cbar_ax_diff = fig_main.add_axes([0.6, 0.18, 0.2, 0.015])
cbar_diff = fig_main.colorbar(mpl.cm.ScalarMappable(norm=norm_diff, cmap=cmap_diff), cax=cbar_ax_diff, orientation='horizontal', extend='both')
cbar_diff.ax.tick_params(labelsize=8)
cbar_diff.set_label(label='Difference in Probability of joint occurrence', size=8)
# Save and show the main plot
plt.savefig('C:/Users/dmuheki/OneDrive - Vrije Universiteit Brussel/Concurrent_climate_extremes_global/average_frequency_of_selected_compound_extremes_under_the_present_day_and_rcp60.pdf', dpi=300)
plt.show()
# Supplementary figure
fig_supp, axs_supp = plt.subplots(len(selected_indices), 3, figsize=(12, 10), subplot_kw={'projection': ccrs.PlateCarree()})
axs_supp = axs_supp.flatten()
# Add maps to the supplementary figure
for col in range(3):
for row in range(len(selected_indices)):
index = row * 3 + col
ax = axs_supp[index]
ax.set_extent([-180, 180, 90, -60], crs=ccrs.PlateCarree())
ax.coastlines(color='dimgrey', linewidth=0.7)
# Check if CF is in the event name and if it's the RCP8.5 column (last column)
if "CF" in selected_compound_events_names[row] and col == 2:
# Apply hatching for RCP8.5 scenario for CF
ax.add_feature(cfeature.LAND, facecolor='none', edgecolor='lightgrey', hatch='///')
else:
ax.add_feature(cfeature.LAND, facecolor='lightgrey')
ax.spines['geo'].set_visible(False) # Remove border
plot = ax.imshow(
supplementary_scenarios_data[col][selected_indices[row]],
origin='lower',
extent=[-180, 180, 90, -60],
cmap=cmap,
norm=norm
)
if row == 0:
ax.set_title(scenarios_supplementary[col], fontsize=10)
if col == 0:
ax.text(-0.2, 0.5, selected_compound_events_names[row], transform=ax.transAxes, fontsize=10, ha='center', va='center', rotation=90)
# Add subplot label
ax.text(0.02, 1.05, subplot_labels[index], transform=ax.transAxes, fontsize=9, va='top', ha='left')
fig_supp.subplots_adjust(wspace=0.1, hspace=-0.5)
cbar_ax_supp = fig_supp.add_axes([0.4, 0.18, 0.25, 0.015])
cbar_supp = fig_supp.colorbar(mpl.cm.ScalarMappable(norm=norm, cmap=cmap), cax=cbar_ax_supp, orientation='horizontal', extend='max')
cbar_supp.ax.tick_params(labelsize=9)
cbar_supp.set_label(label='Probability of joint occurrence', size=8)
# Save and show the supplementary plot
plt.savefig('C:/Users/dmuheki/OneDrive - Vrije Universiteit Brussel/Concurrent_climate_extremes_global/average_frequency_of_selected_compound_extremes_under_the_early_industrial_rcp26_and_rcp85_SUPPLEMENT.pdf', dpi=300)
plt.show()
return main_scenarios_data, supplementary_scenarios_data
#%% Function for plotting map showing the total number of years per location that experienced compound events. FOR VISUALIZATION
def plot_average_95th_quantile_of_length_of_spell_with_occurrence_of_compound_events_considering_all_gcms(average_95th_quantile_of_length_of_spell_with_occurrence_of_compound_event_per_scenario_and_gcm, event_1_name, event_2_name, gcms):
""" Plot a map showing the average 95th percentile of length of spells of compound events throught the data period per location
Parameters
----------
average_95th_quantile_of_length_of_spell_with_occurrence_of_compound_event_per_scenario_and_gcm : Xarray data array
event_1_name, event_2_name : String (Extreme Events)
gcms: List of gcms (Driving GCM)
time_period: String
scenarios: List of gcms
Returns
-------
Plot (Figure) showing the 95th percentile of length of spells of compound events throught the data period per location
"""
#average_95th_quantile_of_length_of_spell_with_occurrence_of_compound_event_per_scenario_and_gcm = [[],[],[],[],[]] # Where order of list is early industrial, present day, rcp 2.6, rcp6.0 and rcp 8.5
for scenario in range(len(average_95th_quantile_of_length_of_spell_with_occurrence_of_compound_event_per_scenario_and_gcm)):
if scenario == 0:
scenario_name = 'Early-industrial'
if scenario == 1:
scenario_name = 'Present-Day'
if scenario == 2:
scenario_name = 'RCP2.6'
if scenario == 3:
scenario_name = 'RCP6.0'
if scenario == 4:
scenario_name = 'RCP8.5'
average_95th_quantile_of_length_of_spell_with_occurrence_of_compound_event_per_gcm = average_95th_quantile_of_length_of_spell_with_occurrence_of_compound_event_per_scenario_and_gcm[scenario]
# Setting the projection of the map to cylindrical / Mercator
fig, axs = plt.subplots(2,2, figsize=(10, 6.5), subplot_kw = {'projection': ccrs.PlateCarree()}) # , constrained_layout=True
# since axs is a 2 dimensional array of geozaxes, we have to flatten it into 1D; as explained on a similar example on this page: https://kpegion.github.io/Pangeo-at-AOES/examples/multi-panel-cartopy.html
axs=axs.flatten()
# Add the background map to the plot
#ax.stock_img()
if scenario == 4 and event_1_name == 'Crop Failures' or scenario == 4 and event_2_name == 'Crop Failures':
print('No data available for the crop failures for the selected GCM scenario under RCP8.5')
plt.close()
else:
for gcm in range(len(average_95th_quantile_of_length_of_spell_with_occurrence_of_compound_event_per_gcm)):
# Plot per GCM in a subplot
plot = axs[gcm].imshow(average_95th_quantile_of_length_of_spell_with_occurrence_of_compound_event_per_gcm[gcm], origin = 'upper' , extent= map_extent, cmap = plt.cm.get_cmap('YlOrRd'), vmin = 1, vmax =30)
# Add the background map to the plot
#ax.stock_img()
# Set the extent of the plotn
axs[gcm].set_extent([-180, 180, 90, -60], crs=ccrs.PlateCarree())
# Plot the coastlines along the continents on the map
axs[gcm].coastlines(color='dimgrey', linewidth=0.7)
# Plot features: lakes, rivers and boarders
axs[gcm].add_feature(cfeature.LAKES, alpha =0.5)