-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathplot_ms.py
More file actions
6910 lines (6232 loc) · 247 KB
/
Copy pathplot_ms.py
File metadata and controls
6910 lines (6232 loc) · 247 KB
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
# ---------------------------------------------------------------
# Functions to compute emergence of exposure from noise
# ----------------------------------------------------------------
#
#%% ----------------------------------------------------------------
# IMPORT AND PATH
# ----------------------------------------------------------------
import os
import requests
from zipfile import ZipFile
import io
import xarray as xr
import pickle as pk
import time
from mpl_toolkits.axes_grid1 import make_axes_locatable
from matplotlib.lines import Line2D
import matplotlib as mpl
import matplotlib.gridspec as gridspec
from matplotlib.patches import Rectangle
from matplotlib.patches import ConnectionPatch
from matplotlib.legend_handler import HandlerTuple
import matplotlib.lines as mlines
from matplotlib.patches import Circle, Wedge, Polygon
from matplotlib.collections import PatchCollection
import matplotlib.patheffects as pe
import mapclassify as mc
from copy import deepcopy as cp
import matplotlib.pyplot as plt
from matplotlib.colors import TwoSlopeNorm
import numpy as np
import pandas as pd
import regionmask as rm
import geopandas as gpd
from scipy import interpolate
import cartopy.crs as ccrs
import seaborn as sns
import cartopy as cr
import cartopy.feature as feature
from scipy.stats import ttest_rel
from scipy.stats import ttest_ind
from settings import *
ages, age_young, age_ref, age_range, year_ref, year_start, birth_years, year_end, year_range, GMT_max, GMT_min, GMT_inc, RCP2GMT_maxdiff_threshold, year_start_GMT_ref, year_end_GMT_ref, scen_thresholds, GMT_labels, GMT_window, GMT_current_policies, pic_life_extent, nboots, resample_dim, pic_by, pic_qntl, pic_qntl_list, pic_qntl_labels, sample_birth_years, sample_countries, GMT_indices_plot, birth_years_plot, letters, basins = init()
# %% ----------------------------------------------------------------
# Conceptual plot for emergence in one location,
def plot_conceptual(
da_cohort_size,
countries_mask,
countries_regions,
d_isimip_meta,
flags,
df_life_expectancy_5,
):
# get data
#
cntry='Belgium'
city_name='Brussels'
# cntry='Switzerland'
# city_name='Zurich'
# concept_bys = np.arange(1960,2021,30)
concept_bys = np.arange(1960,2021,1)
print(cntry)
da_smple_cht = da_cohort_size.sel(country=cntry) # cohort absolute sizes in sample country
da_smple_cht_prp = da_smple_cht / da_smple_cht.sum(dim='ages') # cohort relative sizes in sample country
da_cntry = xr.DataArray(
np.in1d(countries_mask,countries_regions.map_keys(cntry)).reshape(countries_mask.shape),
dims=countries_mask.dims,
coords=countries_mask.coords,
)
da_cntry = da_cntry.where(da_cntry,drop=True)
# weights for latitude (probably won't use but will use population instead)
lat_weights = np.cos(np.deg2rad(da_cntry.lat))
lat_weights.name = "weights"
# brussels coords
city_lat = 50.8476
city_lon = 4.3572
# zurich coords
# 47.3769° N, 8.5417° E
# city_lat = 47.3769
# city_lon = 8.5417
ds_spatial = xr.Dataset(
data_vars={
'cumulative_exposure': (
['run','GMT','birth_year','time','lat','lon'],
np.full(
(len(list(d_isimip_meta.keys())),
len(GMT_indices_plot),
len(concept_bys),
len(year_range),
len(da_cntry.lat.data),
len(da_cntry.lon.data)),
fill_value=np.nan,
),
),
},
coords={
'lat': ('lat', da_cntry.lat.data),
'lon': ('lon', da_cntry.lon.data),
'birth_year': ('birth_year', concept_bys),
'time': ('time', year_range),
'run': ('run', np.arange(1,len(list(d_isimip_meta.keys()))+1)),
'GMT': ('GMT', GMT_indices_plot)
}
)
# load demography pickle
with open('./data/{}/gridscale_dmg_{}.pkl'.format(flags['version'],cntry), 'rb') as f:
ds_dmg = pk.load(f)
# loop over simulations
for i in list(d_isimip_meta.keys()):
print('simulation {} of {}'.format(i,len(d_isimip_meta)))
# load AFA data of that run
with open('./data/{}/{}/isimip_AFA_{}_{}.pkl'.format(flags['version'],flags['extr'],flags['extr'],str(i)), 'rb') as f:
da_AFA = pk.load(f)
# mask to sample country and reduce spatial extent
da_AFA = da_AFA.where(ds_dmg['country_extent']==1,drop=True)
for step in GMT_indices_plot:
if d_isimip_meta[i]['GMT_strj_valid'][step]:
da_AFA_step = da_AFA.reindex(
{'time':da_AFA['time'][d_isimip_meta[i]['ind_RCP2GMT_strj'][:,step]]}
).assign_coords({'time':year_range})
# simple lifetime exposure sum
da_le = xr.concat(
[(da_AFA_step.loc[{'time':np.arange(by,ds_dmg['death_year'].sel(birth_year=by).item()+1)}].cumsum(dim='time') +\
da_AFA_step.sel(time=ds_dmg['death_year'].sel(birth_year=by).item()) *\
(ds_dmg['life_expectancy'].sel(birth_year=by).item() - np.floor(ds_dmg['life_expectancy'].sel(birth_year=by)).item()))\
for by in concept_bys],
dim='birth_year',
).assign_coords({'birth_year':concept_bys})
da_le = da_le.reindex({'time':year_range})
ds_spatial['cumulative_exposure'].loc[{
'run':i,
'GMT':step,
'birth_year':concept_bys,
'time':year_range,
'lat':ds_dmg['country_extent'].lat.data,
'lon':ds_dmg['country_extent'].lon.data,
}] = da_le.loc[{
'birth_year':concept_bys,
'time':year_range,
'lat':ds_dmg['country_extent'].lat.data,
'lon':ds_dmg['country_extent'].lon.data,
}]
# mean for brussels
da_test_city = ds_spatial['cumulative_exposure'].sel({'lat':city_lat,'lon':city_lon},method='nearest').mean(dim='run')
da_test_city = da_test_city.rolling(time=5,min_periods=5).mean()
# standard deviation for brussels
da_test_city_std = ds_spatial['cumulative_exposure'].sel({'lat':city_lat,'lon':city_lon},method='nearest').std(dim='run')
da_test_city_std = da_test_city_std.rolling(time=5,min_periods=5).mean()
# fill in 1st 4 years with 1s
# first for mean
for by in da_test_city.birth_year.data:
for step in GMT_indices_plot:
da_test_city.loc[{'birth_year':by,'GMT':step,'time':np.arange(by,by+5)}] = da_test_city.loc[{'birth_year':by,'GMT':step}].min(dim='time')
# then for std
for by in da_test_city_std.birth_year.data:
for step in GMT_indices_plot:
da_test_city_std.loc[{'birth_year':by,'GMT':step,'time':np.arange(by,by+5)}] = da_test_city_std.loc[{'birth_year':by,'GMT':step}].min(dim='time')
# load PIC pickles
with open('./data/{}/{}/gridscale_le_pic_{}_{}.pkl'.format(flags['version'],flags['extr'],flags['extr'],cntry), 'rb') as f:
ds_pic = pk.load(f)
with open('./data/{}/{}/{}/gridscale_pic_qntls_{}_{}.pkl'.format(flags['version'],flags['extr'],cntry,flags['extr'],cntry), 'rb') as f:
ds_pic_qntl = pk.load(f)
# plotting city lat/lon pixel doesn't give smooth kde
df_pic_city = ds_pic['lifetime_exposure'].sel({'lat':city_lat,'lon':city_lon},method='nearest').to_dataframe().drop(columns=['lat','lon',])
da_pic_city_9999 = ds_pic_qntl['99.99'].sel({'lat':city_lat,'lon':city_lon},method='nearest')
# concept figure
# ------------------------------------------------------------------
# plot building
from mpl_toolkits.axes_grid1 import inset_locator as inset
plt.rcParams['patch.linewidth'] = 0.1
plt.rcParams['patch.edgecolor'] = 'k'
colors = dict(zip(GMT_indices_plot,['steelblue','darkgoldenrod','darkred']))
x=5
y=1
l = 0
gmt_legend={
GMT_indices_plot[0]:'1.5',
GMT_indices_plot[1]:'2.5',
GMT_indices_plot[2]:'3.5',
}
# ------------------------------------------------------------------
# 1960 time series
f,ax = plt.subplots(
figsize=(x,y)
)
for step in GMT_indices_plot:
da_test_city.loc[{'birth_year':1960,'GMT':step}].plot.line(
ax=ax,
color=colors[step],
linewidth=1,
)
# bold line for emergence
da = da_test_city.loc[{'birth_year':1960,'GMT':step}]
da = da.where(da>da_pic_city_9999)
da.plot.line(
ax=ax,
color=colors[step],
linewidth=3,
zorder=4,
)
end_year=1960+np.floor(df_life_expectancy_5.loc[1960,cntry])
ax.set_ylabel(None)
ax.set_xlabel(None)
ax.set_xticks(np.arange(1960,2031,10))
ax.set_xticklabels([1960,None,1980,None,2000,None,2020,None])
ax.set_yticks([0,5])
ax.set_yticklabels([None,5])
ax.annotate(
'Born in 1960',
(1965,ax.get_ylim()[-1]+2),
xycoords=ax.transData,
fontsize=10,
fontweight='bold',
rotation='horizontal',
color='gray',
)
ax.set_title(None)
ax.annotate(
letters[l],
(1960,ax.get_ylim()[-1]+2),
xycoords=ax.transData,
fontsize=10,
rotation='horizontal',
color='k',
fontweight='bold',
)
l+=1
ax.set_xlim(
1960,
end_year,
)
ax.set_ylim(
0,
da_pic_city_9999+1,
)
ax.spines['right'].set_visible(False)
ax.spines['top'].set_visible(False)
ax.tick_params(colors='gray')
ax.spines['left'].set_color('gray')
ax.spines['bottom'].set_color('gray')
ax.hlines(
y=da_pic_city_9999,
xmin=1960,
xmax=da_test_city.loc[{'birth_year':1960}].time.max()+10,
colors='grey',
linewidth=1,
linestyle='--',
label='99.99%',
zorder=1
)
# 1960 pdf
ax_pdf_l = end_year+5
ax_pdf_b = -2
ax_pdf_w = 20
ax_pdf_h = ax.get_ylim()[-1]+2
ax_pdf = ax.inset_axes(
bounds=(ax_pdf_l, ax_pdf_b, ax_pdf_w, ax_pdf_h),
transform=ax.transData,
)
sns.histplot(
data=df_pic_city.round(),
y='lifetime_exposure',
color='lightgrey',
discrete = True,
ax=ax_pdf
)
ax_pdf.hlines(
y=da_pic_city_9999,
xmin=0,
xmax=df_pic_city['lifetime_exposure'][df_pic_city['lifetime_exposure']==0].count(),
colors='grey',
linewidth=1,
linestyle='--',
label='99.99%',
zorder=1
)
for step in GMT_indices_plot:
ax_pdf.hlines(
y=da_test_city.loc[{'birth_year':1960,'GMT':step}].max(),
xmin=0,
xmax=df_pic_city['lifetime_exposure'][df_pic_city['lifetime_exposure']==0].count(),
colors=colors[step],
linewidth=1,
linestyle='-',
label=gmt_legend[step],
zorder=2
)
ax_pdf.spines['right'].set_visible(False)
ax_pdf.spines['top'].set_visible(False)
ax_pdf.set_ylabel(None)
ax_pdf.set_xlabel(None)
ax_pdf.set_ylim(-2,ax.get_ylim()[-1])
ax_pdf.tick_params(colors='gray')
ax_pdf.spines['left'].set_color('gray')
ax_pdf.spines['bottom'].set_color('gray')
ax_pdf.set_title(
letters[l],
loc='left',
fontweight='bold',
fontsize=10,
)
l+=1
# ------------------------------------------------------------------
# 1990 time series
ax2_l = 1990
ax2_b = da_pic_city_9999 *2
ax2_w = np.floor(df_life_expectancy_5.loc[1990,cntry])
ax2_h = np.round(da_test_city.loc[{'birth_year':1990,'GMT':GMT_indices_plot[-1]}].max())
ax2 = ax.inset_axes(
bounds=(ax2_l, ax2_b, ax2_w, ax2_h),
transform=ax.transData,
)
for step in GMT_indices_plot:
da_test_city.loc[{'birth_year':1990,'GMT':step}].plot.line(
ax=ax2,
color=colors[step],
linewidth=1,
)
# bold line for emergence
da = da_test_city.loc[{'birth_year':1990,'GMT':step}]
da = da.where(da>da_pic_city_9999)
da.plot.line(
ax=ax2,
color=colors[step],
linewidth=3,
zorder=4,
)
end_year=1990+np.floor(df_life_expectancy_5.loc[1990,cntry])
ax2.set_ylabel(None)
ax2.set_xlabel(None)
ax2.set_yticks([0,5,10])
ax2.set_yticklabels([None,5,10])
ax2.set_xticks(np.arange(1990,2071,10))
ax2.set_xticklabels([None,2000,None,2020,None,2040,None,2060,None])
ax2.set_xlim(
1990,
end_year,
)
ax2.set_ylim(
0,
np.round(da_test_city.loc[{'birth_year':1990,'GMT':GMT_indices_plot[-1]}].max())+1,
)
ax2.spines['right'].set_visible(False)
ax2.spines['top'].set_visible(False)
ax2.spines['left'].set_position(('data',1990))
ax2.tick_params(colors='gray')
ax2.spines['left'].set_color('gray')
ax2.spines['bottom'].set_color('gray')
ax2.annotate(
'Born in 1990',
(1995,ax2.get_ylim()[-1]),
xycoords=ax2.transData,
fontsize=10,
fontweight='bold',
rotation='horizontal',
color='gray',
)
ax2.set_title(None)
ax2.annotate(
letters[l],
(1990,ax2.get_ylim()[-1]),
xycoords=ax2.transData,
fontsize=10,
rotation='horizontal',
color='k',
fontweight='bold',
)
l+=1
# get time of first line to cross PIC thresh
emergences = []
for step in GMT_indices_plot:
da = da_test_city.loc[{'birth_year':1990,'GMT':step}]
da = da.where(da>da_pic_city_9999)
if np.any(da.notnull()): # testing for median
da_t = da.time.where(da == da.min()).dropna(dim='time').item()
emergences.append(da_t)
first_emerge = np.min(emergences)
ax2.hlines(
y=da_pic_city_9999,
xmin=first_emerge,
xmax=end_year,
colors='grey',
linewidth=1,
linestyle='--',
label='99.99%',
zorder=1
)
# 1990 pdf
ax2_pdf_l = end_year+5
ax2_pdf_b = -2
ax2_pdf_w = 20
ax2_pdf_h = ax2.get_ylim()[-1]+2
ax2_pdf = ax2.inset_axes(
bounds=(ax2_pdf_l, ax2_pdf_b, ax2_pdf_w, ax2_pdf_h),
transform=ax2.transData,
)
sns.histplot(
data=df_pic_city.round(),
y='lifetime_exposure',
color='lightgrey',
discrete = True,
ax=ax2_pdf
)
ax2_pdf.hlines(
y=da_pic_city_9999,
xmin=0,
xmax=df_pic_city['lifetime_exposure'][df_pic_city['lifetime_exposure']==0].count(),
colors='grey',
linewidth=1,
linestyle='--',
label='99.99%',
zorder=1
)
for step in GMT_indices_plot:
ax2_pdf.hlines(
y=da_test_city.loc[{'birth_year':1990,'GMT':step}].max(),
xmin=0,
xmax=df_pic_city['lifetime_exposure'][df_pic_city['lifetime_exposure']==0].count(),
colors=colors[step],
linewidth=1,
linestyle='-',
label=gmt_legend[step],
zorder=2
)
ax2_pdf.spines['right'].set_visible(False)
ax2_pdf.spines['top'].set_visible(False)
ax2_pdf.set_ylabel(None)
ax2_pdf.set_xlabel(None)
ax2_pdf.set_ylim(-2,ax2.get_ylim()[-1])
ax2_pdf.tick_params(colors='gray')
ax2_pdf.spines['left'].set_color('gray')
ax2_pdf.spines['bottom'].set_color('gray')
ax2_pdf.set_title(
letters[l],
loc='left',
fontweight='bold',
fontsize=10,
)
l+=1
ax2_pdf.annotate(
'Unprecedented\nlifetime\nexposure\nfor {} people'.format(str(int(np.round(ds_dmg['by_population_y0'].sel({'birth_year':1990,'lat':city_lat,'lon':city_lon},method='nearest').item(),-3)))),
(1.1,0.3),
xycoords=ax2_pdf.transAxes,
fontsize=14,
rotation='horizontal',
color='gray',
# fontweight='bold',
)
# ------------------------------------------------------------------
# 2020 time series
ax3_l = 2020
ax3_b = np.round(da_test_city.loc[{'birth_year':1990,'GMT':GMT_indices_plot[-1]}].max()) * 1.5
ax3_w = np.floor(df_life_expectancy_5.loc[2020,cntry])
ax3_h = np.round(da_test_city.loc[{'birth_year':2020,'GMT':GMT_indices_plot[-1]}].max())
ax3 = ax2.inset_axes(
bounds=(ax3_l, ax3_b, ax3_w, ax3_h),
transform=ax2.transData,
)
# plot mean lines
for step in GMT_indices_plot:
da_test_city.loc[{'birth_year':2020,'GMT':step}].plot.line(
ax=ax3,
color=colors[step],
linewidth=1,
)
# bold line for emergence
da = da_test_city.loc[{'birth_year':2020,'GMT':step}]
da = da.where(da>da_pic_city_9999)
da.plot.line(
ax=ax3,
color=colors[step],
linewidth=3,
zorder=4,
)
end_year=2020+np.floor(df_life_expectancy_5.loc[2020,cntry])
ax3.set_ylabel(None)
ax3.set_xlabel(None)
ax3.set_yticks([0,5,10,15,20,25])
ax3.set_yticklabels([None,5,10,15,20,25])
ax3.set_xticks(np.arange(2020,2101,10))
ax3.set_xticklabels([2020,None,2040,None,2060,None,2080,None,2100])
ax3.set_xlim(
2020,
end_year,
)
ax3.set_ylim(
0,
np.round(da_test_city.loc[{'birth_year':2020,'GMT':GMT_indices_plot[-1]}].max())+1,
)
ax3.spines['right'].set_visible(False)
ax3.spines['top'].set_visible(False)
ax3.spines['left'].set_position(('data',2020))
ax3.tick_params(colors='gray')
ax3.spines['left'].set_color('gray')
ax3.spines['bottom'].set_color('gray')
# get time of first line to cross PIC thresh
emergences = []
for step in GMT_indices_plot:
da = da_test_city.loc[{'birth_year':2020,'GMT':step}]
da = da.where(da>da_pic_city_9999)
if np.any(da.notnull()):
da_t = da.time.where(da == da.min()).dropna(dim='time').item()
emergences.append(da_t)
first_emerge = np.min(emergences)
ax3.hlines(
y=da_pic_city_9999,
xmin=first_emerge,
xmax=end_year,
colors='grey',
linewidth=1,
linestyle='--',
label='99.99%',
zorder=1
)
ax3.annotate(
'Born in 2020',
(2025,ax3.get_ylim()[-1]),
xycoords=ax3.transData,
fontsize=10,
fontweight='bold',
rotation='horizontal',
color='gray',
)
ax3.set_title(None)
ax3.annotate(
letters[l],
(2020,ax3.get_ylim()[-1]),
xycoords=ax3.transData,
fontsize=10,
rotation='horizontal',
color='k',
fontweight='bold',
)
l+=1
# 2020 pdf
ax3_pdf_l = end_year+5
ax3_pdf_b = -2
ax3_pdf_w = 20
ax3_pdf_h = ax3.get_ylim()[-1]+2
ax3_pdf = ax3.inset_axes(
bounds=(ax3_pdf_l, ax3_pdf_b, ax3_pdf_w, ax3_pdf_h),
transform=ax3.transData,
)
sns.histplot(
data=df_pic_city.round(),
y='lifetime_exposure',
color='lightgrey',
discrete = True,
ax=ax3_pdf
)
ax3_pdf.hlines(
y=da_pic_city_9999,
xmin=0,
xmax=df_pic_city['lifetime_exposure'][df_pic_city['lifetime_exposure']==0].count(),
colors='grey',
linewidth=1,
linestyle='--',
label='99.99%',
zorder=1
)
for step in GMT_indices_plot:
ax3_pdf.hlines(
y=da_test_city.loc[{'birth_year':2020,'GMT':step}].max(),
xmin=0,
xmax=df_pic_city['lifetime_exposure'][df_pic_city['lifetime_exposure']==0].count(),
colors=colors[step],
linewidth=1,
linestyle='-',
label=gmt_legend[step],
zorder=2
)
ax3_pdf.spines['right'].set_visible(False)
ax3_pdf.spines['top'].set_visible(False)
ax3_pdf.set_ylabel(None)
ax3_pdf.set_xlabel(None)
ax3_pdf.set_ylim(-2,ax3.get_ylim()[-1])
ax3_pdf.tick_params(colors='gray')
ax3_pdf.spines['left'].set_color('gray')
ax3_pdf.spines['bottom'].set_color('gray')
ax3_pdf.set_title(
letters[l],
loc='left',
fontweight='bold',
fontsize=10,
)
l+=1
ax3_pdf.annotate(
'Unprecedented\nlifetime\nexposure\nfor {} people'.format(str(int(np.round(ds_dmg['by_population_y0'].sel({'birth_year':2020,'lat':city_lat,'lon':city_lon},method='nearest').item(),-3)))),
(1.1,0.6),
xycoords=ax3_pdf.transAxes,
fontsize=14,
rotation='horizontal',
color='gray',
# fontweight='bold',
)
# City name
ax3.annotate(
'{}, {}'.format(city_name,cntry),
(1960,ax3.get_ylim()[-1]),
xycoords=ax3.transData,
fontsize=16,
rotation='horizontal',
color='gray',
)
# axis labels ===================================================================
# x axis label (time)
x_i=1950
y_i=-10
x_f=2040
y_f=y_i
con = ConnectionPatch(
xyA=(x_i,y_i),
xyB=(x_f,y_f),
coordsA=ax.transData,
coordsB=ax.transData,
color='gray',
)
ax.add_artist(con)
con_arrow_top = ConnectionPatch(
xyA=(x_f-2,y_f+1),
xyB=(x_f,y_f),
coordsA=ax.transData,
coordsB=ax.transData,
color='gray',
)
ax.add_artist(con_arrow_top)
con_arrow_bottom = ConnectionPatch(
xyA=(x_f-2,y_f-1),
xyB=(x_f,y_f),
coordsA=ax.transData,
coordsB=ax.transData,
color='gray',
)
ax.add_artist(con_arrow_bottom)
ax.annotate(
'Time',
((x_i+x_f)/2,y_f+1),
xycoords=ax.transData,
fontsize=12,
color='gray',
)
# y axis label (Cumulative heatwave exposure since birth)
x_i=1950
y_i=-10
x_f=x_i
y_f=y_i + 61
con = ConnectionPatch(
xyA=(x_i,y_i),
xyB=(x_f,y_f),
coordsA=ax.transData,
coordsB=ax.transData,
color='gray',
)
ax.add_artist(con)
con_arrow_left = ConnectionPatch(
xyA=(x_f-2,y_f-1),
xyB=(x_f,y_f),
coordsA=ax.transData,
coordsB=ax.transData,
color='gray',
)
ax.add_artist(con_arrow_left)
con_arrow_right = ConnectionPatch(
xyA=(x_f+2,y_f-1),
xyB=(x_f,y_f),
coordsA=ax.transData,
coordsB=ax.transData,
color='gray',
)
ax.add_artist(con_arrow_right)
ax.annotate(
'Cumulative heatwave exposure since birth',
(x_i-10,(y_i+y_f)/5),
xycoords=ax.transData,
fontsize=12,
rotation='vertical',
color='gray',
)
# legend ===================================================================
# bbox
x0 = 1.5
y0 = 0.5
xlen = 0.5
ylen = 0.5
# space between entries
legend_entrypad = 0.5
# length per entry
legend_entrylen = 0.75
legend_font = 10
legend_lw=2
legendcols = list(colors.values())+['gray']+['lightgrey']
handles = [
Line2D([0],[0],linestyle='-',lw=legend_lw,color=legendcols[0]),
Line2D([0],[0],linestyle='-',lw=legend_lw,color=legendcols[1]),
Line2D([0],[0],linestyle='-',lw=legend_lw,color=legendcols[2]),
Line2D([0],[0],linestyle='--',lw=legend_lw,color=legendcols[3]),
Rectangle((0,0),1,1,color=legendcols[4]),
]
labels= [
'1.5 °C GMT warming by 2100',
'2.5 °C GMT warming by 2100',
'3.5 °C GMT warming by 2100',
'99.99% pre-industrial \n lifetime exposure',
'pre-industrial lifetime \n exposure histogram'
]
ax.legend(
handles,
labels,
bbox_to_anchor=(x0, y0, xlen, ylen), # bbox: (x, y, width, height)
loc='upper left',
ncol=1,
fontsize=legend_font,
labelcolor='gray',
mode="upper left",
borderaxespad=0.,
frameon=False,
columnspacing=0.05,
)
# population estimates
ds_dmg['population'].sel({'time':1990,'lat':city_lat,'lon':city_lon},method='nearest').sum(dim='age')
ds_dmg['by_population_y0'].sel({'birth_year':2020,'lat':city_lat,'lon':city_lon},method='nearest').item()
# getting estimate of all birth years that emerge in 1.5 and 3.5 pathways and how many these cohorts sum to
valid_bys=da_test_city.birth_year.where(da_test_city.loc[{'GMT':0}].max(dim='time')>da_pic_city_9999)
y1 = valid_bys.min(dim='birth_year')
y2 = valid_bys.max(dim='birth_year')
unprecedented=ds_dmg['by_population_y0'].sel(birth_year=np.arange(y1,y2+1),lat=city_lat,lon=city_lon,method='nearest').sum(dim='birth_year').round().item()
print('{} thousand unprecedented born in {} and later under pathway {}'.format(unprecedented/10**3,y1,0))
valid_bys=da_test_city.birth_year.where(da_test_city.loc[{'GMT':20}].max(dim='time')>da_pic_city_9999)
y1 = valid_bys.min(dim='birth_year')
y2 = valid_bys.max(dim='birth_year')
unprecedented=ds_dmg['by_population_y0'].sel(birth_year=np.arange(y1,y2+1),lat=city_lat,lon=city_lon,method='nearest').sum(dim='birth_year').round().item()
print('{} thousand unprecedented born in {} and later under pathway {}'.format(unprecedented/10**3,y1,20))
f.savefig('./ms_figures/f1_concept_{}_{}.png'.format(flags['version'],cntry),dpi=1000,bbox_inches='tight')
f.savefig('./ms_figures/f1_concept_{}_{}.pdf'.format(flags['version'],cntry),dpi=1000,bbox_inches='tight')
#%% ----------------------------------------------------------------
# plotting pf heatmaps for grid scale across hazards with and without
# limiting simulations to show ensemble effects on GMT scaling
def plot_heatmaps_allhazards(
df_GMT_strj,
da_gs_popdenom,
flags,
):
letters = ['a', 'b', 'c',\
'd', 'e', 'f',\
'g', 'h', 'i',\
'j', 'k', 'l']
extremes = [
'heatwavedarea',
'cropfailedarea',
'burntarea',
'driedarea',
'floodedarea',
'tropicalcyclonedarea',
]
# extremes_labels = {
# 'burntarea': '$\mathregular{PF_{Wildfires}}$',
# 'cropfailedarea': '$\mathregular{PF_{Crop failures}}$',
# 'driedarea': '$\mathregular{PF_{Droughts}}$',
# 'floodedarea': '$\mathregular{PF_{Floods}}$',
# 'heatwavedarea': '$\mathregular{PF_{Heatwaves}}$',
# 'tropicalcyclonedarea': '$\mathregular{PF_{Tropical cyclones}}$',
# }
extremes_labels = {
'heatwavedarea': '$\mathregular{CF_{Heatwaves}}$ [%]',
'cropfailedarea': '$\mathregular{CF_{Crop failures}}$ [%]',
'burntarea': '$\mathregular{CF_{Wildfires}}$ [%]',
'driedarea': '$\mathregular{CF_{Droughts}}$ [%]',
'floodedarea': '$\mathregular{CF_{Floods}}$ [%]',
'tropicalcyclonedarea': '$\mathregular{CF_{Tropical cyclones}}$ [%]',
}
unprec_level="unprec_99.99"
# labels for GMT ticks
# GMT_indices_ticks=[6,12,18,24]
GMT_indices_ticks=[0,5,10,15,20]
gmts2100 = np.round(df_GMT_strj.loc[2100,GMT_indices_ticks].values,1)
levels_hw=np.arange(0,101,10)
levels_cf=np.arange(0,31,5)
levels_other=np.arange(0,16,1)
# # --------------------------------------------------------------------
# # population fractions with simulation limits to avoid dry jumps
# # loop through extremes and concat pop and pop frac
# list_extrs_pf = []
# for extr in extremes:
# with open('./data/{}/{}/gridscale_aggregated_pop_frac_{}.pkl'.format(flags['version'],extr,extr), 'rb') as file:
# ds_pf_gs_extr = pk.load(file)
# with open('./data/{}/{}/isimip_metadata_{}_ar6_new_rm.pkl'.format(flags['version'],extr,extr), 'rb') as file:
# d_isimip_meta = pk.load(file)
# sims_per_step = {}
# for step in GMT_labels:
# sims_per_step[step] = []
# print('step {}'.format(step))
# for i in list(d_isimip_meta.keys()):
# if d_isimip_meta[i]['GMT_strj_valid'][step]:
# sims_per_step[step].append(i)
# if extr != 'cropfailedarea':
# p = ds_pf_gs_extr[unprec_level].loc[{
# 'GMT':np.arange(GMT_indices_plot[0],GMT_indices_plot[-1]+1).astype('int'),
# 'run':sims_per_step[GMT_labels[-1]]
# }].sum(dim='country')
# else: # for some reason, cropfailedarea doesn't have 3.5th in earlier v1 pickle run?
# p = ds_pf_gs_extr[unprec_level].loc[{
# 'GMT':np.arange(GMT_indices_plot[0],GMT_indices_plot[-1]+1).astype('int'),
# 'run':sims_per_step[GMT_labels[-1]]
# }].sum(dim='country')
# p = p.where(p!=0).mean(dim='run') / da_gs_popdenom.sum(dim='country') *100
# list_extrs_pf.append(p)
# ds_pf_gs_extrs = xr.concat(list_extrs_pf,dim='hazard').assign_coords({'hazard':extremes})
# # plot
# mpl.rcParams['xtick.labelcolor'] = 'gray'
# mpl.rcParams['ytick.labelcolor'] = 'gray'
# x=14
# y=7
# f,axes = plt.subplots(
# nrows=2,
# ncols=3,
# figsize=(x,y),
# )
# for ax,extr in zip(axes.flatten(),extremes):
# if extr == 'heatwavedarea':
# p = ds_pf_gs_extrs.loc[{
# 'hazard':extr,
# 'birth_year':np.arange(1960,2021),
# }].plot.contourf(
# x='birth_year',
# y='GMT',
# ax=ax,
# add_labels=False,
# # levels=10,
# levels=levels_hw,
# cmap='Reds',
# cbar_kwargs={'ticks':np.arange(0,101,20)}
# )
# elif extr == 'cropfailedarea':
# p = ds_pf_gs_extrs.loc[{
# 'hazard':extr,
# 'birth_year':np.arange(1960,2021),
# }].plot.contourf(
# x='birth_year',
# y='GMT',
# ax=ax,
# add_labels=False,
# # levels=10,
# levels=levels_cf,
# cmap='Reds',
# cbar_kwargs={'ticks':np.arange(0,31,5)}
# )
# else:
# p = ds_pf_gs_extrs.loc[{
# 'hazard':extr,
# 'birth_year':np.arange(1960,2021),
# }].plot.contourf(
# x='birth_year',
# y='GMT',
# ax=ax,
# add_labels=False,
# # levels=10,
# levels=levels_other,
# cmap='Reds',
# cbar_kwargs={'ticks':np.arange(0,16,3)}
# )
# ax.set_yticks(
# ticks=GMT_indices_ticks,
# labels=gmts2100,
# color='gray',
# )
# ax.set_xticks(
# ticks=np.arange(1960,2025,10),
# color='gray',
# )
# # ax stuff
# l=0
# for n,ax in enumerate(axes.flatten()):
# ax.set_title(
# extremes_labels[extremes[n]],
# loc='center',
# fontweight='bold',
# color='gray',
# fontsize=12,
# )
# ax.set_title(
# letters[l],
# loc='left',
# fontweight='bold',
# fontsize=10,
# )
# l+=1
# ax.spines['right'].set_color('gray')
# ax.spines['top'].set_color('gray')
# ax.spines['left'].set_color('gray')
# ax.spines['bottom'].set_color('gray')
# if not np.isin(n,[0,3]):
# ax.yaxis.set_ticklabels([])
# if n == 0:
# ax.annotate(
# 'GMT warming by 2100 [°C]',
# (-.3,-0.6),
# xycoords=ax.transAxes,
# fontsize=12,
# rotation='vertical',
# color='gray',
# # fontweight='bold',
# )
# if n <= 2:
# ax.tick_params(labelbottom=False)
# if n >= 3:
# ax.set_xlabel('Birth year',fontsize=12,color='gray')
# f.savefig('./ms_figures/pf_heatmap_combined_simlim_{}.png'.format(flags['version']),dpi=1000,bbox_inches='tight')
# f.savefig('./ms_figures/pf_heatmap_combined_simlim_{}.eps'.format(flags['version']),format='eps',bbox_inches='tight')
# plt.show()
# --------------------------------------------------------------------
# population fractions with all simulations
# loop through extremes and concat pop and pop frac
list_extrs_pf = []
for extr in extremes:
with open('./data/{}/{}/gridscale_aggregated_pop_frac_{}.pkl'.format(flags['version'],extr,extr), 'rb') as file:
ds_pf_gs_extr = pk.load(file)
p = ds_pf_gs_extr[unprec_level].loc[{
'GMT':np.arange(GMT_indices_plot[0],GMT_indices_plot[-1]+1).astype('int'),
}].sum(dim='country')
p = p.where(p!=0).mean(dim='run') / da_gs_popdenom.sum(dim='country') *100
list_extrs_pf.append(p)
ds_pf_gs_extrs = xr.concat(list_extrs_pf,dim='hazard').assign_coords({'hazard':extremes})