-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfunctions.R
1655 lines (1333 loc) · 70.3 KB
/
functions.R
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
library(dplyr)
library(tidyr)
# If ratio = 1 and input is not a primary input,
# replace sectors with input name with downstream sector name and type,
# then delete downstream row
downstream_replacer <- function(df, primary_sectors){
i <- 1
while (i <= dim(df)[1]){
if (df$ratio[i] == 1 && !(df$input[i] %in% primary_sectors)){
df <- df %>%
mutate(type = if_else(sector == df$input[i],
df$type[i],
type),
sector = if_else(sector == df$input[i],
df$sector[i],
sector)) %>%
filter(input != df$input[i])
} else {
i <- i + 1
}
}
return(df %>% select(-scenario, -region, -year))
}
# If both ratios = 1
# replace inputs with sector name with upstream input name,
# then delete upstream row - also apportions upstream amount
upstream_replacer <- function(df){
i <- 1
while (i <= dim(df)[1]){
if (df$ratio[i] == 1 && df$ratio2[i] == 1 ){
val_to_divide <- filter(df, input == df$input[i])$value
df <- df %>%
mutate(value = if_else(input == df$sector[i],
val_to_divide * ratio,
value),
input = if_else(input == df$sector[i],
df$input[i],
input)) %>%
filter(sector != df$sector[i])
} else {
i <- i + 1
}
}
return(df %>% select(-scenario, -region, -year))
}
# use ratios to apportion passthru sectors to transformation sectors
passthru_remove <- function(df, remaining_passthru = NULL){
if (is.null(remaining_passthru)){
remaining_passthru <- (df %>% filter(type == "passthru") %>% distinct(sector))$sector
}
for (passthru in remaining_passthru){
new_sectors <- df %>%
filter(input == passthru) %>%
select(scenario, region, sector, year, type, ratio)
to_expand <- df %>%
filter(sector == passthru) %>%
select(-sector, -ratio, -ratio2, -type) %>%
right_join(new_sectors, by = c("scenario", "region", "year") ) %>%
mutate(value = value * ratio)
df <- df %>%
filter(input != passthru,
sector != passthru) %>%
bind_rows(to_expand)
}
return(df %>% select(-scenario, -region, -year))
}
# remove transformation sectors from inputs of other transformations
transform_distributer <- function(df, transform_sectors){
for (transform in transform_sectors){
inputs <- (df %>% filter(sector == transform))$input
inputs_to_expand <- dplyr::intersect(inputs, transform_sectors)
for (inp in inputs_to_expand){
sector_input <- df %>%
filter(sector == transform,
input == inp)
input_df <- df %>%
filter(sector == inp,
!(input %in% transform_sectors))
total <- sum(df$value)
input_df <- input_df %>%
mutate(ratio = value / total) %>%
select(scenario, region, input, year, ratio)
to_expand <- sector_input %>%
select(scenario, region, sector, year, type, value) %>%
right_join(input_df, by = c("scenario", "region", "year") ) %>%
mutate(value = value * ratio)
####
# Need to subtract any resource that goes into other transformation from original transform sector
###
subtract_from_upstream <- df %>%
filter(sector == inp,
!(input %in% transform_sectors)) %>%
left_join(to_expand, by = c("scenario", "region", "input", "year")) %>%
mutate(value = value.x - value.y) %>%
select(scenario, region, year, input, sector = sector.x, type = type.x, value)
df <- df %>%
filter(!(input == inp & sector == transform)) %>%
bind_rows(to_expand) %>%
filter(!(sector == inp & !(input %in% transform_sectors))) %>%
bind_rows(subtract_from_upstream) %>%
group_by(scenario, region, input, sector, type, year) %>%
summarise(value = sum(value)) %>%
ungroup()
}
}
return(df %>% select(-scenario, -region, -year))
}
# MAIN FUNCTION for fuel tracing
fuel_distributor <- function(prj){
################### Data Tidying ###################
input <- rgcam::getQuery(prj, "inputs by subsector") %>%
# Remove industry and chemical, as they simply aggregate more detailed sectors
filter(sector != "chemical", sector != "industry")
sectors <- input %>%
filter(Units == "EJ") %>%
# Rewrite transportation subsector to sector
dplyr::mutate(sector = if_else(grepl("trn_", sector), subsector, sector))
# Primary sectors are inputs, but don't have any inputs
primary_sectors <- c(dplyr::setdiff(sectors$input, sectors$sector),
"traded unconventional oil",
"total biomass")
# But we only care about inputs that have associated emissions:
# c("coal", "natural gas", "crude oil", "traditional biomass", "biomass", "unconventional oil")
primary_remove <- setdiff(primary_sectors,
c("coal", "natural gas", "crude oil", "traditional biomass",
"total biomass", "traded unconventional oil"))
# Enduse sectors have inputs, but don't act as inputs
enduse_sectors <- dplyr::setdiff(sectors$sector, sectors$input)
transformation_sectors <- c("delivered biomass", "delivered coal", "delivered gas",
"elect_td_bld", "elect_td_ind", "elect_td_trn",
"H2 enduse", "refined liquids enduse", "refined liquids industrial",
"wholesale gas", "traditional biomass", "district heat")
# All other sectors are pass-thru sectors
passthru_sectors <- dplyr::setdiff(sectors$sector,
c(primary_sectors, enduse_sectors, transformation_sectors))
sector_types <- bind_rows(tibble(sector = primary_sectors, type = "primary"),
tibble(sector = transformation_sectors, type = "transformation"),
tibble(sector = enduse_sectors, type = "enduse"),
tibble(sector = passthru_sectors, type = "passthru"))
# group inputs by sector (subsector no longer relevant)
input_tracing <- sectors %>%
group_by(scenario, region, input, sector, year) %>%
summarise(value = sum(value)) %>%
ungroup() %>%
# Add in sector types
left_join(sector_types, by = "sector")
print("Data ready for distribution.")
################### Input Distributing ###################
# First want to remove unnecessary primary inputs and sectors that depend only on them
#
primary_remove_df <- input_tracing %>%
filter(input %in% primary_remove)
# single_use_sectors <- input_tracing %>%
# filter(sector %in% primary_remove_df$sector) %>%
# group_by(scenario, region, sector, year) %>%
# count() %>%
# filter(n == 1,
# sector != "regional biomass") %>%
# ungroup()
single_use_sectors <- input_tracing %>%
filter(sector %in% primary_remove_df$sector) %>%
group_by(scenario, region, sector, year) %>%
add_count() %>%
filter(n == 1,
sector != "regional biomass") %>%
ungroup() %>%
semi_join(primary_remove_df, by = c("scenario", "region", "input", "sector", "year"))
# Remove unnecessary sectors
global_inputs <- input_tracing %>%
filter(!(input %in% primary_remove)) %>%
anti_join(single_use_sectors, by = c("scenario", "region", "sector", "year"))
# Next, want to get rid of passthru sectors that only have 1 input
#
# Get ratio of sector in each input
in_ratio <- global_inputs %>%
group_by(scenario, region, input, year) %>%
mutate(ratio = value / sum(value)) %>%
ungroup() %>%
# Remove nans - these sectors no longer needed
na.omit()
# If ratio = 1 and input is not a primary input,
# replace sectors with input name with downstream sector name and type,
# then delete downstream row
in_replace_downstream <- in_ratio %>%
group_by(scenario, region, year) %>%
group_modify(~downstream_replacer(., primary_sectors), keep=TRUE) %>%
ungroup()
print("Downstream passthru sectors replaced")
# Sum to combine a few weird sectors (2 regional biomasses bc of trading)
in_replace_downstream <- in_replace_downstream %>%
group_by(scenario, region, input, sector, year, type) %>%
summarise(value = sum(value),
ratio = sum(ratio)) %>%
ungroup()
# Get ratio of inputs in each sector
in_replace_downstream <- in_replace_downstream %>%
group_by(scenario, region, sector, year) %>%
mutate(ratio2 = value / sum(value)) %>%
ungroup() %>%
# Remove nans - these sectors no longer matter
na.omit()
# If both ratios = 1
# replace inputs with sector name with upstream input name,
# then delete upstream row
in_replace_upstream <- in_replace_downstream %>%
group_by(scenario, region, year) %>%
group_modify(~upstream_replacer(.), keep=TRUE) %>%
ungroup()
print("Upstream passthru sectors replaced")
# For each pass thru sector left, need to use ratios to apportion to transformation sectors
#
in_passthru_remove <- in_replace_upstream %>%
group_by(scenario, region, year) %>%
group_modify(~passthru_remove(.), keep=TRUE) %>%
ungroup()
print("Remaining passthru sectors replaced")
# need to redo ratio of sector in each input
in_passthru_remove <- in_passthru_remove %>%
group_by(scenario, region, input, year) %>%
mutate(ratio = value / sum(value)) %>%
ungroup()
# Getting rid of 1975 bc electricity is different
in_passthru_remove <- in_passthru_remove %>%
filter(year >= 1990)
# Repeating fuel distribution with delivered biomass and coal
in_passthru_remove <- in_passthru_remove %>%
group_by(scenario, region, year) %>%
group_modify(~passthru_remove(., c( "delivered biomass", "delivered coal")), keep=TRUE) %>%
ungroup()
print("Delivered coal & biomass replaced")
# Old years (<= 2010) need to rename regional biomass to biomass
in_passthru_remove <- in_passthru_remove %>%
mutate(input = if_else(input == "regional biomass", "total biomass", input))
# sum things up
in_passthru_remove <- in_passthru_remove %>%
group_by(scenario, region, input, sector, type, year) %>%
summarise(value = sum(value)) %>%
ungroup()
# Now need to remove transformation sectors from inputs of other transformations
# ASSUMING THAT REFINED LIQUIDS ARE UPSTREAM OF ELECTRICITY
transform_sectors <- c("elect_td_bld", "elect_td_ind", "elect_td_trn",
"H2 enduse", "district heat", "refined liquids enduse", "refined liquids industrial",
"wholesale gas", "delivered gas")
in_primary <- in_passthru_remove %>%
group_by(scenario, region, year) %>%
group_modify(~transform_distributer(., transform_sectors), keep=TRUE) %>%
ungroup()
print("Transformation sectors removed as inputs to other transformations")
# Now need to separate transformation from enduse
# Apportion primary -> transformation -> enduse
transform_df <- in_primary %>%
filter(type == "transformation")
# Get ratio of enduse in each transformation sector
enduse_df <- in_primary %>%
filter(type == "enduse") %>%
rename(enduse = sector) %>%
group_by(scenario, region, input, year) %>%
mutate(ratio_enduse_in_input = value / sum(value)) %>%
ungroup()
# Get ratio of input in each transformation sector
transform_df <- transform_df %>%
group_by(scenario, region, sector, year) %>%
mutate(ratio_primary_in_trans = value / sum(value)) %>%
ungroup() %>%
rename(transformation = sector, primary = input) %>%
select(-type)
# Add in natural gas for unconventional oil production
gas_in_unconventional_oil <- in_ratio %>%
filter(sector == "unconventional oil production",
input == "regional natural gas") %>%
mutate(input = "natural gas",
enduse = sector) %>%
select(scenario, region, year, primary = input, transformation = sector, enduse, value)
# Expand all transformation inputs in enduse_df to get primary inputs
final_df <- enduse_df %>%
full_join(transform_df, by = c("scenario", "region", "year", "input" = "transformation")) %>%
mutate(primary = if_else(is.na(primary), input, primary),
value = if_else(is.na(value.y), value.x, value.y * ratio_enduse_in_input),
input = if_else(input==primary, enduse,input)) %>%
select(scenario, region, year, primary, transformation = input, enduse, value) %>%
bind_rows(gas_in_unconventional_oil)
# Group electricity, refining, gas processing
final_df <- final_df %>%
mutate(transformation = if_else(transformation %in% c("elect_td_bld", "elect_td_ind","elect_td_trn"),
"electricity", transformation),
transformation = if_else(transformation %in% c("refined liquids enduse", "refined liquids industrial"),
"refining", transformation),
transformation = if_else(transformation %in% c("delivered gas", "wholesale gas"),
"gas processing", transformation)
) %>%
group_by(scenario, region, year, primary, transformation, enduse) %>%
summarise(value = sum(value)) %>%
ungroup()
final_df <- final_df %>%
# Get ratio of enduse in primary
group_by(scenario, region, year, primary) %>%
mutate(ratio_enduse_in_primary = value / sum(value)) %>%
# Get ratio of enduse in transformation
group_by(scenario, region, year, transformation) %>%
mutate(ratio_enduse_in_transformation = value / sum(value)) %>%
ungroup()
print("Final distributions calculated.")
################### Checking Totals ###################
# NOW NEED TO DO A CHECK TO MAKE SURE MATH ADDS UP FOR EACH FUEL/REGION
original_totals <- in_ratio %>%
filter(year >= 1990) %>%
filter(input %in% c("coal", "natural gas", "crude oil", "regional biomass", "traded unconventional oil")) %>%
group_by(scenario, region, year, input) %>%
summarise(value = sum(value)) %>%
ungroup() %>%
mutate(input = if_else(input == "regional biomass", "total biomass", input))
new_totals <- final_df %>%
filter(primary %in% c("coal", "natural gas", "crude oil", "total biomass", "traded unconventional oil")) %>%
group_by(scenario, region, year, primary) %>%
summarise(value = sum(value)) %>%
ungroup() %>%
rename(input = primary)
comp <- original_totals %>%
left_join(new_totals, by = c("scenario", "region", "year", "input")) %>%
mutate(diff = round(value.x - value.y, 3))
if (any(is.na(comp))){
print("NAs in fuel total comparison (likely due to historical oil)")
}
if (any(abs(comp$diff) > 0, na.rm = TRUE)){
rows <- nrow(comp %>% filter(abs(diff) > 0))
print(paste0("Fuel totals incorrect in ", rows, " rows."))
} else {
print("All fuel totals correct.")
}
return(final_df)
}
lifecycle_CO2_emiss_phase_disag <- function(df){
df %>%
mutate(phase = if_else(!(transformation %in% c('refining','gas processing','electricity','backup_electricity')) & ghg == 'CO2','enduse',
if_else((transformation %in% c('electricity','backup_electricity') & ghg == 'CO2'),'midstream',phase))) -> df_for_disag
#assign all CO2 emissions for fuels with zero tailpipe / smokestack emissions to midstream
df_for_bindback <- df_for_disag %>%
filter(!is.na(phase) | ghg != 'CO2')
ccoef_mapping <- read_csv('input/ccoef_mapping.csv',show_col_types = FALSE)
outputs_by_subsector <- rgcam::getQuery(prj, 'outputs by subsector')
inputs_by_subsector <- rgcam::getQuery(prj, 'inputs by subsector')
CO2_sequestration_by_tech <- rgcam::getQuery(prj, 'CO2 sequestration by tech')
inputs_by_subsector %>%
filter(sector == 'refining' | sector == 'gas processing') %>%
rename(PrimaryFuelCO2Coef.name = input) %>%
left_join(ccoef_mapping,by = c('PrimaryFuelCO2Coef.name')) %>%
mutate(c_input = value * PrimaryFuelCO2Coef) %>%
select(-Units) %>%
filter(!(PrimaryFuelCO2Coef.name == 'elect_td_ind')) -> upstream_inputs_by_subsector
CO2_sequestration_by_tech %>%
filter(sector == 'refining') %>%
mutate(fuel = if_else(subsector == 'biomass liquids','biomass',
if_else(subsector == 'coal to liquids','coal',NA_character_))) %>%
group_by(scenario,region,fuel,year,subsector) %>%
summarize(sum_seq = sum(value)) %>%
ungroup() %>%
mutate(sector = 'refining') -> refining_c_seq
upstream_inputs_by_subsector %>%
left_join(refining_c_seq,by = c('scenario','region','fuel','year','sector','subsector')) %>%
mutate(sum_seq = if_else(is.na(sum_seq),0,sum_seq),
upstream_c_emiss = c_input) %>%
group_by(scenario,region,sector,subsector,year,fuel) %>%
summarize(upstream_c_input = sum(upstream_c_emiss)) %>%
ungroup() -> upstream_c_input
outputs_by_subsector%>%
filter(sector == 'refining' | sector == 'gas processing') %>%
rename(PrimaryFuelCO2Coef.name = output) %>%
left_join(ccoef_mapping,by = c('PrimaryFuelCO2Coef.name')) %>%
mutate(c_output = value * PrimaryFuelCO2Coef,
c_output = if_else(is.na(c_output),0,c_output)) %>%
group_by(scenario,region,sector,year) %>%
summarize(c_output = sum(c_output)) %>%
ungroup() -> downstream_c_output
emiss_fracs_by_lifecycle_phase <- upstream_c_input %>%
left_join(downstream_c_output, by = c('scenario','region','sector','year')) %>%
group_by(scenario,region,sector,year) %>%
summarize(downstream_emiss_frac = c_output / sum(upstream_c_input)) %>%
ungroup() %>%
distinct(scenario,region,sector,year,downstream_emiss_frac) %>%
mutate(upstream_emiss_frac = 1-downstream_emiss_frac) %>%
rename(transformation = sector)
df_for_further_processing <- df_for_disag %>%
filter(is.na(phase) & ghg == 'CO2')
df_downstream <- df_for_further_processing %>%
left_join(emiss_fracs_by_lifecycle_phase,by = c('scenario','region','transformation','year')) %>%
mutate(phase = 'enduse',
downstream_emiss_frac = if_else(direct == 'biomass',0,downstream_emiss_frac),
upstream_emiss_frac = if_else(direct == 'biomass',1,upstream_emiss_frac),
value = value * downstream_emiss_frac)
df_upstream <- df_for_further_processing %>%
left_join(emiss_fracs_by_lifecycle_phase,by = c('scenario','region','transformation','year')) %>%
mutate(phase = 'midstream',
downstream_emiss_frac = if_else(direct == 'biomass',0,downstream_emiss_frac),
upstream_emiss_frac = if_else(direct == 'biomass',1,upstream_emiss_frac),
value = value * upstream_emiss_frac)
df_lifecycle_disag <- bind_rows(df_upstream,df_downstream,df_for_bindback) %>%
select(-downstream_emiss_frac,-upstream_emiss_frac) %>%
mutate(phase = if_else(ghg == 'CO2' & transformation %in% c('district heat','H2 production','H2 enduse'),'midstream',phase))
df <- df %>%
mutate(value = if_else(is.na(value),0,value))
df_lifecycle_disag <- df_lifecycle_disag %>%
mutate(value = if_else(is.na(value),0,value))
print(sum(df_lifecycle_disag$value))
print(sum(df$value))
return(df_lifecycle_disag)
}
final_fuel_CO2_disag <- function(all_emissions){
sectors <- read_csv('input/sector_label.csv')
elec_gen_fuels <- read_csv('input/elec_generation.csv')
CO2_sequestration_by_tech <- rgcam::getQuery(prj, 'CO2 sequestration by tech')
sectors %>%
filter(type == 'transformation') %>%
distinct(rewrite) -> transformation_sectors
sectors_elec <- sectors %>%
filter(rewrite == 'electricity')
inputs_by_subsector <- rgcam::getQuery(prj, "inputs by subsector")
all_emissions %>%
select(scenario,region,year,direct,transformation,enduse,ghg,value,Units) %>%
filter(ghg == 'CO2') -> CO2_emiss
CO2_emiss_transform <- CO2_emiss %>%
filter(direct %in% transformation_sectors$rewrite)
#first deal with electricity
all_emissions %>%
select(scenario,region,direct,transformation,enduse,year,value,ghg,Units) %>%
filter((direct != 'electricity') | (ghg != 'CO2')) -> all_emiss_no_elec_CO2
CO2_emiss_elec <- CO2_emiss_transform %>%
filter(direct == 'electricity')
CO2 %>%
filter(sector %in% sectors_elec$sector) %>%
group_by(region,scenario,year) %>%
mutate(normfrac = value/sum(value)) %>%
ungroup() %>%
select(-value,-Units) -> tmp_elec
tmp_elec%>%
left_join(elec_gen_fuels, by = c('sector')) %>%
mutate(fuel = if_else(fuel == 'backup_electricity','natural gas',fuel)) %>%
group_by(scenario,region,year,fuel) %>%
summarize(normfrac = sum(normfrac)) %>%
ungroup() -> temp_elec_fuels
tmp_elec%>%
left_join(CO2_emiss_elec, by = c('scenario','region','year')) %>%
mutate(value = value * normfrac) %>%
left_join(elec_gen_fuels, by = c('sector')) %>%
#filter(year >= 2005) %>%
group_by(scenario,region,fuel,direct,transformation,enduse,year) %>%
summarise(value = sum(value)) %>%
ungroup() %>%
arrange(year) %>%
mutate(direct = fuel,
transformation = if_else(fuel == 'backup_electricity',fuel,transformation),
direct = if_else(fuel == 'backup_electricity','natural gas',direct),#assign backup electricity to gas since natural gas open cycle is the only tech for this sector
ghg = 'CO2',
Units = 'MTCO2e') %>%
select(-fuel) -> elec_CO2_no_bio_final
print("Allocated electricity emissions by fuel")
####
#get electricity emissions intensity per unit generated as it is a fuel for certain other transform sectors (e.g., H2 production)
outputs_by_subsector <- rgcam::getQuery(prj, 'outputs by subsector') %>%
filter(sector == 'electricity') %>%
group_by(scenario,region,year,Units) %>%
summarize(value = sum(value)) %>%
ungroup() %>%
rename(elec_output = value) -> elec_outputs
elec_CO2_no_bio_final %>%
group_by(scenario,region,year,ghg,Units) %>%
summarize(value = sum(value)) %>%
ungroup() %>%
rename(elec_emiss = value) -> tot_elec_emissions
elec_emiss_intensity <- tot_elec_emissions %>%
left_join(elec_outputs %>% select(-Units),by = c('scenario','region','year')) %>%
mutate(value = elec_emiss / elec_output,
Units = 'MtCO2-per-EJ') %>%
select(scenario,region,year,ghg,Units,value)
#### disagregate transportation tailpipe emissions ###
transport_sectors <- read_csv('input/transport.csv')
ccoef_mapping <- read_csv('input/ccoef_mapping.csv')
inputs_by_subsector %>% #get all sectors using refined liquids (incl. non transportation)
filter(input %in% c('refined liquids industrial','refined liquids enduse'),
!(sector %in% c('elec_refined liquids (CC)','elec_refined liquids (CC CCS)','elec_refined liquids (steam/CT)'))) %>%
mutate(subsector = if_else(subsector == 'refined liquids',sector,subsector)) %>%
distinct(subsector)-> refined_liquids_subsector
all_emiss_no_elec_CO2 %>%
filter(((enduse %in% transport_sectors$transportation_subsector & direct == 'refining') | direct %in% transport_sectors$transportation_subsector) & ghg == 'CO2') %>%
select(-transformation)-> trn_CO2
## Filter to get fuels with tailpipe emissions (i.e., natural gas + refined liquids)
trn_inputs_by_subsector <- inputs_by_subsector %>%
filter(subsector %in% transport_sectors$transportation_subsector,
input %in% c('refined liquids enduse','delivered gas','refined liquids industrial')) %>%
rename(enduse = subsector,
PrimaryFuelCO2Coef.name = input) %>%
left_join(ccoef_mapping,by = c('PrimaryFuelCO2Coef.name')) %>%
mutate(transformation = if_else((PrimaryFuelCO2Coef.name == 'refined liquids enduse' | PrimaryFuelCO2Coef.name == 'refined liquids industrial'),'refining',
if_else(PrimaryFuelCO2Coef.name == 'delivered gas','gas processing',NA_character_)),
tailpipe_emiss = value * PrimaryFuelCO2Coef) %>%
group_by(scenario,region,enduse,year) %>%
mutate(frac_tailpipe_emiss = tailpipe_emiss / sum(tailpipe_emiss),
frac_tailpipe_emiss = if_else(tailpipe_emiss ==0 & sum(tailpipe_emiss) == 0,
0, frac_tailpipe_emiss)) %>%
ungroup() %>%
select(-sector,-PrimaryFuelCO2Coef.name,-value,-PrimaryFuelCO2Coef,-fuel,-tailpipe_emiss,-Units)
trn_inputs_by_subsector %>%
left_join(trn_CO2,by = c('scenario','region','enduse','year')) %>%
mutate(frac_tailpipe_emiss = if_else(is.na(frac_tailpipe_emiss) & value == 0,
0, frac_tailpipe_emiss),
value = value * frac_tailpipe_emiss,
fuel = if_else(transformation == 'refining','refining',
if_else(transformation == 'gas processing','natural gas',NA_character_)),
direct = fuel) %>%
select(-frac_tailpipe_emiss,-fuel) %>%
#filter(year >= 2005) %>%
group_by(scenario,region,direct,transformation,enduse,year,ghg,Units) %>%
summarize(value = sum(value)) %>%
ungroup() -> trn_tailpipe_CO2_for_disag
trn_tailpipe_CO2_for_disag %>%
distinct(enduse) -> trn_sectors
all_emiss_no_elec_or_trn_CO2 <- all_emiss_no_elec_CO2 %>%
filter(!((enduse %in% transport_sectors$transportation_subsector & direct == 'refining') |
direct %in% transport_sectors$transportation_subsector) |
ghg != 'CO2')
CO2_sequestration_by_tech$year <- as.numeric(CO2_sequestration_by_tech$year)
CO2_sequestration_by_tech %>%
filter(sector == 'refining') %>%
mutate(fuel = if_else(subsector == 'biomass liquids','biomass',
if_else(subsector == 'coal to liquids','coal',NA_character_))) %>%
group_by(scenario,region,fuel,year) %>%
summarize(sum_seq = sum(value)) %>%
ungroup()-> refining_c_csq
inputs_by_subsector %>%
filter((sector == 'refining') & (input != 'elect_td_ind')) %>%
rename(PrimaryFuelCO2Coef.name = input) %>%
left_join(ccoef_mapping,by = c('PrimaryFuelCO2Coef.name')) %>%
mutate(c_input = value * PrimaryFuelCO2Coef) %>%
group_by(scenario,region,year,fuel) %>%
summarize(c_input = sum(c_input)) %>%
ungroup() %>%
left_join(refining_c_csq,by = c('scenario','region','year','fuel')) %>%
mutate(c_input = if_else(fuel == 'biomass',0,c_input),
sum_seq = if_else(is.na(sum_seq),0,sum_seq),
emiss_no_bio = c_input - sum_seq) -> refining_emiss_by_fuel_no_bio
inputs_by_subsector %>%
filter((sector == 'refining') & (input == 'elect_td_ind')) %>%
left_join(elec_emiss_intensity %>%
select(-Units) %>%
rename(emiss_intensity = value),by = c('scenario','region','year')) %>%
mutate(value = value * emiss_intensity * 12 / 44, #convert to MtC
Units = 'MTC') %>%
select(-emiss_intensity)-> refining_elec_input
temp_elec_fuels %>%
left_join(refining_elec_input,by = c('scenario','region','year')) %>%
mutate(c_input = value * normfrac,
sum_seq = 0,
emiss_no_bio = c_input - sum_seq) %>%
select(scenario,region,year,fuel,c_input,sum_seq,emiss_no_bio) -> refining_elec_input_joined #disaggregate electricity CO2 emissions for refining
#refining_emiss_by_fuel_no_bio_bind <- bind_rows(refining_emiss_by_fuel_no_bio,refining_elec_input_joined) %>%
refining_emiss_by_fuel_no_bio_bind <- bind_rows(refining_emiss_by_fuel_no_bio) %>%
mutate(emiss_no_bio = if_else(is.na(emiss_no_bio),0,emiss_no_bio)) %>%
group_by(scenario,region,year,fuel) %>%
summarize(emiss_no_bio = sum(emiss_no_bio)) %>%
ungroup()
refining_emiss_by_fuel_no_bio_bind %>%
group_by(scenario,region,year) %>%
mutate(emiss_no_bio = if_else(is.na(emiss_no_bio),0,emiss_no_bio),
normfrac = emiss_no_bio/sum(emiss_no_bio),
normfrac = if_else(is.na(normfrac),0,normfrac),
transformation = 'refining',
ghg = 'CO2') %>%
select(-emiss_no_bio) -> refining_emiss_by_fuel_no_bio_norm
refining_emiss_by_fuel_no_bio_norm %>%
left_join(trn_tailpipe_CO2_for_disag %>% filter(transformation == 'refining'),by = c('scenario','region','year','transformation','ghg')) %>%
mutate(direct = fuel,
value = value*normfrac) %>%
#filter(year >= 2005) %>%
select(-fuel,-normfrac) %>%
bind_rows(trn_tailpipe_CO2_for_disag %>% filter(transformation == 'gas processing'))-> trn_tailpipe_CO2_disag
## Now disaggregate hydrogen no bio emissions
all_emiss_no_elec_or_trn_CO2 %>%
filter(direct != 'H2 enduse' | ghg != 'CO2') -> all_emiss_no_elec_or_trn_no_H2_CO2
all_emiss_no_elec_or_trn_CO2 %>%
filter(direct == 'H2 enduse' & ghg == 'CO2') -> H2_CO2_emiss
inputs_by_subsector %>%
filter(sector == 'H2 central production' | sector == 'H2 forecourt production') %>%
rename(PrimaryFuelCO2Coef.name = input) %>%
left_join(ccoef_mapping,by = c('PrimaryFuelCO2Coef.name')) %>%
mutate(PrimaryFuelCO2Coef = if_else(is.na(PrimaryFuelCO2Coef) | fuel == 'biomass',0,PrimaryFuelCO2Coef),
fuel = if_else(is.na(fuel),PrimaryFuelCO2Coef.name,fuel),
c_input = value * PrimaryFuelCO2Coef) %>%
group_by(scenario,region,year,fuel) %>%
summarize(c_input = sum(c_input)) %>%
ungroup() %>%
filter(!(fuel %in% c('elect_td_ind','elect_td_trn'))) -> H2_inputs_no_elec #need to bind back electricity emissions
inputs_by_subsector %>%
filter(sector == 'H2 central production' | sector == 'H2 forecourt production',
input %in% c('elect_td_ind','elect_td_trn')) %>%
group_by(scenario,region,year,Units) %>%
summarize(value = sum(value)) %>%
ungroup() %>%
left_join(elec_emiss_intensity %>%
select(-Units) %>%
rename(emiss_intensity = value),by = c('scenario','region','year')) %>%
mutate(c_input = value * emiss_intensity * 12 /44, #need to convert back to MtC from MtCO2e
fuel = 'electricity') %>%
select(-emiss_intensity,-value) -> H2_grid_elec_inputs
H2_inputs <- bind_rows(H2_inputs_no_elec)
CO2_sequestration_by_tech %>%
filter(sector == 'H2 central production' | sector == 'H2 forecourt production') %>%
mutate(fuel = if_else(subsector == 'gas','natural gas',subsector)) %>%
rename(c_seq = value)-> H2_sequestration
H2_sequestration %>%
distinct(scenario,region,year) %>%
mutate(fuel = 'electricity',
c_seq = 0) -> H2_elec_seq
H2_sequestration <- bind_rows(H2_sequestration) #,H2_elec_seq)
H2_inputs %>%
left_join(H2_sequestration %>%
select(-sector,-subsector,-technology),by = c('scenario','region','year','fuel')) %>%
mutate(c_seq = if_else(is.na(c_seq),0,c_seq),
emiss_no_bio = c_input - c_seq,
Units = 'MTC') %>% #mutate to H2 production (the actual transformation) occurs at the end
group_by(scenario,region,year) %>%
mutate(normfrac = emiss_no_bio / sum(emiss_no_bio)) %>%
select(-Units) -> H2_inputs_joined
H2_inputs_joined %>%
left_join(H2_CO2_emiss, by = c('scenario','region','year')) %>%
mutate(direct = fuel,
value = value * normfrac,
value = if_else(is.na(value) & is.na(normfrac) & emiss_no_bio == 0, 0, value)) %>%
filter(!(value == 0 & is.na(ghg))) %>%
select(-c_input,-c_seq,-emiss_no_bio,-fuel,-normfrac) %>%
filter(direct %in% c('electricity','biomass','coal','natural gas','crude oil')) %>%
mutate(transformation = if_else(direct == 'electricity','H2 grid electrolysis',transformation)) -> H2_CO2_emiss_disag
H2_CO2_emiss_disag %>%
filter(direct != 'electricity') -> H2_CO2_emiss_no_elec
H2_CO2_emiss_disag %>%
filter(direct == 'electricity') -> H2_CO2_emiss_elec
temp_elec_fuels %>%
left_join(H2_CO2_emiss_elec,by = c('scenario','region','year')) %>%
filter(!is.na(Units)) %>%
mutate(value = normfrac * value) %>%
select(-direct,-normfrac) %>%
rename(direct = fuel) -> H2_elec_CO2_disag
#H2_CO2_emiss_disag <- bind_rows(H2_CO2_emiss_no_elec,H2_elec_CO2_disag)
H2_CO2_emiss_disag <- bind_rows(H2_CO2_emiss_no_elec)
#deal with all remaining CO2 emissions
#break out H2 and refining emissions to be dealt with downstream
c_containing <- c('biomass','coal','natural gas','cement limestone','crude oil','airCO2')
#all_emissions %>% select(scenario,region,direct,year,transformation,enduse,ghg,value,Units) %>%
all_emiss_no_elec_or_trn_no_H2_CO2 %>%
filter(!(direct %in% c_containing) & ghg == 'CO2') -> remaining_industry_CO2
#all_emissions %>% select(scenario,region,direct,year,transformation,enduse,ghg,value,Units) %>%
all_emiss_no_elec_or_trn_no_H2_CO2 %>%
filter(!(!(direct %in% c_containing) & ghg == 'CO2')) -> all_emiss_no_elec_or_trn_no_H2_CO2_final
## Filter to get fuels with tailpipe/smokestack emissions (i.e., natural gas + refined liquids)
c_containing_ind_fuels <- c('delivered biomass','delivered coal','delivered gas','regional natural gas','unconventional oil','wholesale gas','traditional biomass',
'refined liquids industrial','refined liquids enduse','limestone','district heat','process heat cement','process heat dac','airCO2')
transform_ind <- c('district heat','process heat cement','process heat dac')
industrial_cseq_by_fuel <- CO2_sequestration_by_tech %>%
# filter(sector %in% remaining_industry_CO2$enduse) %>%
left_join(ccoef_mapping %>% rename(technology = PrimaryFuelCO2Coef.name), by = c('technology')) %>%
select(-PrimaryFuelCO2Coef,-subsector) %>%
rename(enduse = sector,
c_seq = value)
#first break out tailpipe/smokestack emissions (i.e,. where direct == transformation == enduse)
remaining_industry_CO2 %>%
filter(direct == transformation & transformation == enduse,
direct != 'iron and steel') -> point_source_industrial_CO2
#because iron and steel intakes multiple carbon-containing fuels and sequesters a blend of their associated emissions we need to deal with it separately
remaining_industry_CO2 %>%
filter(direct == transformation & transformation == enduse,
direct == 'iron and steel') -> point_source_iron_steel
iron_steel_capture_coef <- 0.9 # here we assume an equal share of all fuel carbon is sequestered for iron and steel
iron_steel_emiss_disag <- rgcam::getQuery(prj,'inputs by tech') %>%
filter(sector == 'iron and steel',
!(input %in% c('elect_td_ind','H2 enduse','scrap'))) %>%
rename(PrimaryFuelCO2Coef.name = input) %>%
left_join(ccoef_mapping,by = c('PrimaryFuelCO2Coef.name')) %>%
mutate(c_emiss = PrimaryFuelCO2Coef * value,
c_emiss = if_else(fuel == 'biomass',0,c_emiss),
c_seq = if_else(technology %in% c('BLASTFUR CCS','EAF with DRI CCS','EAF with SCRAP CCS'),c_emiss * iron_steel_capture_coef,0),
c_emiss = c_emiss - c_seq) %>%
group_by(scenario,region,year) %>%
mutate(normfrac = c_emiss / sum(c_emiss)) %>%
ungroup() %>%
group_by(scenario,region,year,fuel) %>%
summarize(normfrac = sum(normfrac)) %>%
ungroup() %>%
rename(direct = fuel) %>%
left_join(point_source_iron_steel %>% select(-direct),by = c('scenario','region','year')) %>%
mutate(value = value * normfrac,
transformation = 'iron and steel',
transformation = if_else(direct == 'refining','refining',transformation)) %>%
select(-normfrac)
upstream_industrial_CO2 <-remaining_industry_CO2 %>%
anti_join(bind_rows(point_source_industrial_CO2,point_source_iron_steel),by = c('scenario','region','year','direct','transformation','enduse')) %>%
filter(direct != 'district heat')
ind_transform_en_inputs_norm <- inputs_by_subsector %>%
filter(sector %in% transform_ind) %>%
rename(PrimaryFuelCO2Coef.name = input,
transformation = sector) %>%
group_by(scenario,region,year,transformation) %>%
mutate(sum_val = sum(value),
en_frac = value / sum_val,
en_frac = if_else(sum_val == 0 & value == 0, 0, en_frac)) %>%
ungroup() %>%
select(-sum_val) %>%
left_join(ccoef_mapping,by = c('PrimaryFuelCO2Coef.name'))
district_heating_norm <- inputs_by_subsector %>%
filter(sector == 'district heat') %>%
rename(PrimaryFuelCO2Coef.name = input,
transformation = sector) %>%
left_join(ccoef_mapping,by = c('PrimaryFuelCO2Coef.name')) %>%
mutate(fuel = if_else(PrimaryFuelCO2Coef.name == 'refined liquids industrial','refining',fuel),
PrimaryFuelCO2Coef = if_else(fuel == 'biomass',0,PrimaryFuelCO2Coef),
value = value * PrimaryFuelCO2Coef,
Units = 'MTC') %>%
group_by(scenario,region,year,transformation) %>%
mutate(emiss_frac = value/sum(value)) %>%
ungroup() %>%
select(-value,-Units,-subsector,-PrimaryFuelCO2Coef.name,-PrimaryFuelCO2Coef)
district_heating_for_disag <- remaining_industry_CO2 %>%
filter(transformation == 'district heat')
district_heating_norm %>%
left_join(district_heating_for_disag %>% select(-direct), by = c('scenario','region','transformation','year')) %>%
rename(direct = fuel) %>%
mutate(value = value * emiss_frac) -> district_heat_disag
#write_csv(ind_transform_en_inputs_norm,'ind_transform_en_inputs_norm.csv')
ind_inputs_by_subsector_temp <- inputs_by_subsector %>%
filter(sector %in% remaining_industry_CO2$enduse,
input %in% c_containing_ind_fuels) %>%
mutate(input = if_else(input == 'unconventional oil','crude oil',input),
input = if_else(input == 'traditional biomass','biomass',input)) %>%
rename(PrimaryFuelCO2Coef.name = input) #%>%
#%>%
ind_inputs_transform_for_disag <- ind_inputs_by_subsector_temp %>%
filter(PrimaryFuelCO2Coef.name %in% transform_ind)
process_heat_cement_disag <- ind_transform_en_inputs_norm %>%
select(-value,-subsector) %>%
left_join(ind_inputs_transform_for_disag %>% select(-subsector,-Units) %>%
rename(transformation = PrimaryFuelCO2Coef.name),by = c('scenario','region','year','transformation')) %>%
mutate(c_emiss = value * en_frac * PrimaryFuelCO2Coef,
c_emiss = if_else(fuel == 'biomass',0,c_emiss)) %>%
rename(enduse = sector) %>%
left_join(industrial_cseq_by_fuel %>% rename(transformation = enduse) %>%
select(-Units),by = c('scenario','region','year','transformation','fuel')) %>%
mutate(c_seq = if_else(is.na(c_seq),0,c_seq),
c_emiss = c_emiss - c_seq) %>%
rename(direct = fuel) %>%
select(scenario,region,year,direct,transformation,enduse,c_emiss) %>%
rename(value = c_emiss) %>%
filter(transformation == 'process heat cement')
ind_inputs_by_subsector_no_transform <- ind_inputs_by_subsector_temp %>%
filter(!(PrimaryFuelCO2Coef.name %in% transform_ind)) %>%
left_join(ccoef_mapping,by = c('PrimaryFuelCO2Coef.name')) %>%
mutate(value = value * PrimaryFuelCO2Coef,
value = if_else(fuel == 'biomass',0,value),
Units = 'MTC',
transformation = sector,
transformation = if_else(fuel == 'refining','refining',transformation)) %>%
rename(enduse = sector) %>%
left_join(industrial_cseq_by_fuel,by = c('scenario','region','year','enduse','fuel','Units')) %>%
mutate(c_seq = if_else(is.na(c_seq),0,c_seq),
c_emiss = value - c_seq) %>%
rename(direct = fuel) %>%
select(scenario,region,year,direct,transformation,enduse,c_emiss) %>%
rename(value = c_emiss)
ind_point_source_norm <- bind_rows(ind_inputs_by_subsector_no_transform,process_heat_cement_disag) %>%
group_by(scenario,region,year,enduse) %>%
mutate(normfrac = value / sum(value)) %>%
ungroup() %>%
select(-value)
#process_heat_cement_disag %>% filter(transformation != 'process heat cement') -> ind_transform_disag_final
ind_point_source_norm %>%
left_join(point_source_industrial_CO2 %>% select(-direct,-transformation),by = c('scenario','region','year','enduse')) %>%
mutate(value = value * normfrac,
value = if_else(is.na(value),0,value)) %>%
select(-normfrac) %>% #add back iron and steel disag
bind_rows(iron_steel_emiss_disag) -> disag_point_source_ind_CO2
#write_csv(disag_point_source_ind_CO2,'disag_point_source_ind_CO2.csv')
#write_csv(upstream_industrial_CO2,'upstream_industrial_CO2.csv')
#write_csv(ind_transform_disag_final,'ind_transform_disag_final.csv')
remaining_industry_disag <- bind_rows(disag_point_source_ind_CO2,upstream_industrial_CO2,district_heat_disag) %>%
mutate(direct = if_else(direct == 'refining' & value > 0,'crude oil',
if_else(direct == 'refining' & value <= 0,'biomass',direct)),
ghg = 'CO2',
Units = 'MTCO2e')
## Final processing #