-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathanalysis_main.py
2018 lines (1833 loc) · 71.4 KB
/
analysis_main.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 copy
import functools
import json
import math
import os
from collections import defaultdict
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import seaborn as sns
from cycler import cycler
import util
from util import (
social_cost_of_carbon,
world_gdp_2023,
)
import with_learning
sns.set_theme(style="ticks")
# TODO these globals could be removed.
global_cost_with_learning = None
MEASURE_GLOBAL_VARS = False
MEASURE_GLOBAL_VARS_SCENARIO = "Net Zero 2050"
# Ensure that plots directory exists
os.makedirs("plots", exist_ok=True)
# Params that can be modified
lcoe_mode = "solar+wind"
# lcoe_mode="solar+wind+gas"
ENABLE_COAL_EXPORT = 0
ENABLE_WORKER = 1
LAST_YEAR = 2050
# The year where the NGFS value is pegged/rescaled to be the same as Masterdata
# global production value.
NGFS_PEG_YEAR = 2024
# SECTOR_INCLUDED = "Coal"
SECTOR_INCLUDED = "Power"
# Possible values: "default", "100year", "5%", "8%", "0%"
RHO_MODE = "default"
# This is used in Bruegel analysis. Might be deleted later.
INVESTMENT_COST_DIVIDER = 1
print("Renewable degradation:", with_learning.ENABLE_RENEWABLE_GRADUAL_DEGRADATION)
print("30 year lifespan:", with_learning.ENABLE_RENEWABLE_30Y_LIFESPAN)
print("Wright's law", with_learning.ENABLE_WRIGHTS_LAW)
print("Residual benefit", with_learning.ENABLE_RESIDUAL_BENEFIT)
print("Sector included", SECTOR_INCLUDED)
print("BATTERY_SHORT", with_learning.ENABLE_BATTERY_SHORT)
print("BATTERY_LONG", with_learning.ENABLE_BATTERY_LONG)
assert SECTOR_INCLUDED in ["Power", "Coal"]
def maybe_round6(do_it, x):
return round(x, 6) if do_it else x
def pandas_divide_or_zero(num, dem):
return (num / dem).replace([np.inf, -np.inf], 0)
ngfs_df = util.read_ngfs()
iso3166_df = util.read_iso3166()
unit_profit_df = pd.read_csv(
"data_private/v5_final_country_region_profit_analysis.csv.zip",
compression="zip",
)
alpha2_to_alpha3 = iso3166_df.set_index("alpha-2")["alpha-3"].to_dict()
_, df_sector = util.read_forward_analytics_data(SECTOR_INCLUDED)
country_sccs = pd.Series(util.read_country_specific_scc_filtered())
def sum_array_of_mixed_objs(x):
out = 0.0
for e in x:
if isinstance(e, float):
out += e
elif isinstance(e, dict):
out += sum(e.values())
else:
out += e.sum()
return out
def divide_array_of_mixed_objs(arr, divider):
out = []
for e in arr:
if isinstance(e, dict):
out.append({k: v / divider for k, v in e.items()})
else:
# float or Pandas Series
out.append(e / divider)
return out
def add_array_of_mixed_objs(x, y):
assert len(x) == len(y)
out = []
for i in range(len(x)):
xi = x[i]
yi = y[i]
if isinstance(xi, pd.Series):
xi = xi.to_dict()
if isinstance(yi, pd.Series):
yi = yi.to_dict()
if isinstance(xi, dict):
if isinstance(yi, float) and yi == 0.0:
out.append(xi.copy())
continue
z = {}
# We need to include keys from both xi and yi, because recently in
# the coal export, there are 100% importer countries that are not
# part of masterdata.
for key in set(xi) | set(yi):
z[key] = xi.get(key, 0) + yi.get(key, 0)
out.append(z)
else:
# float
out.append(xi + yi)
return out
def calculate_table1_info(
do_round,
scenario,
data_set,
time_period,
total_production,
array_of_total_emissions_non_discounted,
array_of_cost_non_discounted_owner_by_subsector,
array_of_cost_discounted_owner_by_subsector, # opportunity cost
array_of_cost_non_discounted_investment,
array_of_cost_discounted_investment,
current_policies=None,
residual_emissions_series=0.0,
residual_production_series=0.0,
final_cost_with_learning=None,
included_countries=None,
):
if INVESTMENT_COST_DIVIDER > 1:
array_of_cost_discounted_investment = divide_array_of_mixed_objs(
array_of_cost_discounted_investment, INVESTMENT_COST_DIVIDER
)
array_of_cost_non_discounted_investment = divide_array_of_mixed_objs(
array_of_cost_non_discounted_investment, INVESTMENT_COST_DIVIDER
)
out_yearly_info = {}
# Workers
subsectors = util.SUBSECTORS
cost_discounted_worker = 0
worker_compensation = None
worker_retraining_cost = None
if ENABLE_WORKER:
import coal_worker
worker_by_subsector = {
subsector: coal_worker.calculate(
"default",
subsector,
LAST_YEAR,
included_countries=included_countries,
return_summed=True,
scenario=scenario,
)
for subsector in subsectors
}
worker_compensation = {
subsector: worker_by_subsector[subsector][0] for subsector in subsectors
}
worker_compensation_sum_trillion = sum(worker_compensation.values()) / 1e3
worker_retraining_cost = {
subsector: worker_by_subsector[subsector][1] for subsector in subsectors
}
worker_rc_sum_trillion = sum(worker_retraining_cost.values()) / 1e3
cost_discounted_worker = (
worker_compensation_sum_trillion + worker_rc_sum_trillion
)
# End of workers
# Sum across subsectors
array_of_cost_non_discounted_owner = functools.reduce(
util.add_array, array_of_cost_non_discounted_owner_by_subsector.values()
)
array_of_cost_discounted_owner = functools.reduce(
util.add_array, array_of_cost_discounted_owner_by_subsector.values()
)
cost_non_discounted_owner = sum_array_of_mixed_objs(
array_of_cost_non_discounted_owner
)
# nansum is needed because PG has nan value for gas
cost_discounted_owner = np.nansum(array_of_cost_discounted_owner)
cost_non_discounted_investment = sum_array_of_mixed_objs(
array_of_cost_non_discounted_investment
)
cost_discounted_investment = sum_array_of_mixed_objs(
array_of_cost_discounted_investment
)
# In GtCO2
residual_emissions = residual_emissions_series.sum() / 1e9
if current_policies is None:
assert data_set == "FA" or "Current Policies" in data_set, data_set
# The groupby-sum aggregates across subsectors
avoided_emissions_by_country: pd.Series = (
sum(array_of_total_emissions_non_discounted).groupby(level=0).sum()
)
avoided_emissions_non_discounted: float = avoided_emissions_by_country.sum()
avoided_emissions_by_subsector = (
sum(array_of_total_emissions_non_discounted).groupby(level=1).sum()
)
total_production_avoided = total_production
out_yearly_info["benefit_non_discounted"] = list(
array_of_total_emissions_non_discounted
)
else:
assert not (data_set == "FA" or "Current Policies" in data_set)
# The groupby-sum aggregates across subsectors
avoided_emissions_by_country: pd.Series = (
(
sum(current_policies["emissions_non_discounted"])
- sum(array_of_total_emissions_non_discounted)
)
.groupby(level=0)
.sum()
)
avoided_emissions_non_discounted: float = avoided_emissions_by_country.sum()
avoided_emissions_by_subsector: pd.Series = (
(
sum(current_policies["emissions_non_discounted"])
- sum(array_of_total_emissions_non_discounted)
)
.groupby(level=1)
.sum()
)
total_production_avoided = (
current_policies["total_production"] - total_production
)
out_yearly_info["benefit_non_discounted"] = util.subtract_array(
current_policies["emissions_non_discounted"],
array_of_total_emissions_non_discounted,
)
# Rescale to include residual emissions
ae_by_subsector_with_residual = (
avoided_emissions_by_subsector
* (1 + residual_emissions / avoided_emissions_by_subsector.sum())
).to_dict()
# We multiply by 1e9 to go from GtCO2 to tCO2
# We divide by 1e12 to get trilllion USD
for i in range(len(out_yearly_info["benefit_non_discounted"])):
out_yearly_info["benefit_non_discounted"][i] *= (
1e9 / 1e12 * social_cost_of_carbon
)
# Division of residual emissions dict by 1e9 converts to GtCO2
out_yearly_info["avoided_emissions_including_residual_emissions"] = (
avoided_emissions_by_country + residual_emissions_series / 1e9
)
# Sanity check
expected = avoided_emissions_non_discounted + residual_emissions
assert math.isclose(
out_yearly_info["avoided_emissions_including_residual_emissions"].sum(),
expected,
)
# Division by 1e3 converts to trillion dollars, because the ae is in GtCO2
out_yearly_info["country_benefit_country_reduction"] = (
(
out_yearly_info["avoided_emissions_including_residual_emissions"]
* country_sccs
/ country_sccs.sum()
* social_cost_of_carbon
/ 1e3
)
.dropna()
.to_dict()
)
out_yearly_info["global_benefit_country_reduction"] = (
out_yearly_info["avoided_emissions_including_residual_emissions"]
* social_cost_of_carbon
/ 1e3
).to_dict()
out_yearly_info["avoided_emissions_including_residual_emissions"] = out_yearly_info[
"avoided_emissions_including_residual_emissions"
].to_dict()
# Summed benefit
benefit_non_discounted = sum_array_of_mixed_objs(
out_yearly_info["benefit_non_discounted"]
)
# Convert to trillion USD
cost_non_discounted_owner /= 1e12
cost_discounted_owner /= 1e12
cost_non_discounted_investment /= 1e12
cost_discounted_investment /= 1e12
array_of_cost_non_discounted_owner_trillions = divide_array_of_mixed_objs(
array_of_cost_non_discounted_owner, 1e12
)
array_of_cost_discounted_owner_trillions = divide_array_of_mixed_objs(
array_of_cost_discounted_owner, 1e12
)
array_of_cost_non_discounted_investment_trillions = divide_array_of_mixed_objs(
array_of_cost_non_discounted_investment, 1e12
)
array_of_cost_discounted_investment_trillions = divide_array_of_mixed_objs(
array_of_cost_discounted_investment, 1e12
)
# In trillion dollars
residual_benefit = residual_emissions * social_cost_of_carbon / 1e3
# Convert to Gigatonnes of coal
residual_production = residual_production_series.sum() / 1e9
# rho is the same everywhere
rho = util.calculate_rho(util.beta, rho_mode=RHO_MODE)
def discount_the_array(arr):
out = []
for i, e in enumerate(arr):
discount = util.calculate_discount(rho, i)
if len(e) == 0:
out.append(0.0)
else:
out.append({k: v * discount for k, v in e.items()})
return out
out_yearly_info["opportunity_cost_non_discounted"] = (
array_of_cost_non_discounted_owner_trillions
)
out_yearly_info["investment_cost_non_discounted"] = (
array_of_cost_non_discounted_investment_trillions
)
# Division by 1e12 converts to trillion
out_yearly_info["cost_battery_short_non_discounted"] = divide_array_of_mixed_objs(
final_cost_with_learning.cost_non_discounted_battery_short_by_country, 1e12
)
out_yearly_info["cost_battery_long_non_discounted"] = divide_array_of_mixed_objs(
final_cost_with_learning.cost_non_discounted_battery_long_by_country, 1e12
)
out_yearly_info["cost_battery_pe_non_discounted"] = divide_array_of_mixed_objs(
final_cost_with_learning.cost_non_discounted_battery_pe_by_country, 1e12
)
out_yearly_info["cost_battery_grid_non_discounted"] = divide_array_of_mixed_objs(
final_cost_with_learning.cost_non_discounted_battery_grid_by_country, 1e12
)
out_yearly_info["opportunity_cost_owner"] = array_of_cost_discounted_owner_trillions
out_yearly_info["investment_cost"] = array_of_cost_discounted_investment_trillions
out_yearly_info["cost_battery_short"] = discount_the_array(
divide_array_of_mixed_objs(
final_cost_with_learning.cost_non_discounted_battery_short_by_country,
1e12,
)
)
out_yearly_info["cost_battery_long"] = discount_the_array(
divide_array_of_mixed_objs(
final_cost_with_learning.cost_non_discounted_battery_long_by_country,
1e12,
)
)
out_yearly_info["cost_battery_pe"] = discount_the_array(
divide_array_of_mixed_objs(
final_cost_with_learning.cost_non_discounted_battery_pe_by_country, 1e12
)
)
out_yearly_info["cost_battery_grid"] = discount_the_array(
divide_array_of_mixed_objs(
final_cost_with_learning.cost_non_discounted_battery_grid_by_country,
1e12,
)
)
out_yearly_info["cost"] = add_array_of_mixed_objs(
out_yearly_info["opportunity_cost_owner"], out_yearly_info["investment_cost"]
)
out_yearly_info["residual_benefit"] = {
k: v * social_cost_of_carbon / 1e12
for k, v in residual_emissions_series.items()
}
# Costs of avoiding coal emissions
assert cost_discounted_investment >= 0
cost_discounted = (
cost_discounted_owner + cost_discounted_investment + cost_discounted_worker
)
# Equation 1 in the paper
net_benefit = benefit_non_discounted - cost_discounted
last_year = int(time_period.split("-")[1])
arbitrage_period = last_year - NGFS_PEG_YEAR
owner_dict = {
# nansum is needed because PG has nan value for gas
f"OC owner {subsector}": np.nansum(
array_of_cost_discounted_owner_by_subsector[subsector]
)
/ 1e12
for subsector in subsectors
}
worker_dict = {}
if ENABLE_WORKER:
for subsector in subsectors:
# Trillion
worker_dict[f"OC workers lost wages {subsector}"] = (
worker_compensation[subsector] / 1e3
)
worker_dict[f"OC workers retraining cost {subsector}"] = (
worker_retraining_cost[subsector] / 1e3
)
ic_battery_short = sum_array_of_mixed_objs(out_yearly_info["cost_battery_short"])
ic_battery_long = sum_array_of_mixed_objs(out_yearly_info["cost_battery_long"])
ic_battery_pe = sum_array_of_mixed_objs(out_yearly_info["cost_battery_pe"])
ic_battery_grid = sum_array_of_mixed_objs(out_yearly_info["cost_battery_grid"])
ic_battery = ic_battery_short + ic_battery_long + ic_battery_pe + ic_battery_grid
data = {
"Using production projections of data set": data_set,
"Time Period of Carbon Arbitrage": time_period,
"Total coal production avoided (Giga tonnes)": total_production_avoided,
"Total coal production avoided including residual (Giga tonnes)": total_production_avoided
+ residual_production,
"Electricity generation avoided including residual (PWh)": (
# Multiplication by 1e9 converts from Giga tonnes to tonnes
# Division by seconds in 1 hr converts from GJ to GWh
# Division by 1e6 converts from GWh to PWh
util.coal2GJ((total_production_avoided + residual_production) * 1e9)
/ util.seconds_in_1hour
/ 1e6
),
"Total emissions avoided (GtCO2)": avoided_emissions_non_discounted,
"Total emissions avoided including residual (GtCO2)": avoided_emissions_non_discounted
+ residual_emissions,
**{f"AE+residual {k}": v for k, v in ae_by_subsector_with_residual.items()},
"Costs of avoiding coal emissions (in trillion dollars)": cost_discounted,
"Opportunity costs (in trillion dollars)": cost_discounted_owner
+ cost_discounted_worker,
"OC owner (in trillion dollars)": cost_discounted_owner,
**owner_dict,
**worker_dict,
"investment_cost_battery_short_trillion": ic_battery_short,
"investment_cost_battery_long_trillion": ic_battery_long,
"investment_cost_battery_pe_trillion": ic_battery_pe,
"investment_cost_battery_grid_trillion": ic_battery_grid,
"Investment costs in renewable energy": cost_discounted_investment - ic_battery,
"Investment costs (in trillion dollars)": cost_discounted_investment,
"Carbon arbitrage opportunity (in trillion dollars)": net_benefit,
"Carbon arbitrage opportunity relative to world GDP (%)": net_benefit
* 100
/ (world_gdp_2023 * arbitrage_period),
"Carbon arbitrage residual benefit (in trillion dollars)": residual_benefit,
"Carbon arbitrage including residual benefit (in trillion dollars)": net_benefit
+ residual_benefit,
"Carbon arbitrage including residual benefit relative to world GDP (%)": (
net_benefit + residual_benefit
)
* 100
/ (world_gdp_2023 * arbitrage_period),
"Benefits of avoiding coal emissions (in trillion dollars)": benefit_non_discounted,
"Benefits of avoiding coal emissions including residual benefit (in trillion dollars)": benefit_non_discounted
+ residual_benefit,
"country_benefit_country_reduction": sum(
out_yearly_info["country_benefit_country_reduction"].values()
),
}
for k, v in data.items():
if k in [
"Using production projections of data set",
"Time Period of Carbon Arbitrage",
]:
continue
data[k] = maybe_round6(do_round, v)
# TODO included worker
# out_yearly_info = None
return data, out_yearly_info
def calculate_weighted_emissions_factor_by_country_peg_year(_df_nonpower):
if not with_learning.ENABLE_RESIDUAL_BENEFIT:
return None
colname = "activity"
grouped_np = _df_nonpower.groupby("asset_country")
# In tce
production_pegyear_np = grouped_np[colname].sum()
production_pegyear = production_pegyear_np
# Convert million tonnes of CO2 to tCO2
emissions_pegyear_np = grouped_np[util.EMISSIONS_COLNAME].sum() * 1e6
emissions_pegyear = emissions_pegyear_np
ef = emissions_pegyear / production_pegyear
# There are some countries with 0 production, and so it is division by
# zero. We set them to 0.0 for now
ef = ef.fillna(0.0)
return ef
def get_opportunity_cost_owner(
rho,
delta_profit,
scenario,
last_year,
):
# Calculate cost
out_non_discounted = delta_profit
out_discounted = {
subsector: util.discount_array(out_non_discounted[subsector], rho)
for subsector in util.SUBSECTORS
}
return (
out_non_discounted,
out_discounted,
)
def get_cost_including_ngfs_renewable(
_df_nonpower,
rho,
DeltaP,
weighted_emissions_factor_by_country_peg_year,
scenario,
last_year,
_cost_new_method,
):
# We copy _cost_new_method because it is going to be reused for
# different scenario and year range.
temp_cost_with_learning = copy.deepcopy(_cost_new_method)
for i, dp in enumerate(DeltaP):
discount = util.calculate_discount(rho, i)
temp_cost_with_learning.calculate_investment_cost(
dp, NGFS_PEG_YEAR + i, discount
)
out_non_discounted = list(temp_cost_with_learning.cost_non_discounted)
out_discounted = list(temp_cost_with_learning.cost_discounted)
residual_benefits_years_offset = with_learning.RENEWABLE_LIFESPAN
(
residual_emissions,
residual_production,
) = temp_cost_with_learning.calculate_residual(
last_year + 1,
last_year + residual_benefits_years_offset,
weighted_emissions_factor_by_country_peg_year,
)
if MEASURE_GLOBAL_VARS and scenario == MEASURE_GLOBAL_VARS_SCENARIO:
global global_cost_with_learning
global_cost_with_learning = temp_cost_with_learning
return (
out_non_discounted,
out_discounted,
residual_emissions,
residual_production,
temp_cost_with_learning,
)
def generate_table1_output(
rho,
do_round,
_df_nonpower,
included_countries=None,
):
out = {}
out_yearly = {}
# Production
# Giga tonnes of coal
total_production_fa = util.get_production_by_country(df_sector, SECTOR_INCLUDED)
# Emissions
emissions_fa = util.get_emissions_by_country(df_sector)
current_policies = None
production_2019 = (
_df_nonpower.groupby("asset_country")._2019.sum()
if ENABLE_COAL_EXPORT
else None
)
weighted_emissions_factor_by_country_peg_year = (
calculate_weighted_emissions_factor_by_country_peg_year(_df_nonpower)
)
production_with_ngfs_projection_CPS = None
profit_ngfs_projection_CPS = None
for scenario in ["Current Policies", "Net Zero 2050"]:
# NGFS_PEG_YEAR
cost_new_method = with_learning.InvestmentCostWithLearning()
last_year = LAST_YEAR
# Giga tonnes of coal
(
production_with_ngfs_projection,
gigatonnes_coal_production,
profit_ngfs_projection,
) = util.calculate_ngfs_projection(
"production",
total_production_fa,
ngfs_df,
SECTOR_INCLUDED,
scenario,
NGFS_PEG_YEAR,
last_year,
alpha2_to_alpha3,
unit_profit_df=unit_profit_df,
)
emissions_with_ngfs_projection, _, _ = util.calculate_ngfs_projection(
"emissions",
emissions_fa,
ngfs_df,
SECTOR_INCLUDED,
scenario,
NGFS_PEG_YEAR,
last_year,
alpha2_to_alpha3,
)
if scenario == "Current Policies":
# To prepare for the s2-s1 for NZ2050
production_with_ngfs_projection_CPS = production_with_ngfs_projection.copy()
profit_ngfs_projection_CPS = profit_ngfs_projection.copy()
scenario_formatted = f"FA + {scenario} Scenario"
# NGFS_PEG_YEAR-last_year
array_of_total_emissions_non_discounted = emissions_with_ngfs_projection
if scenario == "Net Zero 2050":
DeltaP = util.subtract_array(
production_with_ngfs_projection_CPS, production_with_ngfs_projection
)
delta_profit = {
subsector: util.subtract_array(
profit_ngfs_projection_CPS[subsector],
profit_ngfs_projection[subsector],
)
for subsector in util.SUBSECTORS
}
else:
DeltaP = production_with_ngfs_projection_CPS
delta_profit = profit_ngfs_projection_CPS
# Convert Giga tonnes of coal to GJ
DeltaP = util.coal2GJ([dp * 1e9 for dp in DeltaP])
(
cost_non_discounted_owner,
cost_discounted_owner,
) = get_opportunity_cost_owner(
rho,
delta_profit,
scenario,
last_year,
)
(
cost_non_discounted_investment,
cost_discounted_investment,
residual_emissions,
residual_production,
final_cost_with_learning,
) = get_cost_including_ngfs_renewable(
_df_nonpower,
rho,
DeltaP,
weighted_emissions_factor_by_country_peg_year,
scenario,
last_year,
cost_new_method,
)
if ENABLE_COAL_EXPORT:
from coal_export.common import modify_array_based_on_coal_export
modify_array_based_on_coal_export(
cost_non_discounted_investment, production_2019
)
modify_array_based_on_coal_export(
cost_discounted_investment, production_2019
)
if included_countries is not None:
def _filter(e, is_multiindex=False):
if isinstance(e, dict):
e = pd.Series(e)
if is_multiindex:
return e[e.index.get_level_values(0).isin(included_countries)]
return e[e.index.isin(included_countries)]
def _filter_arr(arr, is_multiindex=False):
return [_filter(e, is_multiindex) for e in arr]
gigatonnes_coal_production = _filter(
sum(production_with_ngfs_projection)
).sum()
array_of_total_emissions_non_discounted = _filter_arr(
array_of_total_emissions_non_discounted, is_multiindex=True
)
cost_non_discounted_owner = {
subsector: _filter_arr(cost_non_discounted_owner[subsector])
for subsector in util.SUBSECTORS
}
cost_discounted_owner = {
subsector: _filter_arr(cost_discounted_owner[subsector])
for subsector in util.SUBSECTORS
}
cost_non_discounted_investment = _filter_arr(cost_non_discounted_investment)
cost_discounted_investment = _filter_arr(cost_discounted_investment)
residual_emissions = _filter(residual_emissions)
residual_production = _filter(residual_production)
final_cost_with_learning.cost_non_discounted_battery_short_by_country = _filter_arr(
final_cost_with_learning.cost_non_discounted_battery_short_by_country
)
final_cost_with_learning.cost_non_discounted_battery_long_by_country = (
_filter_arr(
final_cost_with_learning.cost_non_discounted_battery_long_by_country
)
)
final_cost_with_learning.cost_non_discounted_battery_pe_by_country = (
_filter_arr(
final_cost_with_learning.cost_non_discounted_battery_pe_by_country
)
)
final_cost_with_learning.cost_non_discounted_battery_grid_by_country = (
_filter_arr(
final_cost_with_learning.cost_non_discounted_battery_grid_by_country
)
)
text = f"{NGFS_PEG_YEAR}-{last_year} {scenario_formatted}"
table1_info, yearly_info = calculate_table1_info(
do_round,
scenario,
scenario_formatted,
f"{NGFS_PEG_YEAR}-{last_year}",
gigatonnes_coal_production,
copy.deepcopy(array_of_total_emissions_non_discounted),
cost_non_discounted_owner,
cost_discounted_owner,
cost_non_discounted_investment,
cost_discounted_investment,
current_policies=current_policies,
residual_emissions_series=residual_emissions,
residual_production_series=residual_production,
final_cost_with_learning=final_cost_with_learning,
included_countries=included_countries,
)
out[text] = table1_info
out_yearly[text] = yearly_info
if scenario == "Current Policies":
current_policies = {
"emissions_non_discounted": copy.deepcopy(
array_of_total_emissions_non_discounted
),
"total_production": gigatonnes_coal_production,
}
out = pd.DataFrame(out)
return out, out_yearly
def floatify_array_of_mixed_objs(x):
out = []
for e in x:
if isinstance(e, float):
out.append(e)
elif isinstance(e, dict):
out.append(sum(e.values()))
else:
out.append(e.sum())
return out
def do_plot_yearly_table1(yearly_both):
full_years_2100 = range(NGFS_PEG_YEAR, 2100 + 1)
full_years_midyear = range(NGFS_PEG_YEAR, LAST_YEAR + 1)
for condition, value in yearly_both.items():
print(condition)
plt.figure()
x = (
full_years_2100
if f"{NGFS_PEG_YEAR}-2100" in condition
else full_years_midyear
)
plt.plot(x, floatify_array_of_mixed_objs(value["cost"]), label="Costs")
plt.plot(
x,
floatify_array_of_mixed_objs(value["investment_cost"]),
label="Investment costs",
)
plt.plot(
x,
floatify_array_of_mixed_objs(value["opportunity_cost"]),
label="Opportunity costs",
)
plt.plot(
x,
floatify_array_of_mixed_objs(value["benefit_non_discounted"]),
label="Benefit",
)
plt.xlabel("Time")
plt.ylabel("Trillion dollars")
plt.legend()
plt.title(condition)
plt.axvline(NGFS_PEG_YEAR)
util.savefig(f"yearly_{condition}")
plt.close()
def run_table1(
to_csv=False,
do_round=False,
plot_yearly=False,
return_yearly=False,
included_countries=None,
):
# rho is the same everywhere
rho = util.calculate_rho(util.beta, rho_mode=RHO_MODE)
out, yearly = generate_table1_output(
rho,
do_round,
df_sector,
included_countries=included_countries,
)
out_dict = out.T.to_dict()
both_dict = {}
for key in out_dict.keys():
if key in [
"Using production projections of data set",
"Time Period of Carbon Arbitrage",
]:
both_dict[key] = out_dict[key]
else:
both_dict[key] = maybe_round6(
do_round,
pd.Series(out_dict[key]),
).to_dict()
if to_csv:
uid = util.get_unique_id(include_date=False)
ext = ""
if with_learning.ENABLE_RENEWABLE_GRADUAL_DEGRADATION:
ext += "_degrade"
if with_learning.ENABLE_RENEWABLE_30Y_LIFESPAN:
ext += "_30Y"
if with_learning.ENABLE_WRIGHTS_LAW:
ext += "_wright"
fname = f"plots/table1_{uid}{ext}_{social_cost_of_carbon}_{LAST_YEAR}.csv"
pd.DataFrame(both_dict).T.to_csv(fname)
if plot_yearly:
do_plot_yearly_table1(yearly)
if return_yearly:
return yearly
return both_dict
def run_table2(name="", included_countries=None):
global social_cost_of_carbon, LAST_YEAR
result = {}
sccs = [
util.social_cost_of_carbon_imf,
util.scc_biden_administration,
util.scc_bilal,
]
scc_default = util.social_cost_of_carbon_imf
last_years = [2035, 2050]
for last_year in last_years:
util.social_cost_of_carbon = scc_default
social_cost_of_carbon = scc_default
LAST_YEAR = last_year
result[last_year] = run_table1(included_countries=included_countries)
gc_benefit_old_name = "Benefits of avoiding coal emissions including residual benefit (in trillion dollars)"
subsectors = ["Coal", "Oil", "Gas"]
mapper_worker = {}
for subsector in subsectors:
val = f"OC owner {subsector}"
mapper_worker[val] = val
val = f"OC workers lost wages {subsector}"
mapper_worker[val] = val
val = f"OC workers retraining cost {subsector}"
mapper_worker[val] = val
# Rename the key
mapper = {
"Time Period": "Time Period of Carbon Arbitrage",
"Avoided fossil fuel electricity generation (PWh)": "Electricity generation avoided including residual (PWh)",
"Avoided emissions (GtCO2e)": "Total emissions avoided including residual (GtCO2)",
**{f"Avoided emissions {s}": f"AE+residual {s}" for s in util.SUBSECTORS},
"Costs of power sector decarbonization (in trillion dollars)": "Costs of avoiding coal emissions (in trillion dollars)",
"Opportunity costs (in trillion dollars)": "Opportunity costs (in trillion dollars)",
"OC owner (in trillion dollars)": "OC owner (in trillion dollars)",
**mapper_worker,
"Investment costs (in trillion dollars)": "Investment costs (in trillion dollars)",
"Investment costs in renewable energy": "Investment costs in renewable energy",
"Investment costs short-term storage": "investment_cost_battery_short_trillion",
"Investment costs long-term storage": "investment_cost_battery_long_trillion",
"Investment costs renewables to power electrolyzers": "investment_cost_battery_pe_trillion",
"Investment costs grid extension": "investment_cost_battery_grid_trillion",
}
def _s(y):
return f"2024-{y} FA + Net Zero 2050 Scenario"
table = defaultdict(list)
for k, v in mapper.items():
for y in last_years:
try:
table[k].append(result[y][v][_s(y)])
except KeyError:
print("Missing either of", k, y, v)
continue
if len(table[k]) == 0:
# Some countries may have missing at least one of coal/oil/gas
# e.g. Viet Nam has 0 oil
del table[k]
gdp_2023 = world_gdp_2023
if included_countries is not None:
gdp_marketcap_dict = util.read_json(util.gdp_marketcap_path)
# actual = np.nansum(list(gdp_marketcap_dict.values()))
# actual's value is 103.74, different from worldbank's own data of 105.44.
# Both come from worldbank.
# Convert to trillion dollars
gdp_2023 = (
np.nansum(
[
gdp
for country, gdp in gdp_marketcap_dict.items()
if country in included_countries
]
)
/ 1e12
)
for i, y in enumerate(last_years):
table["Costs per avoided tCO2e ($/tCO2e)"].append(
table["Costs of power sector decarbonization (in trillion dollars)"][i]
* 1e12
/ (table["Avoided emissions (GtCO2e)"][i] * 1e9)
)
arbitrage_period = y - NGFS_PEG_YEAR
for scc in sccs:
scc_scale = scc / scc_default
table[f"scc {scc} GC benefit (in trillion dollars)"].append(
result[y][gc_benefit_old_name][_s(y)] * scc_scale
)
table[f"scc {scc} CC benefit (in trillion dollars)"].append(
result[y]["country_benefit_country_reduction"][_s(y)] * scc_scale
)
table[f"scc {scc} GC benefit per avoided tCO2e ($/tCO2e)"].append(
result[y][gc_benefit_old_name][_s(y)]
* scc_scale
* 1e12
/ (table["Avoided emissions (GtCO2e)"][i] * 1e9)
)
table[f"scc {scc} CC benefit per avoided tCO2e ($/tCO2e)"].append(
result[y]["country_benefit_country_reduction"][_s(y)]
* scc_scale
* 1e12
/ (table["Avoided emissions (GtCO2e)"][i] * 1e9)
)
table[f"scc {scc} GC net benefit (in trillion dollars)"].append(
table[f"scc {scc} GC benefit (in trillion dollars)"][i]
- table["Costs of power sector decarbonization (in trillion dollars)"][
i
]
)
table[f"scc {scc} CC net benefit (in trillion dollars)"].append(
table[f"scc {scc} CC benefit (in trillion dollars)"][i]
- table["Costs of power sector decarbonization (in trillion dollars)"][
i
]
)
table[f"scc {scc} CC Net benefit relative to GDP (%)"].append(
table[f"scc {scc} CC net benefit (in trillion dollars)"][i]
* 100
/ (gdp_2023 * arbitrage_period)
)
table[f"scc {scc} GC Net benefit per avoided tCO2e ($/tCO2e)"].append(
table[f"scc {scc} GC net benefit (in trillion dollars)"][i]
* 1e12
/ (table["Avoided emissions (GtCO2e)"][i] * 1e9)
)