-
Notifications
You must be signed in to change notification settings - Fork 0
/
analysis_country_specific.py
2142 lines (1962 loc) · 71.6 KB
/
analysis_country_specific.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 csv
from collections import defaultdict
import json
import math
import os
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib
import util
import analysis_main
from coal_export.common import modify_avoided_emissions_based_on_coal_export
matplotlib.use("agg")
def flatten_list_of_list(xss):
return [x for xs in xss for x in xs]
# Countries that we have data for, for unilateral action.
# We intentionally exclude XK.
unilateral_countries = {
"MM",
"TZ",
"GB",
"HU",
"RO",
"TH",
"CO",
"US",
"ZM",
"MN",
"PL",
"KG",
"ZW",
"DE",
"VN",
"TJ",
"RU",
"CA",
"TR",
"LA",
"BR",
"NG",
"IR",
"MK",
"RS",
"UA",
"MW",
"ID",
"PK",
"KZ",
"ME",
"AU",
"MX",
"BG",
"SK",
"MZ",
"JP",
"CN",
"ES",
"MG",
"ZA",
"ET",
"CL",
"GR",
"CD",
"NE",
"NO",
"PE",
"SI",
"UZ",
"IN",
"CZ",
"PH",
"VE",
"AR",
"BA",
"BD",
"BW",
"GE",
"NZ",
}
G7 = "US JP DK GB DE IT NO".split()
EU = "AT BE BG CY CZ DK EE FI FR DE GR HU HR IE IT LV LT LU MT NL PL PT RO SK SI ES SE".split()
eurozone = "AT BE HR CY EE FI FR DE GR IE IT LV LT LU MT NL PT SK SI ES".split()
# Largest by avoided emissions
# Taken from avoided_emissions_nonadjusted.csv (see Zulip).
by_avoided_emissions = "CN AU US IN RU ID ZA CA PL KZ CO DE MZ MN UA TR VN BW GR BR CZ BG RO TH RS GB UZ PH ZW NZ MX BD BA LA IR CL ES PK VE TZ HU ME SK ZM SI MG TJ MK GE AR MM JP KG MW NG NE PE NO ET CD".split()
countries_after_coal_export = "AE AF AG AM AO AR AT AU AW AZ BA BB BD BE BF BG BH BI BJ BM BN BO BR BS BW BY BZ CA CD CG CH CI CL CN CO CR CY CZ DE DK DO EC EE EG ES ET FI FJ FR GB GD GE GH GR GT GY HK HN HR HU ID IE IL IN IR IS IT JM JO JP KE KG KH KM KR KW KZ LA LB LC LK LS LT LU LV LY MA MD ME MG MK ML MM MN MS MT MU MV MW MX MY MZ NA NE NG NI NL NO NP NZ OM PA PE PF PH PK PL PS PT PY QA RO RS RU RW SA SC SE SG SI SK SN SV SZ TG TH TJ TN TR TT TZ UA UG US UY UZ VC VE VN XK YE ZA ZM ZW".split()
# Doesn't have SCC value
for c in "AG AW BB BF BH BM FJ GD HK LC MS MT MV NA PF PS SC SG XK".split():
countries_after_coal_export.remove(c)
def prepare_level_development():
(
iso3166_df,
_,
_,
_,
developed_country_shortnames,
) = util.prepare_from_climate_financing_data()
developING_country_shortnames = util.get_developing_countries()
emerging_country_shortnames = util.get_emerging_countries()
levels = [
"Developed Countries",
"Developing Countries",
"Emerging Market Countries",
]
levels_map = {
"Developed Countries": developed_country_shortnames,
"Developing Countries": developING_country_shortnames,
"Emerging Market Countries": emerging_country_shortnames,
}
return levels, levels_map, iso3166_df
def _do_sanity_check_for_calculate_cs_scc_data(
unilateral_actor,
isa_climate_club,
bs,
cs,
bs_region,
cs_region,
unilateral_emissions,
cumulative_benefit,
global_benefit,
global_emissions,
unilateral_emissions_GtCO2,
levels,
cost_climate_club,
benefit_climate_club,
):
# Sanity check
if unilateral_actor is None:
return
if unilateral_actor == "EMDE":
return
# SC1
# We don't test based on region, because PG and WS are not part of
# the 6 regions.
# world_benefit_but_unilateral_action = sum(sum(v) for v in bs_region.values())
world_benefit_but_unilateral_action = sum(sum(v) for v in bs.values())
# Check that the computed world scc corresponds to the original world scc.
if unilateral_emissions > 0:
actual_world_scc = world_benefit_but_unilateral_action / unilateral_emissions
assert math.isclose(
actual_world_scc, util.social_cost_of_carbon
), actual_world_scc
# SC2
if not isa_climate_club:
# The unilateral actor is a country
# Cumulative benefit is the unilateral benefit of the country.
ratio1 = cumulative_benefit / global_benefit
ratio2 = unilateral_emissions_GtCO2 / global_emissions
assert math.isclose(ratio1, ratio2), (ratio1, ratio2)
else:
# Unilateral action is either a region or level of development.
# Double checking that they add up to the same amount
if unilateral_actor in levels:
assert math.isclose(cost_climate_club, sum(cs[unilateral_actor]))
assert math.isclose(benefit_climate_club, sum(bs[unilateral_actor]))
else:
# Region
actual = sum(cs_region[unilateral_actor])
assert math.isclose(cost_climate_club, actual), (
cost_climate_club,
actual,
)
actual = sum(bs_region[unilateral_actor])
assert math.isclose(benefit_climate_club, actual), (
benefit_climate_club,
actual,
)
def calculate_country_specific_scc_data(
unilateral_actor=None,
ext="",
to_csv=True,
last_year=None,
cost_name="cost",
):
if last_year is None:
last_year = 2100
chosen_s2_scenario = f"{analysis_main.NGFS_PEG_YEAR}-{last_year} 2DII + Net Zero 2050 Scenario"
costs_dict = analysis_main.calculate_each_countries_with_cache(
chosen_s2_scenario,
"plots/country_specific_cost.json",
ignore_cache=True,
info_name=cost_name,
last_year=last_year,
)
out = analysis_main.run_table1(to_csv=False, do_round=False)
global_benefit = out[
"Benefits of avoiding coal emissions including residual benefit (in trillion dollars)"
][chosen_s2_scenario]
global_emissions = out["Total emissions avoided including residual (GtCO2)"][
chosen_s2_scenario
]
# In dollars/tCO2
country_specific_scc = util.read_country_specific_scc_filtered()
total_scc = sum(country_specific_scc.values())
levels, levels_map, iso3166_df = prepare_level_development()
region_countries_map, regions = analysis_main.prepare_regions_for_climate_financing(
iso3166_df
)
_, iso2_to_country_name = util.get_country_to_region()
unilateral_benefit = None
unilateral_emissions = None
isa_climate_club = unilateral_actor in (levels + regions + ["EMDE"])
cost_climate_club = None
benefit_climate_club = None
benefit_of_country_doing_the_action = None
if unilateral_actor is not None:
# Generated from the Git branch unilateral_action_benefit
suffix = "_with_coal_export" if analysis_main.ENABLE_COAL_EXPORT else ""
cache_name = (
f"cache/unilateral_benefit_total_trillion_{last_year}{suffix}.json"
)
unilateral_benefit = util.read_json(cache_name)
if isa_climate_club:
unilateral_emissions = 0.0
cost_climate_club = 0.0
benefit_climate_club = 0.0
if unilateral_actor in levels:
group = levels_map[unilateral_actor]
elif unilateral_actor == "EMDE":
group = (
levels_map["Emerging Market Countries"]
+ levels_map["Developing Countries"]
)
else:
group = region_countries_map[unilateral_actor]
for country in group:
if country not in unilateral_benefit:
# Skip if we don't have the data for it.
continue
# TODO we should have just used a JSON data of unilateral
# emissions.
ub = unilateral_benefit[country]
scc = (
country_specific_scc[country]
/ total_scc
* util.social_cost_of_carbon
)
unilateral_emissions += ub / scc
cost_climate_club += costs_dict[country]
# We have to first sum the emissions across the countries, in order
# to get the benefit of the climate club.
for country in group:
if country not in country_specific_scc:
# Skip if we don't have scc data of the country.
continue
scc = (
country_specific_scc[country]
/ total_scc
* util.social_cost_of_carbon
)
benefit_climate_club += unilateral_emissions * scc
else:
benefit_of_country_doing_the_action = unilateral_benefit[unilateral_actor]
scc = (
country_specific_scc[unilateral_actor]
/ total_scc
* util.social_cost_of_carbon
)
unilateral_emissions = benefit_of_country_doing_the_action / scc
# From "trillion" tCO2 to Giga tCO2
if unilateral_emissions is not None:
unilateral_emissions_GtCO2 = unilateral_emissions * 1e3
else:
unilateral_emissions_GtCO2 = None
# print("emissions Giga tCO2", unilateral_actor, unilateral_emissions_GtCO2)
names = defaultdict(list)
cs_level = defaultdict(list)
bs_level = defaultdict(list)
names_region = defaultdict(list)
cs_region = defaultdict(list)
bs_region = defaultdict(list)
no_cost = []
benefit_greater_than_cost = []
costly = []
table = pd.DataFrame(
columns=[
"iso2",
# Commented out so for the website purpose, so that we use
# consistent country naming according to ISO 3166.
# "country_name",
"net_benefit",
"benefit",
"cost",
"country_specific_scc",
]
)
climate_club_countries = None
if isa_climate_club:
if unilateral_actor in levels:
climate_club_countries = levels_map[unilateral_actor]
elif unilateral_actor == "EMDE":
climate_club_countries = (
levels_map["Emerging Market Countries"]
+ levels_map["Developing Countries"]
)
else:
climate_club_countries = region_countries_map[unilateral_actor]
cumulative_benefit = 0.0 # For sanity check
actual_size = 0 # For sanity check
for country, unscaled_scc in country_specific_scc.items():
if country not in costs_dict:
c = 0.0
else:
c = costs_dict[country]
if unilateral_actor is not None:
if isa_climate_club:
if country not in climate_club_countries:
c = 0.0
elif country != unilateral_actor:
# unilateral_actor is 1 country
c = 0.0
cs_scc_scale = unscaled_scc / total_scc
if unilateral_actor is not None:
scc = util.social_cost_of_carbon * cs_scc_scale
b = unilateral_emissions * scc
if not isa_climate_club and unilateral_actor == country:
# SC3
# Sanity check for when the unilateral actor is 1 country only.
assert math.isclose(b, benefit_of_country_doing_the_action)
else:
# Global action
b = cs_scc_scale * global_benefit
cumulative_benefit += b
net_benefit = b - c
table = pd.concat(
[
table,
pd.DataFrame(
[
{
"iso2": country,
# Commented out so for the website purpose, so that we use
# consistent country naming according to ISO 3166.
# "country_name": iso2_to_country_name[country],
"net_benefit": net_benefit,
"benefit": b,
"cost": c,
"country_specific_scc": unscaled_scc,
}
]
),
],
ignore_index=True,
)
if math.isclose(c, 0.0):
no_cost.append(country)
elif b >= c:
benefit_greater_than_cost.append(country)
else:
costly.append(country)
if unilateral_actor == "EMDE":
if (country in levels_map["Developing Countries"]) or (
country in levels_map["Emerging Market Countries"]
):
cs_level["EMDE"].append(c)
bs_level["EMDE"].append(b)
names["EMDE"].append(country)
elif country in levels_map["Developed Countries"]:
cs_level["Developed Countries"].append(c)
bs_level["Developed Countries"].append(b)
names["Developed Countries"].append(country)
else:
if country in levels_map["Developed Countries"]:
cs_level["Developed Countries"].append(c)
bs_level["Developed Countries"].append(b)
names["Developed Countries"].append(country)
elif country in levels_map["Developing Countries"]:
cs_level["Developing Countries"].append(c)
bs_level["Developing Countries"].append(b)
names["Developing Countries"].append(country)
elif country in levels_map["Emerging Market Countries"]:
cs_level["Emerging Market Countries"].append(c)
bs_level["Emerging Market Countries"].append(b)
names["Emerging Market Countries"].append(country)
else:
print("Skipping", country)
part_of_region = False
for region in regions:
if country in region_countries_map[region]:
cs_region[region].append(c)
bs_region[region].append(b)
names_region[region].append(country)
part_of_region = True
break
if not part_of_region:
print("Not part of any region", country)
print("country-specific country count", len(country_specific_scc))
print("No cost", len(no_cost))
print("benefit >= cost", len(benefit_greater_than_cost), benefit_greater_than_cost)
print("cost > benefit", len(costly), costly)
actual_size += len(no_cost) + len(benefit_greater_than_cost) + len(costly)
assert actual_size == len(country_specific_scc), (
actual_size,
len(country_specific_scc),
)
# Sanity check
_do_sanity_check_for_calculate_cs_scc_data(
unilateral_actor,
isa_climate_club,
bs_level,
cs_level,
bs_region,
cs_region,
unilateral_emissions,
cumulative_benefit,
global_benefit,
global_emissions,
unilateral_emissions_GtCO2,
levels,
cost_climate_club,
benefit_climate_club,
)
if to_csv:
table = table.sort_values(by="net_benefit", ascending=False)
table.to_csv(
f"plots/country_specific_table{ext}.csv", index=False, float_format="%.5f"
)
return (
cs_level,
bs_level,
names,
cs_region,
bs_region,
names_region,
unilateral_emissions_GtCO2,
)
def do_country_specific_scc_part3():
raise Exception("This is not yet sanity checked")
emerging = "Emerging Market Countries"
(
cs_emerging,
bs_emerging,
names_emerging,
_,
_,
_,
_,
) = calculate_country_specific_scc_data(
unilateral_actor=emerging,
to_csv=False,
)
cs_emerging = dict(sorted(cs_emerging.items()))
bs_emerging = dict(sorted(bs_emerging.items()))
names_emerging = dict(sorted(names_emerging.items()))
developing = "Developing Countries"
(
cs_developing,
bs_developing,
names_developing,
_,
_,
_,
_,
) = calculate_country_specific_scc_data(
unilateral_actor=developing,
to_csv=False,
)
cs_developing = dict(sorted(cs_developing.items()))
bs_developing = dict(sorted(bs_developing.items()))
names_developing = dict(sorted(names_developing.items()))
fig, axs = plt.subplots(1, 2, figsize=(8, 4))
plt.sca(axs[0])
for level, c in cs_emerging.items():
total_c = sum(c)
total_b = sum(bs_emerging[level])
plt.plot(
total_c, total_b, linewidth=0, marker="o", label=level, fillstyle="none"
)
# 45 degree line
axs[0].axline([0, 0], [0.05, 0.05])
plt.xlabel("PV country-specific costs (bln dollars)")
plt.ylabel("PV country-specific benefits (bln dollars)")
plt.title(emerging)
plt.sca(axs[1])
for level, c in cs_developing.items():
total_c = sum(c)
total_b = sum(bs_developing[level])
plt.plot(
total_c, total_b, linewidth=0, marker="o", label=level, fillstyle="none"
)
# 45 degree line
axs[1].axline([0, 0], [0.05, 0.05])
plt.xlabel("PV country-specific costs (bln dollars)")
plt.ylabel("PV country-specific benefits (bln dollars)")
plt.title(developing)
# Deduplicate labels
handles, labels = plt.gca().get_legend_handles_labels()
by_label = dict(zip(labels, handles))
fig.legend(
by_label.values(),
by_label.keys(),
loc="upper center",
bbox_to_anchor=(0.5, -0.01),
ncol=len(by_label.values()),
)
plt.tight_layout()
util.savefig("country_specific_scatter_part3", tight=True)
def do_country_specific_scc_part4():
# We save to CSV so that the data is shown in the website.
cs, bs, _, _, bs_region, _, _ = calculate_country_specific_scc_data(
unilateral_actor=None,
ext="_part4",
to_csv=False,
)
# Sanity check
# SC4
# The circles in the plot add up to baseline global benefit.
# 114.04 is the global benefit under baseline settings.
actual_global_benefit = sum(sum(b) for b in bs.values())
assert math.isclose(
actual_global_benefit, 114.04380627502013
), actual_global_benefit
actual_global_benefit = sum(sum(b) for b in bs_region.values())
# This is not 114.04, because PG and WS are not part of the 6 regions (they
# are in Oceania).
assert math.isclose(actual_global_benefit, 114.025120520287), actual_global_benefit
# SC5
# Cost
global_cost = 29.03104345418096 # Hardcoded for fast computation.
# Cost for Kosovo. To be excluded.
cost_XK = 0.03241056086650181
actual = sum(sum(c) for c in cs.values())
assert math.isclose(actual, global_cost - cost_XK)
plt.figure()
ax = plt.gca()
def mul_1000(x):
return [i * 1e3 for i in x]
# Multiplication by 1000 converts to billion dollars
for level, c in cs.items():
plt.plot(
mul_1000(c),
mul_1000(bs[level]),
linewidth=0,
marker="o",
label=level,
fillstyle="none",
)
# 45 degree line
ax.axline([0, 0], [1, 1])
plt.xlabel("PV country costs (bln dollars)")
plt.ylabel("PV country benefits (bln dollars)")
ax.set_xscale("log")
ax.set_yscale("log")
axis_limit = 45_000
plt.xlim(5e-2, axis_limit)
plt.ylim(5e-2, axis_limit)
plt.legend()
util.savefig("country_specific_scatter_part4")
def calculate_global_benefit(last_year=None):
if last_year is None:
last_year = 2100
out = analysis_main.run_table1(to_csv=False, do_round=False, plot_yearly=False)
chosen_s2_scenario = f"{analysis_main.NGFS_PEG_YEAR}-{last_year} 2DII + Net Zero 2050 Scenario"
property = "Benefits of avoiding coal emissions including residual benefit (in trillion dollars)"
global_benefit = out[property][chosen_s2_scenario]
return global_benefit
def do_country_specific_scc_part5():
regions = [
"Asia",
"Africa",
"North America",
"Latin America & the Carribean",
"Europe",
"Australia & New Zealand",
]
git_branch = util.get_git_branch()
fname = f"cache/country_specific_data_part5_git_{git_branch}.json"
if os.path.isfile(fname):
content = util.read_json(fname)
cs_region_combined = content["unilateral_cost"]
bs_region_combined = content["unilateral_benefit"]
zerocost = content["freeloader_benefit"]
global_benefit_by_region = content["global_benefit"]
else:
cs_region_combined = {}
bs_region_combined = {}
zerocost = {}
# We round everything to 6 digits, and so the precision is thousand dollars.
def do_round(x):
return round(x, 6)
# This variable is for sanity check
unilateral_emissions_cumulative = 0.0
for group in regions:
unilateral_actor = group
(
_,
_,
_,
cs_region,
bs_region,
_,
unilateral_emissions_GtCO2,
) = calculate_country_specific_scc_data(
unilateral_actor=unilateral_actor,
ext="",
to_csv=False,
)
cs_region_combined[group] = do_round(sum(cs_region[group]))
bs_region_combined[group] = do_round(sum(bs_region[group]))
# group is the entity doing the unilateral action, while the
# regions inside the dict is the one who gets benefit with zero
# cost.
zerocost[group] = {
k: do_round(sum(v)) for k, v in bs_region.items() if k != group
}
unilateral_emissions_cumulative += unilateral_emissions_GtCO2
# Sanity check
# SC6
# Make sure the unilateral emissions, if summed, is the same as baseline result.
# It's not 1425.55 because XK is excluded from the 6 regions.
assert math.isclose(
unilateral_emissions_cumulative, 1424.1494924127742
), unilateral_emissions_cumulative
# This code chunk is used to calculate global_benefit_by_region
global_benefit = calculate_global_benefit()
scc_dict = util.read_country_specific_scc_filtered()
unscaled_global_scc = sum(scc_dict.values())
iso3166_df = util.read_iso3166()
region_countries_map, _ = analysis_main.prepare_regions_for_climate_financing(
iso3166_df
)
global_benefit_by_region = {}
# End of global_benefit_by_region preparation
for region in cs_region_combined.keys():
countries = region_countries_map[region]
scc_scale = (
sum(scc_dict.get(c, 0.0) for c in countries) / unscaled_global_scc
)
# Benefit to 1 region if everyone in the world takes action
global_benefit_by_region[region] = do_round(global_benefit * scc_scale)
with open(fname, "w") as f:
json.dump(
{
"unilateral_cost": cs_region_combined,
"unilateral_benefit": bs_region_combined,
"freeloader_benefit": zerocost,
"global_benefit": global_benefit_by_region,
},
f,
)
# Sanity check
# SC7
# The closed circles in the plot add up to baseline global benefit.
# This is not 114.04 (baseline number), because PG and WS are not part of
# the 6 regions (they are in Oceania).
sum_global_benefit_by_region = sum(global_benefit_by_region.values())
# rel_tol is 1e-6 because previously we round everything to 6 decimals.
assert math.isclose(
sum_global_benefit_by_region, 114.025120, rel_tol=1e-6
), sum_global_benefit_by_region
# SC8
# The open circles and the lots of circles in the left plot add up to
# baseline global benefit.
all_freeloader_benefit = sum(sum(g.values()) for g in zerocost.values())
all_unilateral_benefit = sum(bs_region_combined.values())
actual_benefit = all_freeloader_benefit + all_unilateral_benefit
# This is not 114.04, because PG, WS, and XK are excluded. If they are
# temporarily included, this should be 114.04.
# rel_tol is 1e-6 because previously we round everything to 6 decimals.
assert math.isclose(actual_benefit, 113.913292, rel_tol=1e-6), actual_benefit
# SC9
# Cost
global_cost = 29.03104345418096 # Hardcoded for fast computation.
# Cost for Kosovo. To be excluded.
cost_XK = 0.03241056086650181
actual = sum(cs_region_combined.values())
# rel_tol is 1e-6 because previously we round everything to 6 decimals.
assert math.isclose(actual, global_cost - cost_XK, rel_tol=1e-6)
# For conversion from trillion to billion dollars
def mul_1000(x):
return [i * 1e3 for i in x]
def mul_1000_scalar(x):
return x * 1e3
right = 2.5
fig, axs = plt.subplots(
1,
2,
figsize=(4 * (1 + right) / right, 4),
gridspec_kw={"width_ratios": [1, right]},
)
ax = axs[1]
plt.sca(ax)
# Reset color cycler
ax.set_prop_cycle(None)
# Unilateral benefit
for region, c in cs_region_combined.items():
label = region
plt.plot(
mul_1000_scalar(c),
mul_1000_scalar(bs_region_combined[region]),
linewidth=0,
marker="o",
label=label,
fillstyle="none",
)
benefit = bs_region_combined[region]
break_even_scc = c * util.social_cost_of_carbon / benefit
print(
"self",
region,
"cost",
c,
"benefit",
benefit,
"break-even scc",
break_even_scc,
)
# We plot the global benefit
ax.set_prop_cycle(None)
for region, c in cs_region_combined.items():
plt.plot(
mul_1000_scalar(c),
mul_1000_scalar(global_benefit_by_region[region]),
linewidth=0,
marker="o",
)
print("Freeloader benefit", zerocost)
print("Unilateral benefit", bs_region_combined)
print("Global benefit", global_benefit_by_region)
# 45 degree line
ax.axline([0.1, 0.1], [1, 1])
ax.set_xscale("log")
ax.set_yscale("log")
y_min, y_max = ax.get_ylim()
axis_limit = y_max + 4
plt.xlim(20, axis_limit)
plt.ylim(20, axis_limit)
plt.xlabel("PV country costs (bln dollars)")
fig.legend(
loc="upper center",
bbox_to_anchor=(0.5, -0.005),
ncol=2,
)
plt.tight_layout()
# zerocost
ax = axs[0]
plt.sca(ax)
ax.set_yscale("log")
plt.ylim(20, axis_limit)
transposed = defaultdict(list)
transposed_xs = defaultdict(list)
markersize = 8
for i, (group, content) in enumerate(zerocost.items()):
xs = [i / 5 for _ in range(len(content))]
plt.plot(
xs,
mul_1000(content.values()),
linewidth=0,
marker="o",
label=group,
fillstyle="none",
markersize=markersize,
)
for k, v in content.items():
transposed[k].append(v)
transposed_xs[k].append(i / 5)
# Reset color cycler
ax.set_prop_cycle(None)
for k in zerocost:
plt.plot(
transposed_xs[k],
mul_1000(transposed[k]),
linewidth=0,
marker="o",
label=f"{k} t",
# fillstyle="none",
markersize=markersize * 0.3,
)
# Finishing touch
x_min, x_max = ax.get_xlim()
x_min -= 0.1
x_max *= 1.45
x_mid = (x_min + x_max) / 2
plt.xlim(x_min, x_max)
ax.set_yticklabels([])
plt.xticks([x_mid], [0])
plt.subplots_adjust(wspace=0)
plt.ylabel("PV country benefits (bln dollars)")
util.savefig("country_specific_scatter_part5", tight=True)
def do_country_specific_scc_part6():
top9 = "CN US IN AU RU ID ZA DE KZ".split()
(
_,
iso3166_df_alpha2,
_,
_,
_,
) = util.prepare_from_climate_financing_data()
alpha2_to_full_name = iso3166_df_alpha2["name"].to_dict()
git_branch = util.get_git_branch()
fname = f"cache/country_specific_data_part6_git_{git_branch}.json"
(
cs_combined,
bs_combined,
zerocost,
global_benefit_by_country,
) = common_prepare_cost_benefit_by_country(fname, top9)
# Sanity check
# SC11
# Hardcoded for fast sanity check computation.
# Global deal but benefit only to top9
global_benefit = 114.04380627502013
sum_global_benefit_by_country = sum(global_benefit_by_country.values())
scc_dict = util.read_country_specific_scc_filtered()
unscaled_global_scc = sum(scc_dict.values())
expected = global_benefit * sum(scc_dict[c] for c in top9) / unscaled_global_scc
# This is global action, but benefit only to top9
assert math.isclose(sum_global_benefit_by_country, expected)
# For conversion from trillion to billion dollars
def mul_1000(x):
return [i * 1e3 for i in x]
def mul_1000_scalar(x):
return x * 1e3
right = 2.5
fig, axs = plt.subplots(
1,
2,
figsize=(4 * (1 + right) / right, 4),
gridspec_kw={"width_ratios": [1, right]},
)
ax = axs[1]
plt.sca(ax)
# Reset color cycler
ax.set_prop_cycle(None)
fillstyle = "none"
for group, c in cs_combined.items():
label = alpha2_to_full_name[group]
if label is not None:
label = label.replace("United States of America", "USA")
plt.plot(
mul_1000_scalar(c),
mul_1000_scalar(bs_combined[group]),
linewidth=0,
marker="o",
label=label,
fillstyle=fillstyle,
)
benefit = bs_combined[group]
break_even_scc = c * util.social_cost_of_carbon / benefit
print(
"self",
group,
"cost",
c,
"benefit",
benefit,
"break-even scc",
break_even_scc,
)
print("Unilateral benefit", bs_combined)
print("Global benefit", global_benefit_by_country)
# We plot the global benefit
ax.set_prop_cycle(None)
for group, c in cs_combined.items():
plt.plot(
mul_1000_scalar(c),
mul_1000_scalar(global_benefit_by_country[group]),
linewidth=0,
marker="o",
)
# 45 degree line
ax.axline([0.1, 0.1], [1, 1])
ax.set_xscale("log")
ax.set_yscale("log")
plt.xlabel("PV country costs (bln dollars)")
fig.legend(
loc="upper center",
bbox_to_anchor=(0.5, -0.005),
ncol=3,
)
plt.tight_layout()
y_min_ori, y_max_ori = ax.get_ylim()
# zerocost
ax = axs[0]
plt.sca(ax)
ax.set_yscale("log")
for i, (k, v) in enumerate(zerocost.items()):
plt.plot(
[i / 5 for _ in range(len(v))],
mul_1000(v.values()),
linewidth=0,
marker="o",
label=k,
fillstyle="none",
markersize=4.8,
)
y_min_zero, y_max_zero = ax.get_ylim()
y_min, y_max = min(y_min_ori, y_min_zero), max(y_max_ori, y_max_zero)
plt.ylim(y_min, y_max)
# Finishing touch
x_min, x_max = ax.get_xlim()
x_min -= 0.1
x_max *= 1.45
x_mid = (x_min + x_max) / 2
plt.xlim(x_min, x_max)
ax.set_yticklabels([])
plt.xticks([x_mid], [0])
plt.subplots_adjust(wspace=0)
plt.ylabel("PV country benefits (bln dollars)")
# Rescale original plot to match zerocost range
plt.sca(axs[1])
plt.xlim(y_min, y_max)
plt.ylim(y_min, y_max)
util.savefig("country_specific_scatter_part6", tight=True)
def do_country_specific_scc_part7(
country_doing_action, last_year=None, use_developed_for_zerocost=False
):
"""
use_developed_for_zerocost makes it so that only the developed countries
are shown in the zerocost plot.
"""
(
_,
iso3166_df_alpha2,
_,
_,
_,
) = util.prepare_from_climate_financing_data()
alpha2_to_full_name = iso3166_df_alpha2["name"].to_dict()
# We round to 3 decimal digits instead of 6 because the unit is billion
# dollars.