-
Notifications
You must be signed in to change notification settings - Fork 0
/
5b_EDGAR_get_proxies.R
376 lines (304 loc) · 14.1 KB
/
5b_EDGAR_get_proxies.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
#'
#'
#'
#' @author Simon Schulte
#' Date: 2022-07-14 15:51:48
#'
#' Content:
#'
############################################################################## #
##### load packages ############################################################
############################################################################## #
library(data.table)
library(tidyverse)
library(units)
library(ggforce)
#library(my.utils)
library(countrycode)
library(mRio)
library(testthat)
library(arrow)
############################################################################## #
##### settings #################################################################
############################################################################## #
source('./src/functions.R')
# read config and setup log script
config <- setup_config_and_log()
path2output <- config$path2output
theme_set(theme_bw())
#' Get use or supply shares from SUTs (result of script 0a_prepare_exiobase_SUTs.R)
#'
#' Extract use/supply shares for
#' - (a) specific product(s)
#' - from (a) specific countr(ies)
#' - in specific industries
#' - in specific countries
#'
#'
#' @param x a supply or use table (result of script 0a_prepare_exiobase_SUTs.R)
#' @param products
#' @param industries
#' @param product_countries
#' @param industry_countries
#'
#' @return
#' @export
#'
#' @examples
# sut = use
# products = temp$EXIOBASE_products %>% unlist %>% unique
# industries = temp$EXIOBASE_code %>% unlist %>% unique %>% as.factor()
# industry_countries = c('FIN', 'DEU')
# product_countries <- 'all'
get_SUT_shares <- function(sut,
products = 'all',
industries = 'all',
product_countries = 'all',
industry_countries = 'all') {
#sut <- copy(sut)
#print(sut$product_code)
#print(is.data.table(sut))
if (length(products) == 1 && products == 'all') products <- sut$product_code
if (length(industries) == 1 && industries == 'all') industries <- sut$industry_code
if (length(industry_countries) == 1 && industry_countries == 'all') industry_countries <- sut$country_industry
SUT_shares <- sut[
product_code %in% products
& industry_code %in% industries
& country_industry %in% industry_countries
, list(value = sum(value))
, by = .(industry_code)
]
SUT_shares[, country_total := sum(value)]
SUT_shares[, share := value / country_total]
if (nrow(SUT_shares) == 0) {
# product not used in any of the industries --> equally share them among all
# TODO: more elaborate
SUT_shares <- data.table(industry_code = industries,
share = 1 / length(industries))
}
return(SUT_shares[, .(industry_code, share)])
}
############################################################################## #
##### load data #############################################################
############################################################################## #
edgar_samples <- readRDS(file.path(path2output, 'sample_EDGAR.RData')) #'./temp_results/3b_EDGAR_samples.RData')
ct <- readRDS(config$path2CT_CRF_EDGAR_parsed)
#ct <- readRDS(file.path(path2output, 'prepare_CT_EDGAR.RData'))
#ct <- readRDS('/home/simon/Documents/Projects/Uncertainty_Extensions/code/UNFCCC_CRF_correspondence_tables/intermediate_results/CT_EDGAR_parsed.RData')
############################################################################## #
##### 1. Merge UNFCCC samples with EXIOBASE Correspondence table ###############
############################################################################## #
# _a) data preparation =========================================================
# edgar_samples[, category_code := pathString %>%
# gsub('I\\/', '', .) %>%
# gsub('\\/', '\\.', .)]
ct <- ct[, .(id, EDGAR_code, EXIOBASE_code, proxy_data_source, EXIOBASE_products)]
setkey(edgar_samples, year, country_code, gas, category_code)
setkey(ct, EDGAR_code)
# _b) merge ===================================================================
dt <- merge(edgar_samples, ct,
by.x = c('category_code'),
by.y = c('EDGAR_code'),
all.x = TRUE)
dt[, n_corres := list(sapply(EXIOBASE_code, length))]
#dt <- dt[proxy_data_source %in% c('USE', 'SUPPLY') | n_corres == 1]
# _c) checks ==================================================================
dt$proxy_data_source %>% unique
dt[is.na(EXIOBASE_code) & proxy_data_source %in% c('SUPPLY, USE'), ]
# check coverage ====
edgar_samples3 <- merge(edgar_samples[, list(total_emissions = sum(emissions, na.rm = TRUE)), by = gas],
dt[, list(covered_emissions= sum(emissions, na.rm = TRUE)), by = gas],
by = 'gas')
edgar_samples3[, percent_covered := covered_emissions / total_emissions]
edgar_samples3
# _d) more preparations ======================================================
dt[, key := paste(year, country_code,
paste(EXIOBASE_code, sep = ''),
paste(EXIOBASE_products, sep = ''),
paste(proxy_data_source, sep = ''),
sep = '')]
# list all proxy data sources
dt$proxy_data_source %>% unique
dt$proxy_data_source %>% sapply(length) %>% unique
dt[sapply(proxy_data_source, length) == 0]
#dt[, proxy_data_source := sapply(dt$proxy_data_source, '[', 1)]
dt[is.na(proxy_data_source) & n_corres == 1
, proxy_data_source := '1to1']
dt[EXIOBASE_code == 'all']
dt[proxy_data_source == ('USE')]
dt[is.na(proxy_data_source) & n_corres != 1]
# _e) attach EXIOBASE region to each country ==================================
library(countrycode)
country_mapping <- rio::import(config$path2CountryMappingDESIRE)
country_mapping <- as.data.table(country_mapping)
dt <- merge(dt, country_mapping[, .(ISO3, `DESIRE code`)],
by.x = 'country_code', by.y = 'ISO3', all.x = TRUE)
setnames(dt, 'DESIRE code', 'EXIOBASE_region_code')
dt[is.na(EXIOBASE_region_code)]$country_code
dt[country_code == 'ROU', EXIOBASE_region_code := 'RO']
dt[country_code == 'SCG', EXIOBASE_region_code := 'WE']
dt <- dt[!(country_code %in% c('SEA', 'AIR'))]
############################################################################## #
##### 2. Get proxies ##########################################################
############################################################################## #
############################################################################## #
# _a) SUT ------------------------------------------------------------------
############################################################################## #
# __i. load data ---------------------------------------------------------------
use <- read_feather(file.path(path2output, 'prepare_SUT_proxies_use.feather'))
use <- na.omit(use)
supply <- read_feather(file.path(path2output, 'prepare_SUT_proxies_supply.feather'))
supply <- na.omit(supply)
# load meta data
#meta <- parse_EB3_metadata('/home/simon/Documents/PhD_PROSET/data/EXIOBASE3/V3.8.2/IOT_2015_pxp')
meta <- parse_EB3_metadata(config$path2exiobaseIOT)
# __ii. data checks -----------------------------------------------------------
# are all proxy details there? (should return empty data.table)
test_that('all proxy details (corresponding EB indudstries and products) are there', {
expect_equal(0, nrow(dt[proxy_data_source == 'USE'& is.na(EXIOBASE_products)]))
expect_equal(0, nrow(dt[proxy_data_source == 'USE'& is.na(EXIOBASE_code)]))
expect_equal(0, nrow(dt[proxy_data_source == 'SUPPLY'& is.na(EXIOBASE_products)]))
expect_equal(0, nrow(dt[proxy_data_source == 'SUPPLY'& is.na(EXIOBASE_code)]))
})
# all information on EB sectors correct?
#dt$EXIOBASE_code %>% unlist %>% unique %>% non_common_elements(meta$industries$CodeNr %>% unique)
#dt$EXIOBASE_products %>% unlist %>% unique %>% non_common_elements(meta$products$CodeNr %>% unique)
# __iii. retrieve information from USE table ----------------------------------
dt[proxy_data_source == 'USE'
, proxies := list(mapply(FUN = get_SUT_shares,
products = EXIOBASE_products,
industries = EXIOBASE_code,
industry_countries = EXIOBASE_region_code,
MoreArgs = list(sut = use),
SIMPLIFY = FALSE)),
by = key]
# __iv. retrieve information from SUPPLY table ---------------------------------
dt[proxy_data_source == 'SUPPLY'
, proxies := list(mapply(FUN = get_SUT_shares,
products = EXIOBASE_products,
industries = EXIOBASE_code,
industry_countries = EXIOBASE_region_code,
MoreArgs = list(sut = supply),
SIMPLIFY = FALSE)),
by = key]
# __v. check results ----------------------------------------------------------
dt
dt[sapply(proxies, function(x) if (is.data.table(x)) nrow(x) == 1 else FALSE)]$proxies[[1]]
############################################################################## #
# _b) ROAD TRANSPORT ------------------------------------------------------------------
############################################################################## #
road <- read_feather(file.path(path2output, 'prepare_ROAD_TRANSPORT_proxies.feather'))
road[, proxies := lapply(proxies, as.data.table)]
road[, proxy_data_source := 'PEFA']
setnames(road, c('region', 'proxies'), c('EXIOBASE_region_code', 'proxies_ROAD'))
dt <- merge(dt, road,
by = c('EXIOBASE_region_code', 'proxy_data_source',
'gas'),
sort = FALSE,
all.x = TRUE)
dt[sapply(proxies, is.data.table) & sapply(proxies_ROAD, is.data.table)]
dt[sapply(proxies_ROAD, is.data.table), proxies := proxies_ROAD]
dt[, proxies_ROAD := NULL]
dt[grepl('1.A.3.b', category_code) & !sapply(proxies, is.data.table)]
############################################################################## #
##### Tests #################################################################
############################################################################## #
shares_not_sum_to_1 <- dt[
!is.na(proxy_data_source)
& !(proxy_data_source %in% c('1to1', 'PEFA'))
& !sapply(proxies, function(x) isTRUE(all.equal(sum(x$share), 1)))
]
test_that('all proxy shares sum to 1 (SUPPLY, USE, IEA)', {
expect_equal(nrow(shares_not_sum_to_1), 0)
})
missing_proxies <- dt[!(proxy_data_source %in% c('1to1'))
& !sapply(proxies, is.data.table)
, .(category_code)] %>%
unique
test_that('no proxies are missing', {
expect_equal(nrow(missing_proxies), 0)
})
############################################################################## #
##### Save results #################################################################
############################################################################## #
save_results(dt)
#saveRDS(dt, './temp_results/6a_EDGAR_samples_with_EXIOBASE_proxies.RData')
#TODO: check codes again in Correspondece table (maybe not fitiing codes are just wrong)!
###
# THE END ---------------------------------------------------------------------
# ############################################################################## #
# # _b) PEFA ------------------------------------------------------------------
# ############################################################################## #
#
# # __i. load data ==================================================
# pefa <- readRDS(file.path(path2output, 'prepare_PEFA_proxies.RData')) #'./temp_results/4b_PEFA_proxies.RData')
# setnames(pefa, 'proxies', 'proxies_NACErev2')
# pefa[, proxy_data_source := 'PEFA']
#
# temp <- copy(dt)
# # __ii. Assign to NACE rev2 ==================================================
# dt <- merge(dt, pefa,
# by.x = c('year', 'country_code', 'gas', 'proxy_data_source'),
# by.y = c('time', 'party', 'gas', 'proxy_data_source'),
# all.x = TRUE,
# sort = FALSE)
#
# dt[sapply(proxies_NACErev2, is.null) & proxy_data_source == 'PEFA']$country_code %>% unique
#
# #
# ############################################################################## #
# # _c) Employment ------------------------------------------------------------------
# ############################################################################## #
#
# # __i. load data ==================================================
# empl1 <- readRDS(file.path(path2output, 'prepare_EMPLOYMENT_proxies_primary.RData'))
# empl2 <- readRDS(file.path(path2output, 'prepare_EMPLOYMENT_proxies_secondary.RData'))
#
# empl1[, proxy_data_source := 'PEFA']
# empl1[, PEFA_avail := FALSE]
#
# empl2[, proxy_data_source := 'PEFA']
# empl2[, PEFA_avail := TRUE]
#
# setnames(empl1, 'region', 'EXIOBASE_region_code')
# setnames(empl2, 'region', 'EXIOBASE_region_code')
#
# # __ii. attach to dt
# # a) (countries with PEFA data -> as secondary proxy (only used to further split industries))
# # b) countries without PEFA -> as primary proxy (to also split btw hous/ind)
#
# dt[proxy_data_source == 'PEFA' & !sapply(proxies_NACErev2, is.null),
# PEFA_avail := TRUE]
# dt[proxy_data_source == 'PEFA' & sapply(proxies_NACErev2, is.null),
# PEFA_avail := FALSE]
#
#
# dt <- merge(dt, empl1,
# by = c('EXIOBASE_region_code', 'proxy_data_source', 'PEFA_avail',
# 'gas'),
# sort = FALSE,
# all.x = TRUE)
# dt <- merge(dt, empl2,
# by = c('EXIOBASE_region_code', 'proxy_data_source', 'PEFA_avail'),
# sort = FALSE,
# all.x = TRUE)
#
# # combine both columns to proxies_empl
# dt[!sapply(proxies_empl.x, is.null), proxies_empl := proxies_empl.x]
# dt[!sapply(proxies_empl.y, is.null), proxies_empl := proxies_empl.y]
#
#
# dt[grepl('^1.A.3.b', category_code),
# proxies := proxies_empl]
#
# test_that("All proxies for Road Transport 1.A.3.b is there", {
# expect_equal(0,
# nrow(dt[grepl('^1.A.3.b', category_code) & sapply(proxies_empl, is.null)]))
# })
#
#
# dt[, proxies_empl := NULL]
# dt[, proxies_empl.x := NULL]
# dt[, proxies_empl.y := NULL]
#
# dt[proxy_data_source == 'PEFA']