-
Notifications
You must be signed in to change notification settings - Fork 19
/
Copy path09_mrsut.R
228 lines (172 loc) · 8.58 KB
/
09_mrsut.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
library("data.table")
library("Matrix")
library("parallel")
source("R/01_tidy_functions.R")
source("R/00_system_variables.R")
regions <- fread("inst/regions_full.csv")[current==TRUE]
items <- fread("inst/items_full.csv")
sup <- readRDS("data/sup_final.rds")
cbs <- readRDS("data/cbs_final.rds")
btd <- readRDS("data/btd_final.rds")
use <- readRDS("data/use_final.rds")
use_fd <- readRDS("data/use_fd_final.rds")
areas <- sort(unique(cbs$area_code))
processes <- sort(unique(use$proc_code))
commodities <- sort(unique(use$comm_code))
# Supply ---
# Template to always get full tables
template <- data.table(expand.grid(
proc_code = processes, comm_code = commodities, stringsAsFactors = FALSE))
setkey(template, proc_code, comm_code)
# List with block-diagonal supply matrices, per year
mr_sup_mass <- mclapply(years, function(x) {
matrices <- lapply(areas, function(y, sup_y) {
# Get supply for area y and merge with the template
sup_x <- sup_y[area_code == y, .(proc_code, comm_code, production)]
out <- if(nrow(sup_x) == 0) {
template[, .(proc_code, comm_code, production = 0)]
} else {merge(template, sup_x, all.x = TRUE)}
# Cast the datatable to convert into a matrix
out <- tryCatch(data.table::dcast(out, proc_code ~ comm_code,
value.var = "production", fun.aggregate = sum, na.rm = TRUE, fill = 0),
error = function(e) {stop("Issue at ", x, "-", y, ": ", e)})
# Return a (sparse) matrix of supply for region y and year x
return(Matrix(data.matrix(out[, c(-1)]), sparse = TRUE,
dimnames = list(out$proc_code, colnames(out)[-1])))
}, sup_y = sup[year == x, .(area_code, proc_code, comm_code, production)])
# Return a block-diagonal matrix with all countries for year x
return(bdiag(matrices))
}, mc.cores = 10)
# Convert to monetary values
sup[!is.na(price) & is.finite(price), value := production * price]
# If no price available, keep physical quantities
sup[is.na(price) | !is.finite(price), value := production]
# List with block-diagonal supply matrices in value, per year
mr_sup_value <- mclapply(years, function(x) {
matrices <- lapply(areas, function(y, sup_y) {
# Get supply for area y and merge with the template
sup_x <- sup_y[area_code == y, .(proc_code, comm_code, value)]
out <- if(nrow(sup_x) == 0) {
template[, .(proc_code, comm_code, value = 0)]
} else {merge(template, sup_x, all.x = TRUE)}
# Cast the datatable to convert into a matrix
out <- tryCatch(data.table::dcast(out, proc_code ~ comm_code,
value.var = "value", fun.aggregate = sum, na.rm = TRUE, fill = 0),
error = function(e) {stop("Issue at ", x, "-", y, ": ", e)})
# Return a (sparse) matrix of supply for region y and year x
return(Matrix(data.matrix(out[, c(-1)]), sparse = TRUE,
dimnames = list(out$proc_code, colnames(out)[-1])))
}, sup_y = sup[year == x, .(area_code, proc_code, comm_code, value)])
# Return a block-diagonal matrix with all countries for year x
return(bdiag(matrices))
}, mc.cores = 10)
names(mr_sup_mass) <- names(mr_sup_value) <- years
saveRDS(mr_sup_mass, file.path(output_dir,"mr_sup_mass.rds"))
saveRDS(mr_sup_value, file.path(output_dir,"mr_sup_value.rds"))
# Bilateral supply shares ---
# Template to always get full tables
template <- data.table(expand.grid(
from_code = areas, to_code = areas,
comm_code = commodities, stringsAsFactors = FALSE))
setkey(template, from_code, comm_code, to_code)
# Yearly list of BTD in matrix format
# Note that btd_final includes not only re-export adjusted bilateral trade flows,
# but also domestic production for domestic use, i.e. it gives the sources
# (domestic and imported) of each country's domestic use of any item.
btd_cast <- mclapply(years, function(x, btd_x) {
# Cast to convert to matrix
out <- data.table::dcast(merge(template,
btd_x[year == x, .(from_code, to_code, comm_code, value)],
by = c("from_code", "to_code", "comm_code"), all.x = TRUE),
from_code + comm_code ~ to_code,
value.var = "value", fun.aggregate = sum, na.rm = TRUE, fill = 0)
return(Matrix(data.matrix(out[, c(-1, -2)]), sparse = TRUE,
dimnames = list(paste0(out$from_code, "-", out$comm_code),
colnames(out)[c(-1, -2)])))
}, btd_x = btd[, .(year, from_code, to_code, comm_code, value)], mc.cores = 10)
names(btd_cast) <- years
# Get commodities and their positions from total supply for domestic use
comms <- gsub("(^[0-9]+)-(c[0-9]+)", "\\2", rownames(btd_cast[[1]]))
is <- as.numeric(vapply(unique(comms), function(x) {which(comms == x)},
numeric(length(unique(areas)))))
js <- rep(seq(unique(comms)), each = length(unique(areas)))
# Matrix used to aggregate over commodities
agg <- Matrix::sparseMatrix(i = is, j = js)
# Build supply shares, per year
supply_shares <- mclapply(btd_cast, function(x, agg, js) {
# x_agg <- colSums(crossprod(x, agg)) # Aggregate total supply (all countries)
x_agg <- crossprod(x, agg) # Aggregate total supply (per country)
denom <- data.table(as.matrix(t(x_agg)))
# Calculate shares (per country)
out <- as.matrix(x / as.matrix(denom[rep(seq(length(commodities)), length(areas)), ]))
out[!is.finite(out)] <- 0 # See Issue #75
# source is domestic, where no sources given in btd_final
for(i in 1:nrow(regions)){
out[nrow(items)*(i-1)+62, i] <- 1
}
return(as(out, "Matrix"))
}, agg = agg, js = js, mc.cores = 10)
# Use ---
# Template to always get full tables
template <- data.table(expand.grid(
area_code = areas, proc_code = processes, comm_code = commodities,
stringsAsFactors = FALSE))
setkey(template, area_code, proc_code, comm_code)
# List with use matrices, per year
use_cast <- mclapply(years, function(x, use_x) {
# Cast use to convert to a matrix
out <- data.table::dcast(merge(template[, .(area_code, proc_code, comm_code)],
use_x[year == x, .(area_code, proc_code, comm_code, use)],
by = c("area_code", "proc_code", "comm_code"), all.x = TRUE),
comm_code ~ area_code + proc_code,
value.var = "use", fun.aggregate = sum, na.rm = TRUE, fill = 0)
return(Matrix(data.matrix(out[, c(-1)]), sparse = TRUE,
dimnames = list(out$comm_code, colnames(out)[-1])))
}, use_x = use[, .(year, area_code, proc_code, comm_code, use)], mc.cores = 10)
# Apply supply shares to the use matrix
mr_use <- mcmapply(function(x, y) {
# Repeat use values, then adapted according to shares
mr_x <- x[rep(seq_along(commodities), length(areas)), ]
n_proc <- length(processes)
for(j in seq_along(areas)) { # Per country j
mr_x[, seq(1 + (j - 1) * n_proc, j * n_proc)] <-
mr_x[, seq(1 + (j - 1) * n_proc, j * n_proc)] * y[, j]
}
return(mr_x)
}, use_cast, supply_shares, mc.cores = 10)
names(mr_use) <- years
saveRDS(mr_use, file.path(output_dir,"mr_use.rds"))
# Final Demand ---
# Template to always get full tables
template <- data.table(expand.grid(
area_code = areas, comm_code = commodities,
variable = c("food", "other", "losses", "stock_addition", "balancing", "unspecified", "tourist", "residuals", "processing"),
stringsAsFactors = FALSE))
setkey(template, area_code, comm_code, variable)
use_fd <- melt(use_fd[, .(year, area_code, comm_code,
food, other, losses, stock_addition, balancing, unspecified, tourist, residuals, processing)],
id.vars = c("year", "area_code", "comm_code"))
# List with final use matrices, per year
use_fd_cast <- mclapply(years, function(x, use_fd_x) {
# Cast final use to convert to a matrix
out <- data.table::dcast(merge(template[, .(area_code, comm_code, variable)],
use_fd_x[year == x, .(area_code, comm_code, variable, value)],
by = c("area_code", "comm_code", "variable"), all.x = TRUE),
comm_code ~ area_code + variable,
value.var = "value", fun.aggregate = sum, na.rm = TRUE, fill = 0)
Matrix(data.matrix(out[, -1]), sparse = TRUE,
dimnames = list(out$comm_code, colnames(out)[-1]))
}, use_fd[, .(year, area_code, comm_code, variable, value)], mc.cores = 6)
# Apply supply shares to the final use matrix
mr_use_fd <- mcmapply(function(x, y) {
mr_x <- x[rep(seq_along(commodities), length(areas)), ]
n_var <- length(unique(use_fd[,variable]))
for(j in seq_along(areas)) { # Could do this vectorised
mr_x[, seq(1 + (j - 1) * n_var, j * n_var)] <-
mr_x[, seq(1 + (j - 1) * n_var, j * n_var)] * y[, j]
}
return(mr_x)
}, use_fd_cast, supply_shares, mc.cores = 10)
mr_use_fd <- lapply(mr_use_fd, round)
names(mr_use_fd) <- years
saveRDS(mr_use_fd, file.path(output_dir,"mr_use_fd.rds"))