-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutils.R
More file actions
1847 lines (1609 loc) · 67.5 KB
/
Copy pathutils.R
File metadata and controls
1847 lines (1609 loc) · 67.5 KB
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
#' Useful functions for the `decent` software package.
# |||| ---------------------------------
# Decent Living Energy utils -----------
# |||| ---------------------------------
load_pkgs_runscript <- function(first.time = F, dev = F, plotting = F) {
pkgs <<- c(
"maps",
"rworldmap",
"mapproj",
"vroom", # for loading in CSV files fast
"zoo", # for imputation using `na.approx`
"lestat", # for inverse cumulative distribtuion for depth of deficit (note - also loads the MASS function `select`, so tidyverse needs to be loaded later)
"countrycode", # for working easily with country codes
"readxl", # for reading in excel files
"writexl", # for writing out excel files
"sitools", # for clear unit changes, required by DLE_integration_data_structure.R
"WDI", # World Bank Development indicators package
"table1", # for creating a table with descriptive statistics
"plotly", # for interactive plots
"htmlwidgets", # for saving interactive plots
"here", # for specifying relative paths
"lme4", # for LmList
"tidyverse", # for data wrangling
"logger" # for info (log_info), warnings (log_warn), and debugging (log_debug) -- with the option set in log_threshold, i.e. `log_threshold(TRACE)` to log everything
)
if (dev) {
# add packages only used by code developers
pkgs <- c(pkgs, "styler")
}
if (plotting) {
# add packages only used for plotting (in the plotting gallery)
pkgs <- c(
pkgs,
# "see", # for geom_violinhalf
# "MethylCapSig", # for multivariate lognormal model prediction and sampling
"patchwork", # for multipanel handling
"ggsci", # for some nice colour palettes
"treemapify", # for making treemaps
"scales", # for scaling axes of ggplot objects
# "rgdal", # for transforming map projection to a more reasonable projection method
"rvg", # to make ggplot objects into editable DML objects to write out to powerpoint
"officer" # e.g. to write out plots as editable figures in powerpoint
)
}
if (first.time) {
install.packages(pkgs)
}
load <- lapply(pkgs, library, character.only = TRUE)
select <- dplyr::select # explicitly say that we mean dplyr's select function whenever we use select (not the one from the MASS library...)
filter <- dplyr::filter # explicitly say that we mean dplyr's filter function whenever we use filter (not the one from the stats library...)
mutate <- dplyr::mutate # explicitly say that we mean dplyr's mutate function whenever we use mutate
}
load_pkgs_runscript(first.time = F, dev = T, plotting = T) # for now, we by default always load packages if utils.R is loaded
# Load and initialize DLS dimensions ====
load_dimensions <- function() {
source("DLE_integration_data_structure.R") # integration structure for dimensions
source("DLE_clothing.R")
source("DLE_nutrition.R")
source("DLE_health.R")
source("DLE_water.R")
source("DLE_sanitation.R")
source("DLE_roads.R")
source("DLE_housing.R")
source("DLE_cooling_con.R")
source("DLE_cooling_op.R")
source("DLE_heating_con.R")
source("DLE_heating_op.R")
source("DLE_hotwater_op.R")
source("DLE_appliances.R")
source("DLE_education.R")
source("DLE_transport.R")
}
generate_all_dimensions <- function() {
# NB. currently should follow exactly the function 'AggregateDimensions()'!!
return(
list(
transport = DLE.dimension.transport(
name_dim = "Transport",
indicator = "pkm/cap/year",
unit_rollout = "cap",
grp = c("car", "bus", "rail", "twothree")
),
appliances = DLE.dimension.appliances(
name_dim = "Appliance",
indicator = "unit/hh", # percentage household that have a certain appliance
unit_rollout = "hh", # all of these are considered on a household level
grp = c("clean_cooking_fuel", "television", "mobile_telephone", "refrigerator")
),
water = DLE.dimension.water(
name_dim = "Water",
indicator = "m3/cap/year",
unit_rollout = "cap",
grp = "water"
),
sanit = DLE.dimension.sanit(
name_dim = "Sanitation",
indicator = "cap",
unit_rollout = "cap",
grp = "sanitation"
),
nutrition = DLE.dimension.nutrition(
name_dim = "Nutrition",
unit_rollout = "cap",
indicator = "kcal/day",
grp = "nutrition"
),
clothing = DLE.dimension.clothing(
name_dim = "Clothing",
indicator = "kg/year",
unit_rollout = "cap",
grp = c("clothing", "footwear")
),
health = DLE.dimension.health(
name_dim = "Health",
indicator = "$/cap/year",
unit_rollout = "cap",
grp = "health"
),
education = DLE.dimension.education(
name_dim = "Education",
indicator = "$/cap/year",
unit_rollout = "cap",
grp = c("primary", "lower_secondary")
),
housing = DLE.dimension.housing(
name_dim = "Housing",
indicator = "m2/cap",
unit_rollout = "cap",
grp = c("rural", "urban")
),
heating_con = DLE.dimension.heating_con(
name_dim = "Heating CON",
indicator = "cap",
unit_rollout = "cap",
grp = c("rural", "urban")
),
cooling_con = DLE.dimension.cooling_con(
name_dim = "Cooling CON",
indicator = "cap",
unit_rollout = "cap",
grp = c("rural", "urban")
),
heating_op = DLE.dimension.heating_op(
name_dim = "Heating OP",
indicator = "m2/cap",
unit_rollout = "cap",
grp = c("rural", "urban")
),
cooling_op = DLE.dimension.cooling_op(
name_dim = "Cooling OP",
unit_rollout = "cap",
indicator = "m2/cap",
grp = c("rural", "urban")
),
roads = DLE.dimension.roads(
name_dim = "Roads",
indicator = "km", ## Note: Threshold (road density km/km2) does not have same unit as indicator (km)!!
unit_rollout = "abs",
grp = "roads"
),
hotwater_op = DLE.dimension.hotwater_op(
name_dim = "Hot Water OP",
indicator = "cap",
unit_rollout = "cap",
grp = c("rural", "urban")
# df.input = data.frame(expenditure=3) # Some custom inputs to the dimension (placeholder)
)
)
)
}
# Input data ====
run_initiatialization_input_data <- function(ssp = "SSP2", pov.thres = 20, year.base = 2015) {
# MESSAGE R11 mapping to country iso
message.R11 <<- read_excel(paste0(data.path, "/iso_region_MESSAGE.xlsx")) %>%
mutate(iso = toupper(iso)) %>%
rename(R11.region = `MESSAGE-GLOBIOM`) %>%
select(-RCP_REG) %>%
mutate(iso = ifelse(iso == "ROM", "ROU", iso)) # Typo fix for Romania
# placeholder population - TODO: import SSP population projections and replace this
# pop <- population %>%
# filter(year == 2013) %>% select(-year) %>% # why is this for 2013? The latest year in this R-provided 'population' df
# mutate(iso = countrycode(country, 'country.name', 'iso3c'))
# Population and Urbanization rate
# For now, focus on SSP2
pop <<- read_excel(paste0(data.path, "/iamc_db_SSP_population.xlsx")) %>%
filter(Model == "IIASA-WiC POP", Scenario == ssp) %>%
select(-Variable, -Model, -Scenario) %>%
pivot_longer(cols = `2010.0`:`2100.0`, names_to = "year", values_to = "population") %>%
mutate(year = as.numeric(year), population = population * mega) %>%
select(-Notes, -Unit) %>%
rename(iso = Region)
# Filter countries based on available pop data
message.R11 <<- message.R11 %>% filter(iso %in% unique(pop$iso))
# Urbanization
urbanization <<- read_excel(paste0(data.path, "/iamc_db_SSP_urbanshare.xlsx")) %>%
filter(Scenario == ssp) %>%
select(-Variable, -Model, -Scenario) %>%
pivot_longer(cols = `2010.0`:`2100.0`, names_to = "year", values_to = "urb.rate") %>%
mutate(year = as.numeric(year), urb.rate = urb.rate / 100) %>%
select(-Notes, -Unit) %>%
rename(iso = Region)
# household size data - constant over time
hh_size <<- read.csv(paste0(data.path, "/hh_size.csv"), stringsAsFactors = FALSE)
hh_size <<- message.R11 %>%
left_join(hh_size) %>% # fill NAs
group_by(R11.region) %>%
mutate(hh_size_avg = mean(na.omit(hh_size))) %>%
ungroup() %>%
mutate(hh_size = ifelse(is.na(hh_size), hh_size_avg, hh_size)) %>%
select(-c(country_name, R11.region, hh_size_avg))
# Merge three demographic DFs above
pop <<- message.R11 %>%
left_join(pop) %>%
left_join(urbanization) %>%
left_join(hh_size) %>%
mutate(n_hh = round(population / hh_size)) %>%
mutate(population.urb = population * urb.rate, population.rur = population * (1 - urb.rate)) %>%
select(-c(country_name, R11.region))
# Exchange rate (for EXIO accounting)
usd2eur.baseyr <<- WDI(country = "XC", indicator = "PA.NUS.FCRF", start = year.base, end = year.base)$PA.NUS.FCRF
# poverty headcount closing rate
pov.pop.var <<- paste0("pop_", pov.thres) # Name of the thres variable in the csv input file
pov.gap <<- read.csv(paste0(data.path, "/gdpginipop_povcountdata.csv")) %>%
rename(iso = country) %>%
filter(scenario == ssp, year >= year.base) %>%
select(scenario, iso, year, {{ pov.pop.var }}) %>%
group_by(iso) %>%
left_join(pop %>% select(iso, year, population)) %>%
mutate(pov.pcap = get(pov.pop.var) / population) %>%
mutate(r.closing = pov.pcap / first(pov.pcap)) %>% # gap closing rate index per capita (year.base = 1)
mutate(r.diff = r.closing - lead(r.closing, default = tail(r.closing, 1))) %>% # % difference at each time period
mutate(r.diff = pmax(0, r.diff))
# gdp pathway for GDP-driven (income) scenario pathways
gdp <<- read_csv("P:/ene.general/DecentLivingEnergy/DLE_scaleup/Data/gdp_gini_pop_ssp.csv") %>%
mutate(gdp.pcap = gdp_ppp_2005_bil / pop_mil * 1000) %>%
rename(iso = country) %>%
filter(scenario == ssp) %>%
select(iso, year, gdp.pcap) %>%
drop_na()
# some potentially useful population aggregates
# regional population in base year
R11.pop.baseyr <<- message.R11 %>%
left_join(pop %>% filter(year == year.base)) %>%
select(R11.region, population) %>%
group_by(R11.region) %>%
summarise(population = sum(population))
# regional population
R11.pop <<- message.R11 %>%
left_join(pop) %>%
select(iso, year, R11.region, population) %>%
group_by(R11.region, year) %>%
summarise(population = sum(population))
R11.pop.urbrur <<- message.R11 %>%
left_join(pop) %>%
select(iso, year, R11.region, population, population.urb, population.rur) %>%
group_by(R11.region, year) %>%
summarise(population = sum(population), population.urb = sum(population.urb), population.rur = sum(population.rur))
# # visualise regional population
# ggplot(R11.pop, aes(x=year,y=population)) + geom_line(size=2) + facet_wrap(~R11.region)
# ggplot(R11.pop.urbrur%>% pivot_longer(c(population.urb,population.rur), names_to="population.urbrur"), aes(x=year,y=value, colour=population.urbrur)) + geom_line(size=2) + facet_wrap(~R11.region)
# global population
G.pop <<- R11.pop %>%
group_by(year) %>%
summarise(population = sum(population))
}
# DLS deprivations ====
get_mobility_gap <- function(data.path) {
DLE.transport <- DLE.dimension.transport(
name_dim = "Transport",
indicator = "pkm/cap/year",
unit_rollout = "cap",
grp = c("car", "bus", "rail", "twothree")
)
DLE.transport$DeriveThreshold()
DLE.transport$IdentifyGap()
return(DLE.transport$DF.DLS %>% select(iso, share.pop) %>% distinct(iso, .keep_all = TRUE)) # distinct because it returns for all 4 transport modes, with same share.pop, which is calculated based on the total pkm threshold
}
get_water_gap <- function(data.path) {
fname_water <- "/API_SH.H2O.SMDW.ZS_DS2_en_excel_v2_802993.xls" ## Improved water access
fname_inf_mort <- "/API_SP.DYN.IMRT.IN_DS2_en_excel_v2_992068.xls" ## Infant mortality data
year.base <- 2015 # year for data to be loaded
print("Load data: water")
# Load data: access to water supply
water_acc <- read_excel(paste0(data.path, "/Water", fname_water), sheet = "Data", skip = 3, col_names = TRUE)
water_acc <- water_acc %>%
select_at(c("Country Code", paste(year.base))) %>% # Extract data for the base year
rename_at(paste(year.base), list(~ paste("water_acc"))) %>% # Rename column
mutate(water_acc = water_acc / 100) %>% # Convert % numbers to range 0:1
rename(iso = "Country Code")
# Load data: Infant mortality
mort <- read_excel(paste0(data.path, "/Water", fname_inf_mort), sheet = "Data", skip = 3, col_names = TRUE)
mort <- mort %>%
select_at(c("Country Code", paste(year.base))) %>% # Extract data for the base year
rename_at(paste(year.base), list(~ paste("mort"))) %>%
rename(iso = "Country Code")
# Join data
water_acc <- water_acc %>% # Merge data: water and infant mortality
left_join(mort, by = "iso") %>%
left_join(message.R11, by = "iso") %>% # message region data
select(-c(country_name, R11.region))
# Fit a regression model
print("Regression model: fitting")
lm_water <- lm(water_acc ~ log(mort), data = water_acc)
print(summary(lm_water))
# Extrapolate results
print("Start results extrapolation")
water_extr <- message.R11 %>%
left_join(water_acc, by = "iso") # initialize
water_extr <- water_extr %>%
mutate(water_pred = predict(lm_water, water_extr)) %>% # predicted results
mutate(water_extr = water_pred) %>% # copy predicted results into a new column for extrapolated results
mutate_cond(!is.na(water_acc), water_extr = water_acc) %>% # copy original data, where available
select(iso, R11.region, water_extr) %>% # Keep only iso and extrapolation results
rename(water_access = water_extr)
return(water_extr)
}
get_sanit_gap <- function(data.path) {
fname_sanit <- "/API_SH.STA.SMSS.ZS_DS2_en_excel_v2_804737.xls" ## Improved sanitation data
fname_inf_mort <- "/API_SP.DYN.IMRT.IN_DS2_en_excel_v2_992068.xls" ## Infant mortality data
year.base <- 2015 # year for the gap data loading
# Load data: access to sanit supply
print("Load data")
sanit_acc <- read_excel(paste0(data.path, "/Sanitation", fname_sanit), sheet = "Data", skip = 3, col_names = TRUE)
sanit_acc <- sanit_acc %>%
select_at(c("Country Code", paste(year.base))) %>% # Extract data for the base year
rename_at(paste(year.base), list(~ paste("sanit_acc"))) %>% # Rename column
mutate(sanit_acc = sanit_acc / 100) %>% # Convert % numbers to range 0:1
rename(iso = "Country Code")
# Load data: Infant mortality
mort <- read_excel(paste0(data.path, "/Sanitation", fname_inf_mort), sheet = "Data", skip = 3, col_names = TRUE)
mort <- mort %>%
select_at(c("Country Code", paste(year.base))) %>% # Extract data for the base year
rename_at(paste(year.base), list(~ paste("mort"))) %>%
rename(iso = "Country Code")
# Join data
sanit_acc <- sanit_acc %>% # Merge data: sanitation and infant mortality
left_join(mort, by = "iso") # %>%
# left_join(message.R11, by="iso") %>% # message region data
# select(-country_name)
# Fit a regression model
print("Regression model: fitting")
lm_sanit <- lm(sanit_acc ~ log(mort), data = sanit_acc)
print(summary(lm_sanit))
# Extrapolate results
print("Start results extrapolation")
sanit_extr <- message.R11 %>% left_join(sanit_acc, by = "iso") # initialize
sanit_extr <- sanit_extr %>%
mutate(sanit_pred = predict(lm_sanit, sanit_extr)) %>% # predicted results
mutate(sanit_extr = sanit_pred) %>% # copy predicted results into a new column for extrapolated results
mutate_cond(!is.na(sanit_acc), sanit_extr = sanit_acc) %>% # copy original data, where available
select(iso, R11.region, sanit_extr) %>% # Keep only iso and extrapolation results
rename(sanit_access = sanit_extr)
return(sanit_extr)
}
get_nutri_gap <- function(data.path) {
DLE.nutrition <- DLE.dimension.nutrition(
name_dim = "Nutrition",
indicator = "kcal/day",
grp = "nutrition"
)
DLE.nutrition$DeriveThreshold()
DLE.nutrition$IdentifyGap()
return(DLE.nutrition$DF.DLS %>% select(iso, share.pop))
}
get_edu_gap <- function(data.path) {
method <- "regression"
threshold_prim <- 95 # in %
threshold_ls <- 90 # in %
fname_prim <- "/WorldBank_EducationStatistics_primary.csv" # SE.PRM.CMPT.ZS
fname_ls <- "/WorldBank_EducationStatistics_lowersecondary.csv" # SE.SEC.CMPT.LO.ZS
fname_exp <- "/unesco_govspending_student_cleaned_copiedFromDLE3.csv"
if (method == "regression") {
## read in completion rate files.
education_completion_prim <- read_csv(paste0(data.path, "/Education", fname_prim)) %>%
rename(
iso = CountryCode
) %>%
mutate(grp = "primary") %>%
select(-c(IndicatorCode, IndicatorName, CountryName))
education_completion_ls <- read_csv(paste0(data.path, "/Education", fname_ls)) %>%
rename(
iso = CountryCode
) %>%
mutate(grp = "lower_secondary") %>%
select(-c(IndicatorCode, IndicatorName, CountryName))
### drop rows if not containing enough information and convert to long format
cleanandlong <- function(df_toclean, newvar = "completionrate", years = list(2011, 2012, 2013, 2014, 2015)) {
# drop countries for which there is no data for 2011-2015
df_toclean <- df_toclean[rowSums(is.na(select(df_toclean, as.character(years)))) != ncol(select(df_toclean, as.character(years))), ] # drop all rows where all NA
# drop countries for which there is less than 2 datapoints in the expenditure dataset
IndexMat <- sapply(select(df_toclean, -c(iso)), is.na)
df_toclean <- df_toclean %>% subset(rowSums(!IndexMat) > 2)
# pivot to long
# convert to long format (for regression)
df_clean <- df_toclean %>%
pivot_longer(-c(iso, grp), names_to = "year", values_to = newvar)
df_clean$year <- as.numeric(df_clean$year)
return(df_clean)
}
education_completion_prim <- cleanandlong(education_completion_prim)
education_completion_ls <- cleanandlong(education_completion_ls)
### predict values and return baseyear
predictNAs <- function(df_tofill, var = "completionrate", method = "linear") {
# do regressions per country
if (var == "completionrate") {
if (method == "linear") {
# find intercept and linear regression coefficient
regressions_lin <- lme4::lmList(completionrate ~ year | iso, df_tofill)
}
if (method == "log") {
# find intercept and logarithmic regression coefficient
regressions_log <- lme4::lmList(completionrate ~ log(as.numeric(Year)) | iso, df_tofill)
}
# predict values for the full dataset
df <- df_tofill %>% select(-completionrate)
df$completionratepred <- predict(regressions_lin, newdata = df)
# merge the predicted values if NA, keep the reported values
df_filled <- left_join(df_tofill, df) %>%
mutate(completion_rate = coalesce(completionrate, completionratepred)) %>%
select(-c(completionrate, completionratepred))
}
return(filter(df_filled, year == year.base))
}
education_completion_prim <- predictNAs(education_completion_prim)
education_completion_ls <- predictNAs(education_completion_ls)
}
compl.rate <- left_join(education_completion_prim, education_completion_ls, by = "iso") %>%
select(iso, completion_rate.x, completion_rate.y) %>%
mutate(gap = pmax(0, 100 - pmax(completion_rate.x, completion_rate.y)) / 100) %>%
select(iso, gap)
return(compl.rate)
}
get_housing_gap <- function(data.path) {
fname_slum <- "/API_EN.POP.SLUM.UR.ZS_DS2_en_excel_v2_893267.xls" ## slum population (% of urban)
fname_perm_rur <- "/data_perm_wall_rur.csv" ## pop share with permanent wall (% of rural)
# fname_perm_urb <- "/data_perm_wall_rur.csv" ## pop share with permanent wall (% of urban)
fname_pov <- "/API_SI.POV.UMIC.GP_DS2_en_excel_v2_1002313.xls" ## Data: poverty gap below 5.5$ (WB)
fname_gdp <- "/API_NY.GDP.PCAP.PP.KD_DS2_en_excel_v2_887670.xls" ## Data: GDP 2011 PPP (WB)
year.base <- 2015 # year for data to be loaded
year.slum <- 2014 # year for the slum data (different to ensure data availability)
print("Load data: housing")
# Load data: slum population (% pop)
slum <- read_excel(paste0(data.path, "/Housing", fname_slum), sheet = "Data", skip = 3, col_names = TRUE)
slum <- slum %>%
select_at(c("Country Code", paste(year.slum))) %>% # Extract data for the base year
rename_at(paste(year.slum), list(~ paste("slum"))) %>% # Rename column
mutate(slum = slum / 100) %>% # Convert % numbers to range 0:1
rename(iso = "Country Code")
# Load data: permanent walls in rural (% pop)
perm_rur <- read.csv(paste0(data.path, "/Housing", fname_perm_rur),
stringsAsFactors = FALSE,
header = T
)
perm_rur <- perm_rur %>% rename(perm_rur = share_perm)
# Load data: Poverty gap
pov <- read_excel(paste0(data.path, "/Housing", fname_pov), sheet = "Data", skip = 3, col_names = TRUE)
pov <- pov %>%
select_at(c("Country Code", paste(year.base))) %>% # Extract data for the base year
rename_at(paste(year.base), list(~ paste("pov"))) %>%
rename(iso = "Country Code")
# Join data
housing <- message.R11 %>%
select(iso, R11.region) %>%
left_join(slum, by = "iso") %>% # Merge data: slum pop
left_join(perm_rur, by = "iso") %>% # Permanent walls - rural
# left_join(perm_urb, by = "iso") %>% # Permanent walls - urban
# left_join(gdp, by = "iso") %>% # GDP
left_join(pov, by = "iso") # Poverty
# Fit a regression model (Urban)
print("Regression model: fitting")
lm_hous_urb <- lm(slum ~ pov, data = housing)
print(summary(lm_hous_urb))
# Fit a regression model (Rural)
print("Regression model: fitting")
lm_hous_rur <- lm(perm_rur ~ pov, data = housing)
print(summary(lm_hous_rur))
# Extrapolate results
print("Start results extrapolation")
housing_extr <- housing # initialize
housing_extr <- housing_extr %>%
# urban gap
mutate(gap_urb_pred = predict(lm_hous_urb, housing_extr)) %>% # predicted results
mutate(gap_urb_extr = gap_urb_pred) %>% # copy predicted results into a new column for extrapolated results
mutate_cond(!is.na(slum), gap_urb_extr = slum) %>% # copy original data, where available
# rural gap
mutate(gap_rur_pred = 1 - predict(lm_hous_rur, housing_extr)) %>% # predicted results
mutate(gap_rur_extr = gap_rur_pred) %>% # copy predicted results into a new column for extrapolated results
mutate_cond(!is.na(perm_rur), gap_rur_extr = 1 - perm_rur) %>% # copy original data, where available
select(iso, R11.region, gap_urb_extr, gap_rur_extr) %>% # Keep only iso and extrapolation results
rename(urban = gap_urb_extr) %>%
rename(rural = gap_rur_extr) %>%
gather(key = "grp", value = "gap_perc", c(urban, rural)) %>%
# impose no gaps for developed countries
mutate_cond(R11.region %in% c("NAM", "PAO", "WEU", "EEU"), gap_perc = 0)
# Calculate average gaps by R11.region and urban/rural
housing_reg <- housing_extr %>%
group_by(R11.region, grp) %>%
summarise(gap_perc = mean(na.omit(gap_perc))) %>%
rename(gap_reg_avg = gap_perc)
# Fill in data gaps
housing_extr <- housing_extr %>%
left_join(housing_reg, by = c("R11.region", "grp")) %>%
mutate_cond(is.na(gap_perc), gap_perc = gap_reg_avg) %>%
select(-gap_reg_avg)
# combine urban and rural gaps to get an average gap per capita
housing_extr <- housing_extr %>%
filter(grp == "urban" | grp == "rural") %>%
pivot_wider(names_from = "grp", values_from = "gap_perc") %>%
left_join(pop %>% filter(year == 2015) %>% select(iso, urb.rate)) %>%
mutate(gap = (urban * urb.rate) + (rural * (1 - urb.rate))) %>%
select(iso, gap)
return(housing_extr)
}
get_gaps <- function(data.path, out.path) {
gaps.dls <- vroom(file = file.path(out.path, "DLS_all_gaps.csv")) # input file - get it after running a scenario once.
gaps <- gaps.dls %>% filter(!is.na(gap)) # remove construction dimensions
gaps.transport <- get_mobility_gap(data.path) %>%
mutate(dim = "Transport") %>%
mutate(indicator = "% of population below threshold") %>%
rename(gap = share.pop)
gaps.appliance.cookstove <- gaps %>%
filter(grp == "clean_cooking_fuel") %>%
mutate(gap = ifelse(iso == "CHN",
ifelse(
grp == "clean_cooking_fuel", 0.41,
gap
),
gap
)) %>%
group_by(iso, dim, indicator) %>%
summarise(gap = max(gap)) %>%
mutate(dim = "Clean cooking") %>%
mutate(indicator = "% of population without access")
gaps.appliance.fridge <- gaps %>%
filter(grp == "refrigerator") %>%
mutate(gap = ifelse(iso == "CHN",
ifelse(
grp == "refrigerator", 0,
gap
),
gap
)) %>%
group_by(iso, dim, indicator) %>%
summarise(gap = max(gap)) %>%
mutate(dim = "Cold storage") %>%
mutate(indicator = "% of population without access")
gaps.appliance.television <- gaps %>%
filter(grp == "television") %>%
mutate(gap = ifelse(iso == "CHN",
ifelse(
grp == "television", 0,
gap
),
gap
)) %>%
group_by(iso, dim, indicator) %>%
summarise(gap = max(gap)) %>%
mutate(dim = "Television") %>%
mutate(indicator = "% of population without access")
gaps.appliance.telephone <- gaps %>%
filter(grp == "mobile_telephone") %>%
mutate(gap = ifelse(iso == "CHN",
ifelse(
grp == "mobile_telephone", 0,
gap
),
gap
)) %>%
group_by(iso, dim, indicator) %>%
summarise(gap = max(gap)) %>%
mutate(dim = "Mobile telephone") %>%
mutate(indicator = "% of population without access")
gaps.water <- get_water_gap(data.path) %>%
mutate(dim = "Water access") %>%
mutate(indicator = "% of population below threshold") %>%
mutate(gap = 1 - water_access) %>%
select(iso, dim, indicator, gap)
gaps.sanit <- get_sanit_gap(data.path) %>%
mutate(dim = "Sanitation") %>%
mutate(indicator = "% of population below threshold") %>%
mutate(gap = 1 - sanit_access) %>%
select(iso, dim, indicator, gap)
gaps.nutrition <- get_nutri_gap(data.path) %>%
mutate(dim = "Nutrition") %>%
mutate(indicator = "% of population below threshold") %>%
rename(gap = share.pop) %>%
select(iso, dim, indicator, gap)
# gaps.clothing
# gaps.health
gaps.education <- message.R11 %>%
select(iso) %>%
left_join(get_edu_gap(data.path)) %>%
mutate(dim = "Education") %>%
mutate(indicator = "% of population without 9-yr education") %>%
select(iso, dim, indicator, gap) %>%
mutate(gap = ifelse(
iso == "USA" | iso == "CAN", 0,
ifelse(
iso == "AUS" | iso == "JPN" | iso == "NZL", 0,
gap
)
))
gaps.housing <- get_housing_gap(data.path) %>%
mutate(dim = "Housing") %>%
mutate(indicator = "% of population without decent housing") %>%
select(iso, dim, indicator, gap)
gaps.cooling <- gaps %>% # combine urban and rural gaps to get an average gap per capita
filter(dim == "Cooling CON") %>%
pivot_wider(names_from = "grp", values_from = "gap") %>%
left_join(pop %>% filter(year == 2015) %>% select(iso, urb.rate)) %>%
mutate(gap = (urban * urb.rate) + (rural * (1 - urb.rate))) %>%
mutate(dim = "Cooling") %>%
mutate(indicator = "% of population below threshold") %>%
select(iso, gap, dim, indicator)
gaps.heating <- gaps %>% # combine urban and rural gaps to get an average gap per capita
filter(dim == "Heating CON") %>%
pivot_wider(names_from = "grp", values_from = "gap") %>%
left_join(pop %>% filter(year == 2015) %>% select(iso, urb.rate)) %>%
mutate(gap = (urban * urb.rate) + (rural * (1 - urb.rate))) %>%
mutate(dim = "Heating") %>%
mutate(indicator = "% of population below threshold") %>%
select(iso, gap, dim, indicator)
# gaps.roads
# gaps.hotwater <- gaps %>% # combine urban and rural gaps to get an average gap per capita
# filter(dim=="Hot Water OP") %>%
# pivot_wider(names_from="grp", values_from="gap") %>%
# left_join(pop %>% filter(year==2015) %>% select(iso,urb.rate)) %>%
# mutate(gap=(urban*urb.rate)+(rural*(1-urb.rate))) %>%
# mutate(dim="Hot Water") %>%
# mutate(indicator="% of population below threshold")%>%
# select(iso,gap,dim,indicator)
gaps.all <- bind_rows(list(
gaps.transport %>% mutate(need = "Social", group = "Mobility"),
gaps.appliance.cookstove %>% mutate(need = "Physical", group = "Nutrition"),
gaps.appliance.fridge %>% mutate(need = "Physical", group = "Nutrition"),
gaps.appliance.television %>% mutate(need = "Social", group = "Socialization"),
gaps.appliance.telephone %>% mutate(need = "Social", group = "Socialization"),
gaps.water %>% mutate(need = "Physical", group = "Health"),
gaps.sanit %>% mutate(need = "Physical", group = "Health"),
gaps.nutrition %>% mutate(need = "Physical", group = "Nutrition"),
gaps.education %>% mutate(need = "Social", group = "Socialization"),
gaps.housing %>% mutate(need = "Physical", group = "Shelter"),
gaps.cooling %>% mutate(need = "Physical", group = "Shelter"),
gaps.heating %>% mutate(need = "Physical", group = "Shelter") # ,
# gaps.hotwater %>% mutate(need="Physical", group="Health")
))
gaps.all
return(gaps.all)
}
combine_dls_gaps <- function(data.path, out.path, save.option = c("R11.meanDLS", "R11.DLS", "national.meanDLS", "national.DLS")) {
# TODO: make this function independent from earlier run to produce "DLS_all_gaps.csv"
dls.depr <- get_gaps(data.path, out.path)
if ("national.DLS" %in% save.option) {
write_delim(dls.depr,
file = file.path(out.path, "DLS_deprivations.csv"),
delim = ","
)
}
if ("national.meanDLS" %in% save.option) {
dls.depr.phys.soc <- dls.depr %>%
group_by(iso, need) %>%
summarise(gap = mean(gap, na.rm = TRUE))
dls.depr.phys.soc.agg <- dls.depr %>%
group_by(iso, need) %>%
summarise(gap = mean(gap, na.rm = TRUE)) %>%
group_by(iso) %>%
summarise(gap = mean(gap, na.rm = TRUE))
dls.depr.index <- dls.depr.phys.soc.agg %>%
rename(mean.gap = gap)
write_delim(dls.depr.index,
file = file.path(out.path, "DLS_deprivation_index.csv"),
delim = ","
)
}
if ("R11.DLS" %in% save.option) {
dls.depr.r11 <- dls.depr %>%
left_join(message.R11 %>% select(iso, R11.region)) %>%
left_join(pop %>% filter(year == year.base) %>% select(iso, population)) %>%
group_by(R11.region, dim) %>%
summarise(
gap = weighted.mean(gap, population, na.rm = TRUE)
)
write_delim(dls.depr.r11,
file = file.path(out.path, "DLS_deprivations_R11.csv"),
delim = ","
)
}
if ("R11.meanDLS" %in% save.option) {
dls.depr.phys.soc <- dls.depr %>%
group_by(iso, need) %>%
summarise(gap = mean(gap, na.rm = TRUE))
dls.depr.phys.soc.agg <- dls.depr %>%
group_by(iso, need) %>%
summarise(gap = mean(gap, na.rm = TRUE)) %>%
group_by(iso) %>%
summarise(gap = mean(gap, na.rm = TRUE))
dls.depr.r11 <- dls.depr.phys.soc.agg %>%
left_join(message.R11 %>% select(iso, R11.region)) %>%
left_join(pop %>% filter(year == year.base) %>% select(iso, population)) %>%
group_by(R11.region) %>%
summarise(
gap = weighted.mean(gap, population, na.rm = TRUE)
)
write_delim(dls.depr.r11,
file = file.path(out.path, "DLS_deprivation_index_R11.csv"),
delim = ","
)
}
}
# Running scenarios ====
# Running scenarios: basic scenario steps ====
run_housing <- function(scen = scen) {
# do housing separately, ad-hoc solution
# Initiate an inherited, specific dimension object
DLE.housing <<- DLE.dimension.housing(
name_dim = "Housing",
indicator = "m2/cap",
unit_rollout = "cap",
grp = c("rural", "urban") # ,
# df.input = data.frame(expenditure=3) # Some custom inputs to the dimension (placeholder)
)
DLE.housing$DeriveThreshold()
DLE.housing$IdentifyGap()
DLE.housing$DeriveEnergyIntensity()
DLE.housing$ConstructRolloutScenario(scen)
DLE.housing$UpdateDLE()
if (exists("SAVE.DLE.HOUSING.STOCK")) {
if (SAVE.DLE.HOUSING.STOCK == TRUE) {
housing.stock.timeseries <- DLE.housing$DLE.tot %>%
ungroup() %>%
select(iso, grp, year, stock_new_pcap, stock_old_pcap) %>%
distinct()
# check that there's no duplicates or extra information not captured in the selected columns above
if (
!(nrow(housing.stock.timeseries) == nrow(DLE.housing$DLE.tot %>% ungroup() %>% select(iso, grp, year) %>% distinct()))
) {
stop("Housing stock file that you are saving contains non-unique data. There is more information than is captured in the file.")
} else {
write_delim(
x = housing.stock.timeseries,
file = file.path(out.path, paste0(
ssp, "_",
as.character(year.target),
# "_lct", as.character(lct)), # N.B.: this will lead to a slight naming inconsistency, because others will have lctTRUE/lctFALSE, but comes with the benefit of not having two files with the same information (housing stock is not affected by transport mode convergence).
"_housingstock.csv"
)),
delim = ","
)
}
}
}
}
run_accel_scenario <- function(ssp = "SSP2", year.target = year.target, lct = FALSE) {
# Construct a normative target scenario (ACCEL)
load_dimensions()
# Build a list of dimensions
dim.list <<- generate_all_dimensions()
# Initiate a scenario object - thres/gap/E.int are taken care of here.
DLE.ACCEL <<- DLE.scenario(scenario.name = "ACCEL", dims = dim.list, year.tgt.scen = year.target, lct = lct)
# Create the gap df from all the dims
DLE.ACCEL$CollectAllGap()
# do housing
run_housing(scen = "ACCEL")
# roll out scenario
DLE.ACCEL$SetupRollout(lct = lct)
# get energy intensities
DLE.ACCEL$CallDeriveEnergyIntensity()
# do aggregates.
DLE.ACCEL$SumDLE()
DLE.ACCEL$AggregateRegions()
DLE.ACCEL$AggregateDimensions()
DLE.ACCEL$PlotDLEpcap_ByRegByDim()
DLE.ACCEL$PlotDLEpcap_ByRegByNeed()
DLE.ACCEL$PlotDLEpcap_GlobalByDim()
# we use global DLE.ACCEL here instead of return because we use it as a global object throughout all steps.
}
run_gap_closing_proxy_scenario <- function(ssp, pov.thres) {
# Construct an poverty income gap closing scenario (Income)
load_dimensions()
# Build a list of dimensions
dim.list <<- generate_all_dimensions()
# Initiate a scenario object - thres/gap/E.int are taken care of here.
DLE.income <<- DLE.scenario(scenario.name = "Income", dims = dim.list, year.tgt.scen = Inf)
# Create the gap df from all the dims
DLE.income$CollectAllGap()
# do housing
run_housing(scen = "Income")
# roll out scenario
DLE.income$SetupRollout() # lct would need a target year - for transport, where it's forced to be set to Inf now
# get energy intensities
DLE.income$CallDeriveEnergyIntensity()
# do aggregates.
DLE.income$SumDLE()
DLE.income$AggregateRegions()
DLE.income$AggregateDimensions()
DLE.income$PlotDLEpcap_ByRegByDim()
DLE.income$PlotDLEpcap_ByRegByNeed()
DLE.income$PlotDLEpcap_GlobalByDim()
# we use global DLE.ACCEL here instead of return because we use it as a global object throughout all steps.
}
run_income_crosssection_regression_scenario <- function(ssp, income.indicator) {
# Construct a GDP regression scenario (Income.regression)
load_dimensions()
# Build a list of dimensions
dim.list <<- generate_all_dimensions()
# Initiate a scenario object - thres/gap/E.int are taken care of here.
DLE.income.regression <<- DLE.scenario(scenario.name = "Income.regression", dims = dim.list, year.tgt.scen = Inf) # scenario name, used later in ConstructRolloutScenario
# Create the gap df from all the dims
DLE.income.regression$CollectAllGap()
# do housing
run_housing(scen = "Income.regression") # Called first to prevent thermal comfort (and later hot water) depending on this while not called yet.
# roll out scenario
DLE.income.regression$SetupRollout(lct = lct)
# get energy intensities
DLE.income.regression$CallDeriveEnergyIntensity()
# do aggregates.
DLE.income.regression$SumDLE()
DLE.income.regression$AggregateRegions()
DLE.income.regression$AggregateDimensions()
DLE.income.regression$PlotDLEpcap_ByRegByDim()
DLE.income.regression$PlotDLEpcap_ByRegByNeed()
DLE.income.regression$PlotDLEpcap_GlobalByDim()
# we use global DLE.ACCEL here instead of return because we use it as a global object throughout all steps.
}
# Running scenarios: scenario wrappers for easier use ====
run_accel_scenario_wrapper <- function(ssp = "SSP2", year.target = 2040, lct = FALSE, save.option = c("R11.csvneeds")) {
# run scenario
if (SUPPRESS.DLE.PRINTLOG) {
quiet(
run_accel_scenario(ssp, year.target, lct)
)
} else {
run_accel_scenario(ssp, year.target, lct)
}
# scenario results by dimensions - national
out.df.national <- DLE.ACCEL$DLE.alldims
# scenario results by dimensions - R11
out.df.r11 <- DLE.ACCEL$DLE.alldims.agg
# scenario results aggregated by needs group - R11
out.df.r11.need.aggregation <- DLE.ACCEL$DLE.group.agg
# save.options (style; regional_level.save_format): c("national.csvdims", "R11.csvdims", "R11.csvneeds", "R11.htmldims", "R11.htmlneeds", "global.htmlneeds")
save_options_wrapper(
df.national = out.df.national,
df.r11 = out.df.r11,
df.r11.need.aggregation = out.df.r11.need.aggregation,
save.option = save.option,
save.string = paste0(ssp, "_", as.character(year.target), "_lct", as.character(lct))
)
}
run_income_scenario_wrapper <- function(ssp = "SSP2", pov.thres = 10, save.option = c("R11.csvneeds")) {
# run scenario
run_gap_closing_proxy_scenario(ssp, pov.thres)
# scenario results by dimensions - national
out.df.national <- DLE.income$DLE.alldims
# scenario results by dimensions - R11
out.df.r11 <- DLE.income$DLE.alldims.agg
# scenario results aggregated by needs group - R11
out.df.r11.need.aggregation <- DLE.income$DLE.group.agg
# save.options (style; regional_level.save_format): c("national.csvdims", "R11.csvdims", "R11.csvneeds", "R11.htmldims", "R11.htmlneeds", "global.htmlneeds")
save_options_wrapper(
df.national = out.df.national,
df.r11 = out.df.r11,
df.r11.need.aggregation = out.df.r11.need.aggregation,
save.option = save.option,
save.string = paste0(ssp, "_", as.character(pov.thres))
)
}
run_income_regression_scenario_wrapper <- function(ssp = "SSP2", income.indicator = "log.gdp", save.option = c("R11.csvneeds")) {
run_income_crosssection_regression_scenario(ssp, income.indicator)
# scenario results by dimensions - national
out.df.national <- DLE.income.regression$DLE.alldims
# scenario results by dimensions - R11
out.df.r11 <- DLE.income.regression$DLE.alldims.agg
# scenario results aggregated by needs group - R11
out.df.r11.need.aggregation <- DLE.income.regression$DLE.group.agg
# save.options (style; regional_level.save_format): c("national.csvdims", "R11.csvdims", "R11.csvneeds", "R11.htmldims", "R11.htmlneeds", "global.htmlneeds")