-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathbias_correction_masked.py
2001 lines (1587 loc) · 109 KB
/
bias_correction_masked.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import os
os.chdir('C:/Users/morenodu/OneDrive - Stichting Deltares/Documents/PhD/Paper_drought/data')
import xarray as xr
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import geopandas as gpd
import cartopy.crs as ccrs
import cartopy.io.shapereader as shpreader
import seaborn as sns
def bias_correction_masked(mask, start_date, end_date, cru_detrend = False, df_features_ec_3C_season = False, save_figs = False):
"""
This function takes as input the EC_earth model projections for PD, 2C and 3C
and the mask for a region (US, Brazil, etc.) and corrects the bias to match
CRU cru_ts4.04 for the climatology 1990-2020.
Parameters:
Mask: regions to which the data should be cropped to. Should have a value where
values > 0 can be mapped. EX: Dataset with yields, where climate cells are selected
only for grids with positive (real) yields.
Detrend: Whether or not to consider detrending the CRU dataset used to
correct the bias for the EC earth model.
Important: needs to match EC_earth resolution, which means it needs to be rescaled. Follows:
$ cdo -remapycon,tasmax_m_ECEarth_PD_ensemble_2035-4035.nc YOUR_FILE.nc YOUR_FILE_LOWRES.nc
Returns:
DS_cli_ec, DS_cli_ec_2C: The EC_earth projections biased corrected and masked.
Created on Wed Feb 10 17:19:09 2021
by @HenriqueGoulart
"""
#%% Openinig and cleaning data
# Function
def states_mask(input_gdp_shp, state_names) :
country = gpd.read_file(input_gdp_shp, crs="epsg:4326")
country_shapes = list(shpreader.Reader(input_gdp_shp).geometries())
soy_states = country[country['NAME_1'].isin(state_names)]
states_area = soy_states['geometry'].to_crs({'proj':'cea'})
states_area_sum = (sum(states_area.area / 10**6))
return soy_states, country_shapes, states_area_sum
state_names = ['Iowa','Illinois','Minnesota','Indiana','Nebraska','Ohio',
'South Dakota','North Dakota', 'Missouri','Arkansas']
soy_us_states, us1_shapes, us_states_area_sum = states_mask('gadm36_USA_1.shp', state_names)
state_names = ['Rio Grande do Sul','Paraná']
soy_br_states, br1_shapes, brs_states_area_sum = states_mask('gadm36_BRA_1.shp', state_names)
state_names = ['Buenos Aires','Santa Fe', 'Córdoba']
soy_ar_states, ar1_shapes, ar_states_area_sum = states_mask('gadm36_ARG_1.shp', state_names)
state_names = ['Mato Grosso','Goiás']
soy_brc_states, br1_shapes, brc_states_area_sum = states_mask('gadm36_BRA_1.shp', state_names)
# Needs to import DS_Yield from other script
if isinstance(mask, xr.core.dataset.Dataset) == True:
mask_ref = mask[list(mask.keys())[0]].mean('time')
elif isinstance(mask, xr.core.dataarray.DataArray) == True:
mask_ref = mask.mean('time')
else:
raise ValueError('Mask should be either Dataset or Dataarray')
# CRU data
DS_t_max_cru = xr.open_dataset("EC_earth_PD/cru_ts4.04.1901.2019.tmx.dat_lr.nc",
decode_times=True).sel(time=slice(start_date, end_date))
DS_t_max_cru_us = DS_t_max_cru.where(mask_ref > -0.1 ) # mask
DS_dtr_cru = xr.open_dataset("EC_earth_PD/cru_ts4.04.1901.2019.dtr.dat_lr.nc",
decode_times=True).sel(time=slice(start_date, end_date))
DS_dtr_cru_us = DS_dtr_cru.where(mask_ref > -0.1 )
DS_pre_cru = xr.open_dataset("EC_earth_PD/cru_ts4.04.1901.2019.pre.dat_lr.nc",
decode_times=True).sel(time=slice(start_date, end_date))
DS_pre_cru_us = DS_pre_cru.where(mask_ref > -0.1 )
# Detrending data
def detrend_dim(da, dim, deg=1):
# detrend along a single dimension
p = da.polyfit(dim=dim, deg=deg)
fit = xr.polyval(da[dim], p.polyfit_coefficients)
return da - fit
def detrend(da, dims, deg=1):
# detrend along multiple dimensions
# only valid for linear detrending (deg=1)
da_detrended = da
for dim in dims:
da_detrended = detrend_dim(da_detrended, dim, deg=deg)
return da_detrended
# Create Bias correction dataset: Detrend time series for higher range and add mean for 1990-2020.
if cru_detrend == True:
start_date_mean, end_date_mean = start_date, end_date
DS_tmx_cru_us_det = xr.DataArray( detrend_dim(DS_t_max_cru_us.tmx, 'time') + DS_t_max_cru_us.tmx.sel(
time=slice(start_date_mean, end_date_mean)).mean('time'), name= DS_t_max_cru_us.tmx.name, attrs = DS_t_max_cru_us.tmx.attrs )
DS_dtr_cru_us_det = xr.DataArray( detrend_dim(DS_dtr_cru_us.dtr, 'time') + DS_dtr_cru_us.dtr.sel(
time=slice(start_date_mean, end_date_mean)).mean('time'), name= DS_dtr_cru_us.dtr.name, attrs = DS_dtr_cru_us.dtr.attrs)
DS_pre_cru_us_det = xr.DataArray( detrend_dim(DS_pre_cru_us.pre, 'time') + DS_pre_cru_us.pre.sel(
time=slice(start_date_mean, end_date_mean)).mean('time'), name= DS_pre_cru_us.pre.name, attrs = DS_pre_cru_us.pre.attrs)
if cru_detrend == False: #No detrending
DS_tmx_cru_us_det = DS_t_max_cru_us.tmx
DS_dtr_cru_us_det = DS_dtr_cru_us.dtr
DS_pre_cru_us_det = DS_pre_cru_us.pre
# Merge everything
DS_cru_merge = xr.merge([DS_tmx_cru_us_det, DS_dtr_cru_us_det, DS_pre_cru_us_det])
# Benchmark of undetrended variables
DS_cru_prov = xr.merge([DS_t_max_cru_us.tmx, DS_dtr_cru_us.dtr, DS_pre_cru_us.pre])
# Test detrending - comparison of time series
for feature in list(DS_cru_merge.keys()):
df_feature = DS_cru_prov[feature].to_dataframe().groupby(['time']).mean() # pandas because not spatially variable anymore
df_feature_8 = df_feature.loc[df_feature.index.month == 8]
df_feature_det = DS_cru_merge[feature].to_dataframe().groupby(['time']).mean() # pandas because not spatially variable anymore
df_feature_det_8 = df_feature_det.loc[df_feature_det.index.month == 8]
plt.plot(df_feature_8, label = f'{feature} normal 8')
plt.plot(df_feature_det_8, label = f"{feature} det 8")
plt.legend()
plt.show()
# KDEPLOT to compare pdfs
df_feature_8['Scenario'] = 'Not detrended'
df_feature_det_8['Scenario'] = 'Detrended'
df_hist_us = pd.concat( [df_feature_8, df_feature_det_8],axis=0)
plt.figure(figsize = (6,6), dpi=144)
fig = sns.kdeplot( data = df_hist_us, x= df_hist_us[feature], hue="Scenario", fill=True, alpha=.2)
plt.show()
# EC-Earth
def open_regularize(address_file, reference_file):
DS_ec = xr.open_dataset(address_file,decode_times=True)
if list(DS_ec.keys())[1] == 'tasmax':
da_ec = DS_ec[list(DS_ec.keys())[1]] - 273.15
elif list(DS_ec.keys())[1] == 'pr':
da_ec = DS_ec[list(DS_ec.keys())[1]] * 1000
else:
da_ec = DS_ec[list(DS_ec.keys())[1]]
DS_ec = da_ec.to_dataset()
DS_ec_crop = DS_ec.where(reference_file.mean('time') > -300 )
return DS_ec_crop
#Temp - Kelvin to celisus
DS_tmx_ec = open_regularize("EC_earth_PD/tasmax_m_ECEarth_PD_ensemble_2035-4035.nc", DS_pre_cru_us['pre'])
# precipitation
DS_pre_ec = open_regularize("EC_earth_PD/pr_m_ECEarth_PD_ensemble_2035-4035.nc", DS_pre_cru_us['pre'])
# dtr
DS_dtr_ec = open_regularize("EC_earth_PD/dtr_m_ECEarth_PD_ensemble_2035-4035.nc", DS_pre_cru_us['pre'])
# Test plot to see if it's good
plt.figure(figsize=(20,10)) #plot clusters
ax=plt.axes(projection=ccrs.Mercator())
DS_tmx_ec['tasmax'].mean('time').plot(x='lon', y='lat',transform=ccrs.PlateCarree(), robust=True)
ax.add_geometries(us1_shapes, ccrs.PlateCarree(),edgecolor='black', facecolor=(0,1,0,0.0))
ax.set_extent([-105,-25,-50,50], ccrs.PlateCarree())
ax.set_title('Spatial variability of bias between CRU and EC-earth')
plt.show()
# Test plot to see if it's good
plt.figure(figsize=(20,10)) #plot clusters
ax=plt.axes(projection=ccrs.Mercator())
DS_dtr_cru_us['dtr'].mean('time').plot(x='lon', y='lat',transform=ccrs.PlateCarree(), robust=True)
ax.add_geometries(us1_shapes, ccrs.PlateCarree(),edgecolor='black', facecolor=(0,1,0,0.0))
ax.set_extent([-105,-25,-50,50], ccrs.PlateCarree())
ax.set_title('Spatial variability of bias between CRU and EC-earth')
plt.show()
# Measure diference between model and observed data
subt = DS_tmx_ec['tasmax'].mean('time') - DS_t_max_cru_us['tmx'].mean('time')
plt.figure(figsize=(20,10)) #plot clusters
ax=plt.axes(projection=ccrs.Mercator())
subt.plot(x='lon', y='lat',transform=ccrs.PlateCarree(), robust=True)
ax.add_geometries(us1_shapes, ccrs.PlateCarree(),edgecolor='black', facecolor=(0,1,0,0.0))
ax.set_extent([-105,-25,-50,50], ccrs.PlateCarree())
ax.set_title('Spatial variability of bias between CRU and EC-earth')
plt.show()
#%% BIAS CORRECTION - Convert and tests
from xclim import sdba
import scipy.stats as stats
def bias_analysis(obs_data, model_data, level = 'PD', cor = 'False'):
"""
Bias analysis graphs by entering the observed data and the model to be corrected.
Parameters:
obs_data: data to serve as training reference, the observed dataset;
model_data: the data that is required to be adjusted, usually the model data.
No return, just graphs showing bias
"""
df_cru_cli=obs_data.to_dataframe().groupby(['time']).mean() # pandas because not spatially variable anymore
df_ec=model_data[list(model_data.keys())[0]].to_dataframe().groupby(['time']).mean() # pandas because not spatially variable anymore
if cor == 'False':
mode = 'not_cor'
elif cor == 'True':
mode = 'correct'
if obs_data.name == 'tmx':
feature_name = 'temperature'
elif obs_data.name == 'dtr':
feature_name = 'DTR'
elif obs_data.name == 'pre':
feature_name = 'precipitation'
# Compare mean annual cycle
df_cru_year = df_cru_cli.groupby(df_cru_cli.index.month).mean()
df_ec_year = df_ec.groupby(df_ec.index.month).mean()
# plot
plt.figure(figsize = (5,5), dpi=200)
plt.plot(df_cru_year, label = 'CRU', color = 'darkblue')
plt.plot(df_ec_year, label = 'EC-Earth', color = 'red' )
plt.ylabel(obs_data.attrs['units'])
plt.title(f'Mean annual cycle - {feature_name} {level}')
plt.legend(loc="lower left")
if save_figs == True:
plt.savefig(f'paper_figures/bias_adj_mean_{mode}_{obs_data.name}_{level}.png', format='png', dpi=500)
plt.show()
# Compare std each year
df_cru_year_std = df_cru_cli.groupby(df_cru_cli.index.month).std()
df_ec_year_std = df_ec.groupby(df_ec.index.month).std()
# plot
plt.figure(figsize = (5,5), dpi=200)
plt.plot(df_cru_year_std, label = 'CRU', color = 'darkblue')
plt.plot(df_ec_year_std, label = 'EC-Earth', color = 'red' )
plt.ylabel(obs_data.attrs['units'])
plt.title(f'Variability around the mean - {feature_name} {level}')
plt.legend(loc="lower left")
if save_figs == True:
plt.savefig(f'paper_figures/bias_adj_std_{mode}_{obs_data.name}_{level}.png', format='png', dpi=500)
plt.show()
stats.probplot(df_cru_cli.iloc[:,0], dist=stats.beta, sparams=(3,2), plot=plt,fit=False)
# Compare Q-Q plot
fig, ax = plt.subplots(1, 1, figsize=(5, 5), dpi=200)
stats.probplot(df_ec.iloc[:,0], dist=stats.beta, sparams=(3,2),plot=plt,fit=False)
ax.get_lines()[0].set_color('C1')
# plt.legend(loc="lower left")
plt.show()
def bias_figure(model_data, model_data_cor, obs_data, scenario = 'PD'):
if obs_data.name == 'tmx':
feature_name = 'temperature'
elif obs_data.name == 'dtr':
feature_name = 'DTR'
elif obs_data.name == 'pre':
feature_name = 'precipitation'
df_ec = model_data[list(model_data.keys())[0]].to_dataframe().groupby(['time']).mean() # pandas because not spatially variable anymore
df_ec_cor = model_data_cor[list(model_data_cor.keys())[0]].to_dataframe().groupby(['time']).mean() # pandas because not spatially variable anymore
df_ec_year = df_ec.groupby(df_ec.index.month).mean()
df_ec_cor_year = df_ec_cor.groupby(df_ec_cor.index.month).mean()
if scenario == 'PD':
df_cru_cli = obs_data.to_dataframe().groupby(['time']).mean() # pandas because not spatially variable anymore
df_cru_year = df_cru_cli.groupby(df_cru_cli.index.month).mean()
# plot
plt.figure(figsize = (5,5), dpi=200)
plt.plot(df_cru_year, label = 'CRU', color = 'black')
plt.plot(df_ec_year, label = 'EC-Earth original', color = 'darkblue' )
plt.plot(df_ec_cor_year, label = 'EC-Earth corrected', color = 'red', linestyle = '--' )
plt.ylabel(obs_data.attrs['units'])
plt.title(f'Mean annual cycle - {feature_name} bias correction')
plt.legend(loc="lower left")
if save_figs == True:
plt.savefig(f'paper_figures/bias_adj_mean_{obs_data.name}_all.png', format='png', dpi=500)
plt.show()
if scenario == '2C':
color_plot = 'orange'
elif scenario == '3C':
color_plot = 'green'
if scenario == '2C' or scenario == '3C':
# plot
plt.figure(figsize = (5,5), dpi=200)
plt.plot(df_ec_year, label = f'EC-Earth {scenario}', color = color_plot )
plt.plot(df_ec_cor_year, label = 'EC-Earth PD', color = 'red', linestyle = '--' )
plt.ylabel(obs_data.attrs['units'])
plt.title(f'Mean annual cycle - {feature_name} for {scenario}')
plt.legend(loc="lower left")
if save_figs == True:
plt.savefig(f'paper_figures/bias_adj_mean_{obs_data.name}_{scenario}_adjusted.png', format='png', dpi=500)
plt.show()
# bias correction for tasmax Quantile mapping - First compare the original, then adjust the bias and compare the bias corrected version
bias_analysis( DS_cru_merge.tmx, DS_tmx_ec, level = 'PD', cor = 'False')
dqm_tmx = sdba.adjustment.DetrendedQuantileMapping(nquantiles=25, group='time.month', kind='+')
dqm_tmx.train(DS_cru_merge['tmx'],DS_tmx_ec['tasmax'])
DS_tmx_ec_cor = dqm_tmx.adjust(DS_tmx_ec['tasmax'], interp='linear')
DS_tmx_ec_cor = DS_tmx_ec_cor.to_dataset(name= 'tmx')
bias_analysis(DS_cru_merge.tmx, DS_tmx_ec_cor, level = 'PD', cor = 'True')
bias_figure(DS_tmx_ec, DS_tmx_ec_cor, DS_cru_merge.tmx, scenario = 'PD')
# bias correction for dtr Quantile mapping - First compare the original, then adjust the bias and compare the bias corrected version
bias_analysis(DS_cru_merge.dtr, DS_dtr_ec, level = 'PD', cor = 'False')
dqm_dtr = sdba.adjustment.DetrendedQuantileMapping(nquantiles=25, group='time.month', kind='+')
dqm_dtr.train(DS_cru_merge['dtr'],DS_dtr_ec['dtr'])
DS_dtr_ec_cor = dqm_dtr.adjust(DS_dtr_ec['dtr'], interp='linear')
DS_dtr_ec_cor = DS_dtr_ec_cor.to_dataset(name= 'dtr')
bias_analysis(DS_cru_merge.dtr, DS_dtr_ec_cor, level = 'PD', cor = 'True')
bias_figure(DS_dtr_ec, DS_dtr_ec_cor, DS_cru_merge.dtr, scenario = 'PD')
# bias correction for precipitation Quantile mapping - First compare the original, then adjust the bias and compare the bias corrected version
bias_analysis(DS_cru_merge.pre, DS_pre_ec, level = 'PD', cor = 'False')
dqm_pr = sdba.adjustment.DetrendedQuantileMapping(nquantiles=25, group='time.month', kind='+')
dqm_pr.train(DS_cru_merge['pre'],DS_pre_ec['pr'])
DS_pre_ec_cor = dqm_pr.adjust(DS_pre_ec['pr'], interp='linear')
DS_pre_ec_cor = DS_pre_ec_cor.to_dataset(name= 'pre')
bias_analysis(DS_cru_merge.pre, DS_pre_ec_cor, level = 'PD', cor = 'True')
bias_figure(DS_pre_ec, DS_pre_ec_cor, DS_cru_merge.pre, scenario = 'PD')
# Merge in one dataset
DS_cli_ec = xr.merge([DS_tmx_ec_cor.tmx, DS_dtr_ec_cor.dtr, DS_pre_ec_cor.pre])
letter = 'a)'
for feature in list(DS_cli_ec.keys()):
if feature == 'tmx':
feature_name = 'temperature'
letter = 'a)'
sel_kwargs={'label': '°C'}
elif feature == 'dtr':
feature_name = 'DTR'
letter = 'b)'
sel_kwargs={'label': '°C'}
elif feature == 'pre':
feature_name = 'precipitation'
letter = 'c)'
sel_kwargs={'label': 'mm/month'}
subt_cor = DS_cli_ec[feature].mean('time') - DS_cru_merge[feature].mean('time')
plt.figure(figsize=(10,5)) #plot clusters
ax=plt.axes(projection=ccrs.Mercator())
subt_cor.plot(x='lon', y='lat',transform=ccrs.PlateCarree(), robust=True,levels=10, cbar_kwargs = sel_kwargs)
ax.add_geometries(us1_shapes, ccrs.PlateCarree(),edgecolor='black', facecolor=(0,1,0,0.0))
ax.set_extent([-105,-65,20,50], ccrs.PlateCarree())
ax.set_title(f'{letter} Corrected bias for {feature_name}')
plt.tight_layout()
plt.show()
#%% 2C simulation - future data
#Temp - Kelvin to celisus
DS_tmx_ec_2C = open_regularize("EC_earth_2C/tasmax_m_ECEarth_2C_ensemble_2062-4062.nc", DS_pre_cru_us['pre'])
# precipitation
DS_pre_ec_2C = open_regularize("EC_earth_2C/pr_m_ECEarth_2C_ensemble_2062-4062.nc", DS_pre_cru_us['pre'])
# dtr
DS_dtr_ec_2C = open_regularize("EC_earth_2C/dtr_m_ECEarth_2C_ensemble_2062-4062.nc", DS_pre_cru_us['pre'])
def bias_correction(DS_cru_merge, DS_ec, detrend_model, var_name, level = 'PD'):
bias_analysis(DS_cru_merge, DS_ec, level = level, cor = 'False')
DS_ec_cor = detrend_model.adjust(DS_ec[list(DS_ec.keys())[0]], interp='linear')
DS_ec_cor = DS_ec_cor.to_dataset(name= var_name)
bias_analysis(DS_cru_merge, DS_ec_cor, level = level, cor = 'True')
return DS_ec_cor
# Correct bias
DS_tmx_ec_2C_cor = bias_correction(DS_cru_merge.tmx, DS_tmx_ec_2C, dqm_tmx, 'tmx', level = '2C')
DS_dtr_ec_2C_cor = bias_correction(DS_cru_merge.dtr, DS_dtr_ec_2C, dqm_dtr, 'dtr', level = '2C')
DS_pre_ec_2C_cor = bias_correction(DS_cru_merge.pre, DS_pre_ec_2C, dqm_pr, 'pre', level = '2C')
# Plot figures to compare PD to 2C
bias_figure(DS_tmx_ec_2C_cor, DS_tmx_ec_cor, DS_cru_merge.tmx, scenario = '2C')
bias_figure(DS_dtr_ec_2C_cor, DS_dtr_ec_cor, DS_cru_merge.dtr, scenario = '2C')
bias_figure(DS_pre_ec_2C_cor, DS_pre_ec_cor, DS_cru_merge.pre, scenario = '2C')
# Merge in one dataset
DS_cli_ec_2C = xr.merge([DS_tmx_ec_2C_cor.tmx, DS_dtr_ec_2C_cor.dtr, DS_pre_ec_2C_cor.pre])
if df_features_ec_3C_season is False:
print('3C NOT included')
return(DS_cli_ec, DS_cli_ec_2C)
#%% 3C simulation - future data
elif df_features_ec_3C_season is True:
print('3C included')
DS_ec_2c_ref = xr.open_dataset("EC_earth_2C/dtr_m_ECEarth_2C_s01r00_2062.nc",decode_times=True)
def open_regularize_3c(address_file, reference_file):
# Correct latitude error at ECMWF, latitude is float32 but we need float64
DS_ec = xr.open_dataset(address_file,decode_times=True)
DS_ec['lat'] = DS_ec_2c_ref.lat
if list(DS_ec.keys())[1] == 'tasmax':
da_ec = DS_ec[list(DS_ec.keys())[1]] - 273.15
elif list(DS_ec.keys())[1] == 'pr':
da_ec = DS_ec[list(DS_ec.keys())[1]] * 1000
print('pr selected')
elif list(DS_ec.keys())[1] == 'dtr':
da_ec = DS_ec[list(DS_ec.keys())[1]]
else:
raise Exception('Should be either tasmax, pr or dtr')
DS_ec = da_ec.to_dataset()
DS_ec_crop = DS_ec.where(reference_file.mean('time') > -300 )
return DS_ec_crop
#Temp - Kelvin to celisus
DS_tmx_ec_3C = open_regularize_3c("EC_earth_3C/tasmax_d_ECEarth_3C_ensemble_2082-4082.nc", DS_pre_cru_us['pre'])
# precipitation
DS_pre_ec_3C = open_regularize_3c("EC_earth_3C/pr_m_ECEarth_3C_ensemble_2082-4082.nc", DS_pre_cru_us['pre'])
# dtr
DS_dtr_ec_3C = open_regularize_3c("EC_earth_3C/dtr_d_ECEarth_3C_ensemble_2082-4082.nc", DS_pre_cru_us['pre'])
# Correct bias
DS_tmx_ec_3C_cor = bias_correction(DS_cru_merge.tmx, DS_tmx_ec_3C, dqm_tmx, 'tmx', level = '3C')
DS_dtr_ec_3C_cor = bias_correction(DS_cru_merge.dtr, DS_dtr_ec_3C, dqm_dtr, 'dtr', level = '3C')
DS_pre_ec_3C_cor = bias_correction(DS_cru_merge.pre, DS_pre_ec_3C, dqm_pr, 'pre', level = '3C')
# Plot figures to compare PD to 3C
bias_figure(DS_tmx_ec_3C_cor, DS_tmx_ec_cor, DS_cru_merge.tmx, scenario = '3C')
bias_figure(DS_dtr_ec_3C_cor, DS_dtr_ec_cor, DS_cru_merge.dtr, scenario = '3C')
bias_figure(DS_pre_ec_3C_cor, DS_pre_ec_cor, DS_cru_merge.pre, scenario = '3C')
# Merge in one dataset
DS_cli_ec_3C = xr.merge([DS_tmx_ec_3C_cor.tmx, DS_dtr_ec_3C_cor.dtr, DS_pre_ec_3C_cor.pre])
return(DS_cli_ec, DS_cli_ec_2C, DS_cli_ec_3C)
#%% Function conversion
def function_conversion(DS_cli_ec_PD, DS_cli_ec_2C, DS_cli_ec_3C = None, months_to_be_used=[7,8], water_year = False):
"""
This function takes as input the bias corrected EC_earth model projections,
the months to be selected for the season (months_to_be_used = [7,8]),
Parameters:
DS_cli_ec_PD, DS_cli_ec_2C, DS_cli_ec_3C: The datasets for present day climate and for the 2C (optional 3C);
months_to_be_used: which months to use when converting to dataframe;
water_year: if calculations need to be carried out for interannual periods.
Returns:
The formatted dataframes representing EC_earth projections for PD,2C,3C
Created on Wed Feb 10 17:19:09 2021
by @HenriqueGoulart
"""
# Features considered for this case
column_names = [i+str(j) for i in list(DS_cli_ec_PD.keys()) for j in months_to_be_used]
DS_cru = xr.open_dataset("EC_earth_PD/cru_ts4.04.1901.2019.tmx.dat_lr.nc",
decode_times=True).sel(time=slice('31-12-1989', '31-12-2020'))
#convert to dataframe, reshape so every month is in a separate colum:
def reshape_data(dataarray): #converts and reshape data
if isinstance(dataarray, pd.DataFrame):
dataframe = dataarray.dropna(how='all')
dataframe['month'] = dataframe.index.get_level_values('time').month
dataframe['year'] = (np.repeat(range(0,2000), 12))
dataframe.set_index('month', append=True, inplace=True)
dataframe.set_index('year', append=True, inplace=True)
dataframe = dataframe.reorder_levels(['time', 'year','month'])
dataframe.index = dataframe.index.droplevel('time')
dataframe = dataframe.unstack('month')
dataframe.columns = dataframe.columns.droplevel()
else:
dataframe = dataarray.to_dataframe().dropna(how='all')
dataframe['month'] = dataframe.index.get_level_values('time').month
dataframe['year'] = (np.repeat(range(0,2000), 12))
dataframe.set_index('month', append=True, inplace=True)
dataframe.set_index('year', append=True, inplace=True)
dataframe = dataframe.reorder_levels(['time', 'year','month', 'lat', 'lon'])
dataframe.index = dataframe.index.droplevel('time')
dataframe = dataframe.unstack('month')
dataframe.columns = dataframe.columns.droplevel()
return dataframe
# Function to transform the dataset into dataframe for each selected month
def dataset_to_dataframe(DS_cli_ec):
df_features_ec = []
for feature in list(DS_cli_ec.keys()):
df_feature_2 = DS_cli_ec[feature].to_dataframe().groupby(['time']).mean()
# arrange time so water year stays a single year (12,1,2,3...) if not, skip
if (water_year == True):
df_feature_2.index = np.tile(DS_cru.time.sel(time=slice('31-12-2010', '31-12-2015')), 400)
df_feature_2.index.name = 'time'
df_feature_2['year'] = df_feature_2.index.year.where(df_feature_2.index.month < 10,
df_feature_2.index.year + 1)
df_feature_2['month'] = pd.DatetimeIndex(df_feature_2.index).month
df_feature_2['day'] = pd.DatetimeIndex(df_feature_2.index).day
df_feature_2['time'] = pd.to_datetime(df_feature_2.iloc[:,1:4])
df_feature_2.index = df_feature_2['time']
df_feature_2.drop(['month','day','time','year'], axis=1, inplace = True)
df_feature_2_reshape = reshape_data(df_feature_2).loc[:,months_to_be_used]
df_features_ec.append(df_feature_2_reshape)
df_features_ec = pd.concat(df_features_ec, axis=1) # format data
df_features_ec.columns = column_names
# Adapt the structure to match the RF structure
if len(df_features_ec.columns) == 6:
df_features_ec_season_local = pd.concat( [df_features_ec.iloc[:,0:2].mean(axis=1),
df_features_ec.iloc[:,2:4].mean(axis=1),
df_features_ec.iloc[:,4:6].mean(axis=1)], axis=1 )
df_features_ec_season_local.columns=[f'tmx_{months_to_be_used[0]}_{months_to_be_used[1]}',
f'dtr_{months_to_be_used[0]}_{months_to_be_used[1]}',
f'precip_{months_to_be_used[0]}_{months_to_be_used[1]}']
return df_features_ec,df_features_ec_season_local
elif len(df_features_ec.columns) == 9:
df_features_ec_season_local = pd.concat( [df_features_ec.iloc[:,0:3].mean(axis=1),
df_features_ec.iloc[:,3:6].mean(axis=1),
df_features_ec.iloc[:,6:9].mean(axis=1)], axis=1 )
df_features_ec_season_local.columns=[f'tmx_{months_to_be_used[0]}_{months_to_be_used[1]}_{months_to_be_used[2]}',
f'dtr_{months_to_be_used[0]}_{months_to_be_used[1]}_{months_to_be_used[2]}',
f'precip_{months_to_be_used[0]}_{months_to_be_used[1]}_{months_to_be_used[2]}']
return df_features_ec,df_features_ec_season_local
# PRESENT DAY
df_features_ec,df_features_ec_season = dataset_to_dataframe(DS_cli_ec_PD)
print("PD done!")
# FUTURE 2C
df_features_ec_2C,df_features_ec_season_2C = dataset_to_dataframe(DS_cli_ec_2C)
print("2C done!")
# FUTURE 3C
if DS_cli_ec_3C is None:
return df_features_ec_season,df_features_ec_season_2C
elif DS_cli_ec_3C is not None:
df_features_ec_3C,df_features_ec_season_3C = dataset_to_dataframe(DS_cli_ec_3C)
return df_features_ec_season, df_features_ec_season_2C, df_features_ec_season_3C
# second way - check if they match
#%% Scenario exploration
def predictions_permutation(brf_model, df_clim_agg_chosen, df_features_ec_season,
df_features_ec_2C_season = None, df_features_ec_3C_season = None, df_clim_2012 = None):
"""
This function takes as input the bias corrected EC_earth model projections,
the months to be selected for the season (months_to_be_used = [7,8]),
Parameters:
brf_model: the machine learning model trained for the area;
df_features_ec_season: dataframe containing the climatic features as input
(processed by previous function)
df_features_ec_season_2C = dataframe containing cl. features for future period
Returns:
Series of plots and prints showing the predictions of the ML for different
time periods.
score_prc: the ratio (score) indicating the amount of seasons with failure
per total seasons.
Created on Wed Feb 10 17:19:09 2021
by @HenriqueGoulart
"""
# Storyline probability of failure 2012
y_pred_2012 = brf_model.predict_proba(df_clim_2012.values.reshape(1, -1))[0][1]
print("2012 prediction is: ",y_pred_2012)
# Predictions for Observed data PD
def predictions(brf_model,df_features_ec_season):
y_pred = brf_model.predict(df_features_ec_season)
score_prc = sum(y_pred)/len(y_pred)
print("\n The total failures are:", sum(y_pred),
" And the ratio of failure seasons by total seasons is:", score_prc, "\n")
probs = brf_model.predict_proba(df_features_ec_season)
if df_clim_2012 is not None:
seasons_over_2012 = df_features_ec_season[probs[:,1]>=y_pred_2012]
print(f"\n Number of >= {y_pred_2012} probability failure events: {len(seasons_over_2012)} and mean conditions are:",
np.mean(seasons_over_2012))
return y_pred, score_prc, probs, seasons_over_2012
def return_period(df, colname):
# Sort data smallest to largest
sorted_data = df.sort_values(by=colname)
# Count total obervations
n = sorted_data.shape[0]
# Add a numbered column 1 -> n to use in return calculation for rank
sorted_data.insert(0, 'rank', range(1, 1 + n))
# Calculate probability
sorted_data["probability"] = (n - sorted_data["rank"] + 1) / (n + 1)
# Calculate return - yearly data, no need to further trnasform
sorted_data["return-years"] = (1 / sorted_data["probability"])
return(sorted_data)
def plot_probs_failure(probs, probs_perm):
# put them together in the same dataframe for plotting
probs_agg=pd.DataFrame( [probs[:,1],probs_perm[:,1]]).T
probs_agg.columns=['Ordered','Permuted']
# plots comparing prediction confidence for obs and perumuted
probs_agg_melt = probs_agg.melt(value_name='Failure probability').assign(data='Density')
sns.displot(probs_agg_melt, x="Failure probability", hue="variable", kde=False)
plt.show()
# Compare the number of cases above a failure threshold
fails_prob_together = np.empty([len(thresholds),2])
i=0
for prc in thresholds:
# print(f'The number of observed seasons with failure probability over {prc}% is:',
# len(probs[:,1][probs[:,1]>prc/100]), 'and permuted is: ',
# len(probs_perm[:,1][probs_perm[:,1]>prc/100]))
fails_prob_together[i,:] = (len(probs[:,1][probs[:,1]>prc/100]),
len(probs_perm[:,1][probs_perm[:,1]>prc/100]))
i=i+1
# Create dataframe with all failure probabilities for ordered and permuted cases
df_fails_prob_together = pd.DataFrame( fails_prob_together, index = thresholds,
columns = probs_agg.columns)
# Plot figure to compare the amount of cases above the thresholds
plt.figure(figsize=(6,6), dpi=150)
sns.lineplot(data=df_fails_prob_together)
plt.axvline(x=50, alpha=0.5,c='k',linestyle=(0, (5, 5)))
plt.ylabel('Amount of cases')
plt.xlabel('Threshold (%)')
plt.title('Number of cases above a failure prediction level')
plt.show()
plt.figure(figsize=(6,6), dpi=150)
sns.lineplot(data=df_fails_prob_together,
y=df_fails_prob_together['Ordered']/df_fails_prob_together['Permuted'],
x = df_fails_prob_together.index)
plt.ylabel('Ratio Ordered / permuted')
plt.xlabel('Threshold (%)')
plt.title('Ratio between ordered and permuted per threshold level')
plt.show()
sorted_probs = return_period(probs_agg, 'Ordered')
plt.scatter(x=sorted_probs["return-years"], y=sorted_probs["Ordered"])
plt.xscale('log')
plt.xlabel('years')
plt.ylabel('Failure probability')
plt.title("Confidence event and return period")
plt.show()
# print("The mean ratio across all thresholds is:", np.mean(df_fails_prob_together['Ordered']/df_fails_prob_together['Permuted']))
return probs_agg, sorted_probs
def probs_bootstrap(df_features_ec_season, probs, size_sample = 10):
probs_perm = np.empty([len(df_features_ec_season), size_sample])
for i in range(size_sample):
df_bootstrap = df_features_ec_season.apply(np.random.RandomState(seed=i).permutation, axis=0)
y_pred_i = brf_model.predict(df_bootstrap)
probs_i = brf_model.predict_proba(df_bootstrap)
probs_perm[:,i] = probs_i[:,1]
# Plot ensemble of permutations against ordered data
df_probs_perm = pd.DataFrame(probs_perm)
fails_prob_ord = np.empty([len(thresholds),1])
fails_prob_together = np.empty([len(thresholds),df_probs_perm.shape[1]])
i=0
for prc in thresholds:
fails_prob_ord[i] = len(probs[:,1][probs[:,1] > prc/100])
fails_prob_together[i,:] = pd.DataFrame( df_probs_perm.apply(lambda x: x[x > prc/100].count()) ).T
i=i+1
# Create dataframe with all failure probabilities for ordered and permuted cases
df_fails_prob_together = pd.DataFrame( fails_prob_together, index = thresholds,
columns = df_probs_perm.columns)
# print( np.mean(df_fails_prob_together, axis=1), np.std(df_fails_prob_together, axis=1))
# plot for ensemble with CI 0.99
fig, ax = plt.subplots()
ci = 2.58 * np.std(df_fails_prob_together, axis=1)/np.mean(df_fails_prob_together,axis=1)
ax.plot(df_fails_prob_together.index,fails_prob_ord )
ax.plot(df_fails_prob_together.index, df_fails_prob_together.mean(axis=1), '--')
ax.fill_between(df_fails_prob_together.index, (df_fails_prob_together.mean(axis=1)-ci), (df_fails_prob_together.mean(axis=1)+ci), color='r', alpha=.9)
ax.set_ylabel('Amount of cases')
ax.set_xlabel('Threshold (%)')
ax.set_title(f'Cases above a failure prediction level for ({size_sample} members)')
plt.show()
# Define the specification of the plot
thresholds=range(0,101,1)
# PERMUTATION ---------- Preliminary analysis shows that precipitation is such an important variable that it alone can predict a good amount of the failures, irrespective of the other variables
df_features_ec_season_permuted = df_features_ec_season.apply(np.random.RandomState(seed=1).permutation, axis=0)
# predictions for observed data PD
y_pred, score_prc, probs, seasons_over_2012 = predictions(brf_model, df_features_ec_season)
# Predictions for permuted
y_pred_perm, score_prc_perm, probs_perm, seasons_over_2012_perm = predictions(brf_model,df_features_ec_season_permuted)
# Difference between obs. and permuted
print(f"Permuted failure seasons are: {sum(y_pred_perm)} and ordered are: {sum(y_pred)}. Compound role is {sum(y_pred_perm)/sum(y_pred)}.")
print("The ratio between predicted failures in observed data and permuted data is:",
score_prc / score_prc_perm)
print("The difference between predicted failures in observed data and permuted data is:",
score_prc - score_prc_perm, "\n ")
# plots comparing prediction confidence for obs and perumuted
probs_agg,sorted_probs = plot_probs_failure(probs, probs_perm)
# check the ensembles to see how likely the ordered values stand wrt to the ensemble
probs_bootstrap_test = probs_bootstrap(df_features_ec_season, probs)
if df_features_ec_2C_season is None:
return score_prc
#%% Predictions for 2C degree
elif (df_features_ec_2C_season is not None and df_features_ec_3C_season is None):
# PERMUTATION ---------- Preliminary analysis shows that precipitation is such an important variable that it alone can predict a good amount of the failures, irrespective of the other variables
df_features_ec_2C_season_permuted = df_features_ec_2C_season.apply(np.random.RandomState(seed=1).permutation, axis=0)
# predictions for observed data PD
y_pred_2C, score_prc_2C, probs_2C, seasons_over_2012_2C = predictions(brf_model, df_features_ec_2C_season)
# Predictions for permuted
y_pred_2C_perm, score_prc_perm_2C, probs_perm_2C, seasons_over_2012_perm_2C = predictions(brf_model, df_features_ec_2C_season_permuted)
# Difference between obs. and permuted
print("The ratio between predicted failures in observed data and permuted data is:",
score_prc_2C / score_prc_perm_2C)
print("The difference between predicted failures in observed data and permuted data is:",
score_prc_2C - score_prc_perm_2C, '\n')
# plots comparing prediction confidence for obs and perumuted
probs_agg_2C, sorted_probs_2C = plot_probs_failure(probs_2C, probs_perm_2C)
# check the ensembles to see how likely the ordered values stand wrt to the ensemble
probs_2C_bootstrap_test = probs_bootstrap(df_features_ec_2C_season, probs_2C)
### Plot comparing 2C and PD return periods
plt.figure(figsize=(6,6), dpi=150)
sns.scatterplot(data = sorted_probs, x=sorted_probs["return-years"],
y=sorted_probs["Ordered"], label='PD',linewidth=0 )
sns.scatterplot(data = sorted_probs_2C, x=sorted_probs_2C["return-years"],
y=sorted_probs_2C["Ordered"], label = '2C',linewidth=0 )
if y_pred_2012 is not None:
plt.axhline(y = y_pred_2012, linestyle = '--', color = 'k', label='2012')
plt.xscale('log')
plt.legend(loc="lower right")
plt.xlabel('years')
plt.ylabel('Failure probability')
plt.title("Confidence event and return period for PD and 2C")
plt.show()
### Graph comparing ensemble PD for 100 years against 100 years CRU
probs_cru = brf_model.predict_proba(df_clim_agg_chosen)[:,1]
df_probs_cru=pd.DataFrame( probs_cru, columns = ['Ordered'])
sorted_probs_cru = return_period(df_probs_cru, 'Ordered')
# Reshape to have 100 years each column
probs_ec_ensemble = np.reshape(probs[:,1], (100,20))
probs_ec_ensemble = pd.DataFrame(probs_ec_ensemble)
df_ordered = np.empty([100,20])
df_return_year = np.empty([100,20])
for i in list(probs_ec_ensemble.columns):
sorted_probs_ec_ensemble = return_period(probs_ec_ensemble, [i])
df_ordered[:,i] = sorted_probs_ec_ensemble[i]
df_return_year[:,i] = sorted_probs_ec_ensemble["return-years"]
df_return_year = pd.DataFrame(df_return_year)
df_ordered = pd.DataFrame(df_ordered)
# Statistics ensemble // If each obs needs to be ploted: # plt.scatter( x=df_return_year, y=df_ordered)
ord_min = np.min(df_ordered, axis=1)
ord_max = np.max(df_ordered, axis=1)
ord_mean = np.mean(df_ordered, axis=1)
plt.figure(figsize=(6,6), dpi=150)
plt.fill_between(df_return_year[0], ord_min, ord_max,
facecolor="orange", # The fill color
color='blue', # The outline color
alpha=0.2, label= 'Ensemble') # Transparency of the fill
plt.scatter( x=df_return_year[0], y=ord_mean,label = 'Mean ensemble',)
sns.scatterplot(data = sorted_probs_cru, x=sorted_probs_cru["return-years"],
y=sorted_probs_cru["Ordered"], label = 'CRU',linewidth=0 )
plt.xscale('log')
plt.legend(loc="lower right")
plt.xlabel('years')
plt.ylabel('Failure probability')
plt.title("Confidence event and return period for PD and 2C")
plt.savefig('paper_figures/return_period_ensemble.png', format='png', dpi=150)
plt.show()
# Compare 2C with PD
print("Comparison PD with 2C")
print("The ratio between failures in 2C and PD is",score_prc_2C/score_prc, "\n")
print("The increase in failures between 2C and PD is", (score_prc_2C - score_prc)*100,"% \n")
# put them together in the same dataframe for plotting
probs_agg_t2=pd.DataFrame( [probs[:,1],probs_2C[:,1]]).T
probs_agg_t2.columns=['Present','2C']
# plots comparing prediction confidence for each arrangement of data
probs_agg_t2_melt = probs_agg_t2.melt(value_name='Failure probability').assign(data='Density')
# ax = sns.violinplot(data=probs_agg_t2_melt, x="data", y='Failure probability',
# hue='variable', split=True, inner="quartile",bw=.1)
# sns.displot(probs_agg_t2_melt, x="Failure probability",hue="variable", kind="kde", fill='True')
sns.displot(probs_agg_t2_melt, x="Failure probability",hue="variable",kde=False)
plt.show()
# Compare the number of cases above a failure threshold
fails_prob_together_2C = np.empty([len(thresholds),2])
i=0
for prc in thresholds:
# print(f'The number of PD seasons with failure probability over {prc}% is:',
# len(probs[:,1][probs[:,1]>prc/100]), 'and 2C is: ',
# len(probs_2C[:,1][probs_2C[:,1]>prc/100]))
fails_prob_together_2C[i,:] = (len(probs[:,1][probs[:,1]>prc/100]),
len(probs_2C[:,1][probs_2C[:,1]>prc/100]))
i=i+1
df_fails_prob_together_2C = pd.DataFrame( fails_prob_together_2C, index = thresholds, columns = probs_agg_t2.columns)
# Plot figure ti compare the amount of cases above the thresholds
plt.figure(figsize=(6,6), dpi=150)
sns.lineplot(data=df_fails_prob_together_2C)
plt.axvline(x=50, alpha=0.5,c='k',linestyle=(0, (5, 5)))
plt.ylabel('Amount of cases')
plt.xlabel('Threshold (%)')
plt.title('Number of cases above a failure prediction level')
plt.show()
plt.figure(figsize=(6,6), dpi=150)
sns.lineplot(data=df_fails_prob_together_2C, y=df_fails_prob_together_2C['2C']/df_fails_prob_together_2C['Present'], x = df_fails_prob_together_2C.index)
plt.ylabel('Ratio 2C / present')
plt.xlabel('Threshold (%)')
plt.title('Ratio between 2C and present for each threshold level')
plt.show()
# print("The mean ratio across all thresholds is:", np.mean(df_fails_prob_together_2C['2C']/df_fails_prob_together_2C['Present']))
# Table with occurrences of similar extreme values to 2012
table_events_prob2012 = pd.DataFrame([[len(seasons_over_2012),len(seasons_over_2012_2C)],
[len(seasons_over_2012_perm),len(seasons_over_2012_perm_2C)]],
columns = ['PD','2C'], index = ['Ord.','Perm.'])
print(table_events_prob2012)
# Table with scores comparison
table_scores = pd.DataFrame( [[score_prc, score_prc_2C, score_prc_2C/score_prc],
[score_prc_perm, score_prc_perm_2C, score_prc_perm_2C/score_prc_perm],
[score_prc/score_prc_perm,score_prc_2C/score_prc_perm_2C, np.nan ]],
columns = ['PD','2C', '2C/PD'], index = ['Ord.','Perm.', 'Ord./Perm.'] )
print(table_scores)
return table_scores, table_events_prob2012
#%% Predictions for 2C and 3C degree
elif (df_features_ec_2C_season is not None and df_features_ec_3C_season is not None):
# PERMUTATION ---------- Preliminary analysis shows that precipitation is such an important variable that it alone can predict a good amount of the failures, irrespective of the other variables
df_features_ec_2C_season_permuted = df_features_ec_2C_season.apply(np.random.RandomState(seed=1).permutation, axis=0)
df_features_ec_3C_season_permuted = df_features_ec_3C_season.apply(np.random.RandomState(seed=1).permutation, axis=0)
# predictions for observed data PD
y_pred_2C, score_prc_2C, probs_2C, seasons_over_2012_2C = predictions(brf_model, df_features_ec_2C_season)
# Predictions for permuted
y_pred_2C_perm, score_prc_perm_2C, probs_perm_2C, seasons_over_2012_perm_2C = predictions(brf_model, df_features_ec_2C_season_permuted)
# predictions for observed data PD
y_pred_3C, score_prc_3C, probs_3C, seasons_over_2012_3C = predictions(brf_model, df_features_ec_3C_season)
# Predictions for permuted
y_pred_3C_perm, score_prc_perm_3C, probs_perm_3C, seasons_over_2012_perm_3C = predictions(brf_model, df_features_ec_3C_season_permuted)
# Difference between obs. and permuted
print("The 2C ratio between predicted failures in observed data and permuted data is:",
score_prc_2C / score_prc_perm_2C)
print("The 3C ratio between predicted failures in observed data and permuted data is:",
score_prc_3C / score_prc_perm_3C)
# plots comparing prediction confidence for obs and perumuted
probs_agg_2C, sorted_probs_2C = plot_probs_failure(probs_2C, probs_perm_2C)
# check the ensembles to see how likely the ordered values stand wrt to the ensemble
probs_2C_bootstrap_test = probs_bootstrap(df_features_ec_2C_season, probs_2C)
# plots comparing prediction confidence for obs and perumuted
probs_agg_3C, sorted_probs_3C = plot_probs_failure(probs_3C, probs_perm_3C)
### Plot comparing 2C and PD return periods
plt.figure(figsize=(6,6), dpi=150)
sns.scatterplot(data = sorted_probs, x=sorted_probs["return-years"],
y=sorted_probs["Ordered"], label='PD',linewidth=0 )
sns.scatterplot(data = sorted_probs_2C, x=sorted_probs_2C["return-years"],
y=sorted_probs_2C["Ordered"], label = '2C',linewidth=0 )
sns.scatterplot(data = sorted_probs_3C, x=sorted_probs_3C["return-years"],
y=sorted_probs_3C["Ordered"], label = '3C',linewidth=0 )
if y_pred_2012 is not None:
plt.axhline(y = y_pred_2012, linestyle = '--', color = 'k', label='2012')
plt.xscale('log')
plt.legend(loc="lower right")
plt.xlabel('years')
plt.ylabel('Failure probability')
plt.title("Confidence event and return period for PD and 2C")
plt.show()
### Graph comparing ensemble PD for 100 years against 100 years CRU
probs_cru = brf_model.predict_proba(df_clim_agg_chosen)[:,1]
df_probs_cru=pd.DataFrame( probs_cru, columns = ['Ordered'])
sorted_probs_cru = return_period(df_probs_cru, 'Ordered')
# Reshape to have 100 years each column
probs_ec_ensemble = np.reshape(probs[:,1], (100,20))
probs_ec_ensemble = pd.DataFrame(probs_ec_ensemble)
df_ordered = np.empty([100,20])
df_return_year = np.empty([100,20])
for i in list(probs_ec_ensemble.columns):
sorted_probs_ec_ensemble = return_period(probs_ec_ensemble, [i])
df_ordered[:,i] = sorted_probs_ec_ensemble[i]
df_return_year[:,i] = sorted_probs_ec_ensemble["return-years"]
df_return_year = pd.DataFrame(df_return_year)
df_ordered = pd.DataFrame(df_ordered)
# Statistics ensemble // If each obs needs to be ploted: # plt.scatter( x=df_return_year, y=df_ordered)
ord_min = np.min(df_ordered, axis=1)
ord_max = np.max(df_ordered, axis=1)
ord_mean = np.mean(df_ordered, axis=1)
plt.figure(figsize=(6,6), dpi=150)
plt.fill_between(df_return_year[0], ord_min, ord_max,
facecolor="orange", # The fill color
color='blue', # The outline color
alpha=0.2, label= 'Ensemble') # Transparency of the fill
plt.scatter( x=df_return_year[0], y=ord_mean,label = 'Mean ensemble',)
sns.scatterplot(data = sorted_probs_cru, x=sorted_probs_cru["return-years"],
y=sorted_probs_cru["Ordered"], label = 'CRU',linewidth=0 )
plt.xscale('log')
plt.legend(loc="lower right")
plt.xlabel('years')
plt.ylabel('Failure probability')
plt.title("Confidence event and return period for PD and 2C")
plt.savefig('paper_figures/return_period_ensemble.png', format='png', dpi=150)
plt.show()
# Compare 2C with PD
print("Comparison PD with 2C")
print("The ratio between failures in 2C and PD is",score_prc_2C/score_prc, "\n")
print("The increase in failures between 2C and PD is", (score_prc_2C - score_prc)*100,"% \n")
print("Comparison PD with 2C")
print("The ratio between failures in 3C and PD is",score_prc_3C/score_prc, "\n")
print("The increase in failures between 3C and PD is", (score_prc_3C - score_prc)*100,"% \n")
# put them together in the same dataframe for plotting
probs_agg_t2=pd.DataFrame( [probs[:,1],probs_2C[:,1],probs_3C[:,1] ]).T
probs_agg_t2.columns=['Present','2C','3C']
# plots comparing prediction confidence for each arrangement of data
probs_agg_t2_melt = probs_agg_t2.melt(value_name='Failure probability').assign(data='Density')
# ax = sns.violinplot(data=probs_agg_t2_melt, x="data", y='Failure probability',
# hue='variable', split=True, inner="quartile",bw=.1)
# sns.displot(probs_agg_t2_melt, x="Failure probability",hue="variable", kind="kde", fill='True')
sns.displot(probs_agg_t2_melt, x="Failure probability",hue="variable",kde=False)
plt.show()
# Compare the number of cases above a failure threshold
fails_prob_together_3C = np.empty([len(thresholds),3])
i=0
for prc in thresholds:
# print(f'The number of PD seasons with failure probability over {prc}% is:',
# len(probs[:,1][probs[:,1]>prc/100]), 'and 2C is: ',
# len(probs_2C[:,1][probs_2C[:,1]>prc/100]))
fails_prob_together_3C[i,:] = (len(probs[:,1][probs[:,1]>prc/100]),