-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSimulated_Sandbox_Notebook.Rmd
1716 lines (1314 loc) · 67.2 KB
/
Simulated_Sandbox_Notebook.Rmd
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
---
title: "DENSIFICAR Project Notebook"
author: Jeremiah J. Nieves
output:
html_document:
toc: true
toc_float: true
toc_collapsed: true
toc_depth: 2
number_sections: true
---
<!-- Note: For formatting, this Notebook requires the bookdown package -->
<!-- Set scrollable code and preview blocks and limit the code window size -->
```{css, include = FALSE, echo = FALSE}
pre {
max-height: 300px;
overflow-y: auto;
}
pre[class] {
max-height: 300px;
}
```
```{r, include = FALSE}
knitr::opts_chunk$set(
collapse = TRUE,
comment = "#>"
)
```
```{r setup, include = FALSE, message = FALSE, warning = FALSE}
options(prompt = 'R> ', continue = '+ ', width = 80)
def.chunk.hook <- knitr::knit_hooks$get("chunk")
knitr::knit_hooks$set(chunk = function(x, options) {
x <- def.chunk.hook(x, options)
ifelse(options$size != "normalsize", paste0("\n \\", options$size,"\n\n", x, "\n\n \\normalsize"), x)
})
require(knitr)
require(sf)
require(spdep)
require(dplyr)
require(raster)
require(fasterize)
require(log4r)
require(data.table)
require(snow)
require(parallel)
require(ggplot2)
require(gridExtra)
require(MASS)
require(tidyr)
root <- "D:/"
prj_dir <- paste0(root,"/Research/Mexico_2021/")
```
```{r common_utility_functions_invisible, include = FALSE, message = FALSE, warning = FALSE}
## Function to make sure directories exist:
ensure_dir <- function(d){
## Function for ensuring that a directory exists and creating it if it does
## not; returns the path of the input path
if (!dir.exists(d)) {
dir.create(d)
}
return(d)
}
## Function to load and or install packages:
package_prep <- function(...){
libs <- unlist(list(...))
## Check if the packages can be loaded and are already installed:
req <- unlist(lapply(libs, require, character.only = TRUE))
## Packages we need to install:
need <- libs[req = FALSE]
if (length(need) > 0) {
## Install the needed packages
install.packages(need)
## Load the just installed packages:
lapply(need, require,character.only = TRUE)
}
}
# Authors: Maksym Bondarenko [email protected]
# Date : October 2017
# Version 0.1
#
#' wpGetOS function will return a string with OS
#' of the system
#' Tested on Windows 10
#' @rdname wpGetOS
#' @return string
wpGetOS <- function(){
sysinf <- Sys.info()
if (!is.null(sysinf)) {
OS <- tolower(sysinf['sysname'])
if (OS == 'windows') {
return('windows')
} else if (OS == 'darwin') {
return('osx')
} else if (OS == 'linux') {
return('linux')
}
} else { ## other OS
OS <- .Platform$OS.type
if (grepl("^darwin", R.version$os))
return('osx')
if (grepl("linux-gnu", R.version$os))
return('linux')
}
}
# Authors: Maksym Bondarenko [email protected]
# Date : October 2017
# Version 0.1
#
#' wpGetAvalMem function will return avalible
#' of the system memory in GB
#' Tested on Windows 10
#'
#' @rdname wpGetAvalMem
#' @return numeric
wpGetAvalMem <- function(){
OS = tolower(wpGetOS())
if (OS == 'windows') {
memavail = shell('wmic OS get FreePhysicalMemory /Value', intern = T)
memavail = memavail[grep('FreePhysicalMemory', memavail)]
memavail = as.numeric(gsub('FreePhysicalMemory=','',memavail))
}else if (OS == 'osx') {
memavail = as.numeric(unlist(strsplit(system("sysctl hw.memsize", intern = T), split = ' '))[2])/1e3
}else{
memavail = as.numeric(system(" awk '/MemTotal/ {print $2}' /proc/meminfo", intern = T))
}
return(memavail / (1024 * 1024))
}
# Authors: Maksym Bondarenko [email protected]
# Date : October 2017
# Version 0.1
#
#' wpGetBlocksNeed function will return a number of blocks
#' sugesting for processing raster file. It will take into consideration
#' number of layers, cells, cores and avalible memory on computer
#' (not maximum memory but avalible)
#' @param x raster
#' @param cores number of cores
#' @param n parameter to increase requrement of the raster
#' @param number_type Will be used to estimate requred memory
#' @rdname wpGetBlocksNeed
#' @return integer
#' @export
#' @examples
#' wpGetBlocksNeed( x, cores=2, n=1 )
#'
wpGetBlocksNeed <- function(x, cores, n=1, number_type = "numeric"){
#stopifnot(hasValues(x))
n <- n + nlayers(x) - 1
cells <- round( 1.1 * ncell(x) ) * n
#memneed <- cells * 8 * n / (1024 * 1024)
if (number_type == "integer") {
byte_per_number = 4
} else if (number_type == "numeric") {
byte_per_number = 8
} else {
#byte_per_number = .Machine$sizeof.pointer
stop(sprintf("Unknown number_type: %s", number_type))
}
blocks <- 1
memneed <- (cells * byte_per_number * n / (1024 * 1024 * 1024))/blocks
memavail <- wpGetAvalMem()/cores
while ((memneed > memavail)) {
memneed <- (cells * byte_per_number * n / (1024 * 1024 * 1024))/blocks
blocks <- blocks + 1
}
if ( blocks < cores) blocks <- cores
return(blocks)
}
## https://github.com/worldpopglobal/wpUtilities/blob/master/R/wpProgressMessage.R
wpProgressMessage <- function(x,
max = 100,
label=NULL) {
if (is.null(label)) label = ''
if (x != max) ar = '>' else ar = ''
percent <- x / max * 100
cat(sprintf('\r[%-50s] %d%% %s',
paste(paste(rep('=', percent / 2), collapse = ''),'',sep = ar),
floor(percent),
label))
if (x == max)
cat('\n')
}
## https://github.com/worldpopglobal/wpUtilities/blob/master/R/wpTimeDiff.R
wpTimeDiff <- function(start, end, frm="hms") {
dsec <- as.numeric(difftime(end, start, units = c("secs")))
hours <- floor(dsec / 3600)
if (frm == "hms" ) {
minutes <- floor((dsec - 3600 * hours) / 60)
seconds <- dsec - 3600*hours - 60*minutes
out = paste0(
sapply(c(hours, minutes, seconds), function(x) {
formatC(x, width = 2, format = "d", flag = "0")
}), collapse = ":")
return(out)
}else{
return(hours)
}
}
# Authors: Maksym Bondarenko [email protected]
# Date : October 2017
# Version 0.1
#
#' wpZonalStatistics function compute zonal statistics. That is,
#' cross-tabulate the values of a Raster* object
#' based on a "zones" RasterLayer. NA values are removed.
#' Function uses DoParallel library to work with a big raster data
#'
#' @param x Raster* object
#' @param y RasterLayer object with codes representing zones
#' @param fun The function to be applied. Either as character: 'mean', 'min', 'max' and 'sum'
#' @param cores Integer. Number of cores for parallel calculation
#' @param minblk Integer. Minimum number of blocks
#' @param na.rm using na.rm = TRUE for missing data
#' @param silent If FALSE then the progress will be shown
#' @rdname wpZonalStatistics
#' @return A data.frame with a value for each zone (unique value in zones)
#' @export
#' @examples
#' wpZonalStatistics( x=rasterObj1, y=rasterObj2, cores=2, minblk=4 )
#'
wpZonalStatistics <- function(x,
y,
fun = 'mean',
cores = NULL,
minblk = NULL,
na.rm = TRUE,
silent = TRUE) {
#chack_pkg_load("raster","doParallel")
fun <- tolower(fun)
if (length(fun) > 1) {
fun <- fun[1]
}
if (!fun %in% c('sum', 'mean', 'sd', 'min', 'max', 'count')) {
stop("fun can be 'sum', 'mean', 'sd', 'min', 'max', or 'count'")
}
# get real physical cores in a computer
max.cores <- detectCores(logical = TRUE)
if (is.null(cores)) {
cores <- max.cores - 1
}
if (cores > max.cores) {
stop(paste0("Number of cores ",
cores,
" more then real physical cores in PC ",
max.cores ))
}
if (is.null(minblk)) {
minblk <- wpGetBlocksNeed(x, cores, n = 1)
}
compareRaster(c(x, y))
stopifnot(hasValues(x))
stopifnot(hasValues(y))
layernames <- names(x)
blocks <- blockSize(x, minblocks = minblk)
tStart <- Sys.time()
cl <- makeCluster(cores)
# broadcast the data and functions to all worker
# processes by clusterExport
# clusterExport(cl, c(x,"y", "blocks"))
registerDoParallel(cl)
result <- foreach(i = 1:blocks$n,
.combine = rbind,
.packages = 'raster') %dopar%
{
df.x <- data.frame( getValues(x,
row = blocks$row[i],
nrows = blocks$nrows[i]) )
df.y <- data.frame( getValues(y,
row = blocks$row[i],
nrows = blocks$nrows[i]) )
if ( fun == 'mean' | fun == 'sd' ) {
df.fun <- aggregate(x = (df.x),
by = list(df.y[,1]),
FUN = function(x, na.rm = TRUE) sum(as.numeric(x),
na.rm = na.rm),
na.rm = na.rm)
df.length <- aggregate(x = (df.x),
by = list(df.y[,1]),
FUN = function(x, na.rm = na.rm) length(stats::na.omit(x)),
na.rm = na.rm)
colnames(df.length) <- c(layernames,'length')
colnames(df.fun) <- c(layernames,'sum')
df <- merge(df.fun, df.length, all = TRUE, by = layernames)
if (fun == 'sd') {
df.sq <- aggregate(x = (df.x^2),
by = list(df.y[,1]),
FUN = function(x, na.rm = TRUE) sum(as.numeric(x),
na.rm = na.rm),
na.rm = na.rm)
colnames(df.sq) <- c(layernames,'sq')
df <- merge(df, df.sq, all = TRUE, by = layernames)
}
} else if ( fun == 'count') {
df <- aggregate(x = (df.x),
by = list(df.y[,1]),
FUN = function(x, na.rm=na.rm) length(stats::na.omit(x)),
na.rm = na.rm)
colnames(df) <- c(layernames,'count')
} else if ( fun == 'sum') {
df <- aggregate(x = (df.x),
by = list(df.y[,1]),
FUN = function(x, na.rm = TRUE) sum(as.numeric(x),
na.rm = na.rm),
na.rm = na.rm)
colnames(df) <- c(layernames,'sum')
} else {
df <- aggregate(x = (df.x),
by = list(df.y[,1]),
FUN = fun,
na.rm = na.rm)
colnames(df) <- c(layernames,fun)
}
return(df)
}
stopCluster(cl)
if ( fun == 'mean' | fun == 'sd') {
df1 <- aggregate(x = result$sum,
by = list(result[[1]]),
FUN = 'sum',
na.rm = na.rm)
df2 <- aggregate(x = result$length,
by = list(result[[1]]),
FUN = 'sum',
na.rm = na.rm)
df1$x <- df1$x / df2$x
if (fun == 'sd') {
df3 <- aggregate(x = result$sq,
by = list(result[[1]]),
FUN = 'sum', na.rm = na.rm)
df1$x <- sqrt(( (df3$x / df2$x) - (df1$x)^2 ) * (df2$x / (df2$x - 1)))
colnames(df1) <- c(layernames, 'sd')
} else{
colnames(df1) <- c(layernames,'mean')
}
} else if ( fun == 'count') {
df1 <- aggregate(x = result[[2]],
by = list(result[[1]]),
FUN = 'sum',
na.rm = na.rm)
colnames(df1) <- c(layernames,'count')
} else if ( fun == 'sum') {
df1 <- aggregate(x = result[[2]],
by = list(result[[1]]),
FUN = function(x, na.rm = TRUE) sum(as.numeric(x),
na.rm = na.rm),
na.rm = na.rm)
colnames(df1) <- c(layernames,'sum')
} else{
df1 <- aggregate(x = result[[2]],
by = list(result[[1]]),
FUN = fun,
na.rm = na.rm)
colnames(df1) <- c(layernames,fun)
}
tEnd <- Sys.time()
if (!silent) print(paste("Elapsed Processing Time:", wpTimeDiff(tStart,tEnd)))
return(df1)
}
```
# Data and Study Area
## Spatial Population Data Preprocessing
The Guadalajara areal population data is rather unique. The urbanised and settled areas, even the smaller settlement agglomerations, are rather detailed, approximating 30m^2^ in some places (Figure 1)[]. These population data are unique for a few reasons besides their high resolution. First, these polygons capture not only city blocks, but in some cases individual buildings. Additionally, there are areas of true zeros such as industrial estates and even large (block length) urban planter boxes. Lastly, these data, within settled areas, do not cover streets, meaning that the polygons within settled areas (of a certain size) are not connected. This is particularly interesting at the more peri-urban interface where these data go from non-connected blocks of buildings to partially or fully connected Thiessen-like polygons. These characteristics present some unique opportunities in terms of modelling structure and data for population modelling. For example, determining if a polygonal area is more or less urbanised (relatively) can be done by looking at the number of first order neighbours they have; if they have one or more, they are peri-urban to more rural and can be then divided into either a urbanised or rural training set. Note, urban and rural are loosely used here to indicate the relative density of settlement and the built environment.
```{r figure_1, echo = FALSE}
knitr::include_graphics("figures/figure_1.png")
```
We initially read in the polygons, removed all features that corresponded to water bodies (field "GUBID_INT" equal to zero), corrected the geometry of all polygons, and rewrote them to file.
```{r clean_census_polygons, eval = FALSE}
input_polygon_path <- paste0(prj_dir,
"gla_admin_shape_csv/",
"gla_admin.shp")
outdir <- paste0(prj_dir, "/Census/")
id_field_name <- "GUBID_INT"
input_polygon <- st_read(input_polygon_path,
stringsAsFactors = FALSE) %>%
filter(GUBID_INT != 0)
valid_geom_table <- table(st_is_valid(input_polygon))
if (valid_geom_table["FALSE"] > 0) {
input_polygon <- st_make_valid(input_polygon)
}
st_write(input_polygon,
paste0(outdir,"MEX_admin_cleaned.shp"),
"MEX_admin_cleaned",
delete_layer = T)
```
We then need to take that cleaned data and expand the polygon boundaries to where they all touch. We accomplish this by expanding the boundaries as we would in the process of defining Thiessen polygons. We do this within \proglang{Python} using the package `momepy` and the morphological tessellation procedure. The cleaned polygons, which had areas of "no data" corresponding to areas covered by streets later served as our validation areas when examining the modelled, gridded population surfaces. The tessellated polygons later served as the input for the creation of the simulated polygons holding population data, which themselves later served as the source areas in our dasymetric disaggregation of counts.
```{python tessellate_settlement_polygons, eval = FALSE, python.reticulate = FALSE}
import geopandas as gpd
import momepy as mm
df = gpd.read_file("/Users/martin/Downloads/MEX_settlement_polygons/MEX_settlement_polygons.shp")
df.crs
df
%time limit = df.buffer(500).unary_union
%time tess = mm.Tessellation(df, 'GUBID_INT', limit=limit, segment=2, shrink=1)
tess.tessellation.to_file("/Users/martin/Downloads/MEX_settlement_tessellation")
tess.tessellation
```
## Input Areal Population Data Descriptives
We'll make some quick descriptive figures of the population data below.
```{r areal_population_desc, message = FALSE, warning = FALSE}
validation_shp_path <- paste0(prj_dir, "Census/MEX_admin_cleaned.shp")
tessel_shp_path <- paste0(prj_dir,
"Census/MEX_admin_cleaned_fully_tessellated_UTM_13N.shp")
validation_shp <- st_read(validation_shp_path)
validation_shp <- validation_shp %>%
mutate(AREA = as.numeric(st_area(validation_shp))) %>%
st_drop_geometry() %>%
dplyr::select(GUBID_INT, AREA) %>%
mutate(DATA = "Validation")
tessel_shp <- st_read(tessel_shp_path)
tessel_shp <- tessel_shp %>%
mutate(AREA = as.numeric(st_area(tessel_shp))) %>%
st_drop_geometry() %>%
dplyr::select(GUBID_INT, AREA) %>%
mutate(DATA = "Tessellated")
area_df <- rbind(validation_shp, tessel_shp)
rm(validation_shp, tessel_shp)
gc()
hist_grob <- ggplot(area_df,
aes(x = log10({AREA/1000000}),
fill = DATA)) +
geom_density(alpha = 0.2) +
coord_cartesian(xlim = c(-5,2)) +
theme_bw() +
labs(x = "Polygon Area (log10(Sq. Km))")
plot(hist_grob)
```
# Methods
## Census Simulation
We wanted to simulate areal population count data that were synthetically degraded in their spatial resolution, i.e. there are less areal units (polygons) covering the same area, and containing the population count equal to the sum of constituent units, with a coarser average spatial resolution. To do so, we decided to quasi-randomly select polygons and merge them with their neighbour that has the least difference in average population density. We say quasi-random as the selection was based upon probabilities defined by an exponential curve over the distribution of polygon areas which made the selection preferentially sample smaller, i.e. more urbanised, polygons for merging. We determined this to be appropriate as the majority of population and polygons are located in urbanised areas and we did not want a scenario where the majority of less densely populated areas, typically characterised by larger polygons, were always aggregated firstly. We determined the scale factor to use in defining the probability curve based upon trial and error and settled on the value of `4` as providing a balanced mix of more densely populated and less densely populated polygons being selected for merging across the entire merging progression. The merging criteria was to minimise the loss in variability of the population density values.
To make sure the simulated aggregation of the polygon-based population count data was both random but replicable, we, randomly, defined 100 random seeds to be used. This meant that for each target level of simulated aggregation, e.g. 95%, 85%, 75%, ..., 15%, 10% of original units, we had 100 different simulated versions. This was done to allow for the creation of bootstrap estimated point estimates and confidence intervals of any error metrics of interest.
The process of sampling and dissolving thousands to tens of thousands of polygons is a surprisingly resource intensive process, which increases with the number of random iterations, i.e. 100, we are doing for each target number of simulated units. We therefore decided to carry out the simulated aggregation procedure in a High Performance Computing (HPC) environment, specifically the Barkla HPC at the University of Liverpool. Like many HPC environments, Barkla uses the Slurm job scheduler to take and execute job submissions. we decided to submit jobs that took several command-line-style arguments that were then passed to the R-based function that was executed by each job. To further speed this process up, we decided to define the job script to allow for arrays of arguments, i.e. a text-based file that defined the command-line-style arguments with one job per line and the arguments separated by whitespace, to be submitted with multiple jobs in a single HPC command.
This meant that we had one flexible *job submission script*, that called upon one *executable R script* that took command-line passed arguments that were retrieved from the line, in the text-based *job list*, corresponding to the *job index*, or indices, submitted in the HPC command. For example, we may have the job submission script `foo_job.sh`, written in \proglang{Bash}, that can take job array indices as inputs and retrieve the corresponding arguments for each sub-job (one per index) from the text-based job list `foo_job_list.txt`. When calling the job submission script in the HPC command, for each sub-job, e.g. `1-10` would have `10` sub-jobs where `1` would have arguments on line `1` of the job list file and so on, the sub-job specific arguments retrieved from the job list would be passed to the executable script `foo_script.R` that would then run with the specified computing resources.
Given that the executable script is set up to run in parallel, this means that we also defined a function to carry out the aggregation subprocess. We therefore have the following nest of processes, from lowest (\proglang{R} individual aggregation subprocess) to highest level (HPC job submission script): aggregation subprocess (`simulate_coarser_units_PARALLEL()`), the \proglang{R}-based executable script (`simulate_aggregate_units_HPC.R`), and the text-based job list (`simulate_aggregate_units_HPC_job_list.txt`) and the corresponding Bash-based job submission script (`simulate_aggregate_units_HPC.sh`). We'll now walk through each of these.
### Polygon simulation - single simulation
As stated, the \proglang{R} executable script runs multiple simulations in parallel using a "task-farm" style setup where each parallel process, i.e. each random seed provided to the script via command arguments, calls the function `simulate_coarser_units_PARALLEL()`. This function takes an input set of input polygons and create a more spatially coarse set of polygons for use in disaggregation modelling testing. Units will be semi-randomly sampled, with smaller units being preferentially selected. Once selected, the selected unit will be aggregated with its neighbouring polygon (queen rule) that has the smallest difference in average population density. This is to minimize the loss of variance in the unit average population densities that later go into the random forest model. Aggregated units retained the unique ID of the selected unit, the populations were summed, and the area and population density will be recalculated prior to the next sampling and aggregation step. This procedure is continued until the desired number of spatial units are met. Units could be aggregated multiple times and all aggregations were recorded in a table prior to a final dissolving based upon identical unique IDs. The initial version of this function dissolved the sampled and merge unit together after every iteration, but this was grossly inefficient. We then decided to record the units in the dataframe and then carry out a single dissolve operation at the end when the number of target units had been reached. This reduced the necessary computation time by around 80%. The only parameter in this function is a task index, relative to the tasks given to the script, which the function is then able to retrieve all of the necessary variables from predefined vectors and or using that index. The variables that are either retrieved by the index or defined from arguments passed to the executable script, for use within the function, correspond to: the random seed, the input polygon path, the output directory, a text-based output tag, the number of target units, the id field name, the population field name, the population density field name, the area field name, the probability scale factor (a constant of `4` for this study), and variables indicating if this is a continuation of previous aggregations. Additionally, a text based log file was written for each task that recorded the merging procedure so that the entire procedure was traceable without needing to rerun the simulation.
If the task was a continuation of previous aggregation runs, e.g. the task in question was to achieve a 15% reduction in total units and the 5 and 10% runs had already been done, the last previous run was used as the input polygon (when `input_polygon_path == "xxx"`) and we "skipped" an equivalent number of random samples so that we were not pulling the same samples in each run.
```{r census_simulation, eval = FALSE}
simulate_coarser_units_PARALLEL <- function(i){
if (seed_skip != 0) {
seed <- seed_list[[i]]
set.seed(seed)
sample(1:seed_skip,seed_skip)
}else{
seed <- seed_list[[i]]
set.seed(seed)
}
if (input_polygon_path == "xxx") {
input_polygon_path <- paste0(previous_directory,
output_name_pattern,
ifelse(output_tag == "" | is.null(output_tag),"",
paste0("_",output_tag)),
"_seed_",seed,
"_scale_",probability_scale_factor,
"_target_", previous_target_units,".shp")
id_field_name <- substr(id_field_name,1,10)
pop_field_name <- substr(pop_field_name,1,10)}
logfile <- paste0(output_directory, "Simulation_INFO_Log",
ifelse(output_tag == "" | is.null(output_tag),"",
paste0("_",output_tag,"_")),
"_seed_",seed,
"_scale_",probability_scale_factor,
"_target_", ifelse(input_polygon_path == "xxx",
previous_target_units,
target_units),
".txt")
log_console_appender <- log4r::console_appender(layout = default_log_layout())
log_file_appender <- log4r::file_appender(logfile, append = TRUE,
layout = default_log_layout())
log_logger <- log4r::logger(threshold = "INFO",
appenders = list(log_console_appender,
log_file_appender))
info(log_logger, paste0("Reading in shapefile from ",input_polygon_path))
in_shp <- st_read(input_polygon_path)
## PRE-CHECKS AND DEFAULT PARAMETER SETTING -----
if (sub(".*LENGTHUNIT\\[\\\"([a-z]*)\\\".*",
"\\1",
grep(".*LENGTHUNIT.*",
strsplit(st_crs(in_shp)$wkt,"\\n")[[1]],
value = TRUE,
perl = TRUE)[1],
perl = TRUE) != "metre") {
stop("Input shapefile is unprojected! Please project the data to a linear unit of metres and retry.")
}
if (is.null(target_units)) {target_units <- ceiling(nrow(in_shp)/3*2)}
info(log_logger, paste0("Starting with ", nrow(in_shp)," spatial units."))
info(log_logger, paste0("No. of target units is ", target_units))
if (is.null(area_field_name) | is.null(pop_density_field_name)) {
info(log_logger," Calculating area for input units...")
area_field_name <- "AREA"
in_shp[,area_field_name] <- 0
in_shp[,area_field_name] <- as.numeric(st_area(in_shp))/1000000
}
if (is.null(pop_density_field_name)) {
info(log_logger, " Calculating population density for input units...")
pop_density_field_name <- "POP_DENS"
in_shp <- in_shp %>%
mutate(!!pop_density_field_name := !!as.name(pop_field_name)/!!as.name(area_field_name))
}
info(log_logger, paste0("Creating simulated aggregation with seed value of ", seed))
info(log_logger," Starting...")
iteration <- 1
foo_shp <- in_shp %>%
mutate(GUBID_INT = as.character(GUBID_INT))
orig_units <- nrow(foo_shp)
shp_df <- st_drop_geometry(foo_shp[,])
while (length(unique(shp_df[,id_field_name])) > target_units) {
info(log_logger, paste0("Overall progress: ",
round({{orig_units - length(unique(shp_df[,id_field_name]))} / {orig_units - target_units} * 100},
digits = 0), "%"))
info(log_logger,
" Calculating sampling probabilities based upon unit area... ")
shp_df <- shp_df %>%
arrange(desc(.data[[area_field_name[[1]]]])) %>%
mutate(SAMPLE_W = 1/{1 + {{.data[[area_field_name[[1]]]] -min(.data[[area_field_name[[1]]]])}/{max(.data[[area_field_name[[1]]]]) - min(.data[[area_field_name[[1]]]])}}}**probability_scale_factor[[1]]) %>%
mutate(SAMPLE_P = SAMPLE_W/sum(SAMPLE_W))
foo_sample_ID <- sample(x = as.character(pull(shp_df, !!id_field_name)),
size = 1,
prob = as.numeric(pull(shp_df, SAMPLE_P)))
info(log_logger, paste0(" Sampling polygon ID: ", foo_sample_ID))
index_sample <- which(as.character(pull(shp_df, !!id_field_name)) == foo_sample_ID)
sampled_popdens <- shp_df %>%
filter(.data[[id_field_name[[1]]]] == foo_sample_ID[[1]]) %>%
pull(.data[[pop_density_field_name[[1]]]]) %>%
as.numeric() %>%
dplyr::first()
sampled_area <- shp_df %>%
filter(.data[[id_field_name[[1]]]] == foo_sample_ID[[1]]) %>%
pull(.data[[area_field_name[[1]]]]) %>%
as.numeric() %>%
dplyr::first()
sampled_population <- shp_df %>%
filter(.data[[id_field_name[[1]]]] == foo_sample_ID[[1]]) %>%
pull(.data[[pop_field_name[[1]]]]) %>%
as.numeric() %>%
dplyr::first()
info(log_logger, " Calculating neighbors... ")
foo_buffer <- foo_shp %>%
filter(.data[[id_field_name[[1]]]] %in% foo_sample_ID) %>%
st_buffer(1) %>%
group_by(.data[[id_field_name[[1]]]]) %>%
summarise(geometry = sf::st_union(geometry)) %>%
ungroup()
foo_neighbors <- foo_shp[unlist(st_intersects(foo_buffer,foo_shp)),] %>%
filter(!(.data[[id_field_name[[1]]]] %in% foo_sample_ID))
info(log_logger,paste0(" Retrieved ", nrow(foo_neighbors),
" neighbors of sampled unit... "))
foo_neighbors <- foo_neighbors %>%
mutate(POP_DEN = abs(.data[[pop_density_field_name[[1]]]] - sampled_popdens[[1]]))
min_diff <- min(foo_neighbors$POP_DEN)
merge_neighbor_ID <- foo_neighbors %>%
filter(POP_DEN == min(POP_DEN)) %>%
dplyr::select(.data[[id_field_name[[1]]]]) %>%
st_drop_geometry() %>%
unlist() %>%
as.character() %>%
unique()
merged_area <- shp_df %>%
filter(.data[[id_field_name[[1]]]] %in% merge_neighbor_ID) %>%
distinct() %>%
pull(.data[[area_field_name[[1]]]]) %>%
as.numeric() %>%
sum(na.rm = TRUE)
merged_population <- shp_df %>%
filter(.data[[id_field_name[[1]]]] %in% merge_neighbor_ID) %>%
distinct() %>%
pull(.data[[pop_field_name[[1]]]]) %>%
as.numeric() %>%
sum(na.rm = TRUE)
merged_popdens <- merged_population/merged_area
info(log_logger, paste0(" Merging polygon ",merge_neighbor_ID,
" with population density of ",merged_popdens,
" and area of ",
merged_area,"... "))
resultant_population <- sampled_population + merged_population
resultant_area <- sampled_area + merged_area
resultant_popdens <- resultant_population/resultant_area
merge_idx <- which(shp_df[,id_field_name] %in% merge_neighbor_ID)
shp_df <- as.data.table(shp_df)
shp_df[get(id_field_name) %in% c(merge_neighbor_ID, foo_sample_ID),
(pop_field_name) := resultant_population]
shp_df[get(id_field_name) %in% c(merge_neighbor_ID, foo_sample_ID),
(area_field_name) := resultant_area]
shp_df[get(id_field_name) %in% c(merge_neighbor_ID, foo_sample_ID),
(pop_density_field_name) := resultant_popdens]
shp_df[get(id_field_name) %in% c(merge_neighbor_ID, foo_sample_ID),
(id_field_name) := foo_sample_ID]
shp_df <- shp_df %>% as.data.frame()
foo_shp[as.numeric(unlist(st_drop_geometry(foo_shp[, id_field_name]))) %in% merge_neighbor_ID,
id_field_name] <- foo_sample_ID
info(log_logger," Recording the merging in the main table... ")
merge_record_for_log <- sprintf(paste0("MERGE RECORD //// ",
"Seed %s // ",
"Iteration %s // ",
"Selected.Unit %s // ",
"Merged.Unit %s // ",
"Selected.AREA %s // ",
"Selected.POP %s // ",
"Selected.POPDENS %s // ",
"Merged.AREA %s // ",
"Merged.POP %s // ",
"Merged.POPDENS %s // ",
"Resultant.AREA %s // ",
"Resultant.POP %s // ",
"Resultant.POPDENS %s"),
seed,
iteration,
ifelse(length(foo_sample_ID) > 1,
paste(foo_sample_ID,
sep = ", ", collapse = ", "),
foo_sample_ID),
ifelse(length(merge_neighbor_ID) > 1,
paste(merge_neighbor_ID,
sep = ", ", collapse = ", "),
merge_neighbor_ID),
sampled_area,
sampled_population,
sampled_popdens,
ifelse(length(merged_area) > 1,
paste(merged_area,
sep = ", ", collapse = ", "),
merged_area),
ifelse(length(merged_population) > 1,
paste(merged_population,
sep = ", ", collapse = ", "),
merged_population),
ifelse(length(merged_popdens) > 1,
paste(merged_popdens,
sep = ", ", collapse = ", "),
merged_popdens),
resultant_area,
resultant_population,
resultant_popdens)
info(log_logger, merge_record_for_log)
iteration <- iteration + 1
rm(foo_buffer, foo_neighbors)
gc()
}
info(log_logger," Dissolving geometries and merging data back into the sf object... ")
duplicated_ids_logical <- foo_shp %>%
pull(.data[[id_field_name[[1]]]]) %>%
duplicated()
duplicated_ids <- pull(foo_shp, .data[[id_field_name[[1]]]])[duplicated_ids_logical]
shp_df_mergeable <- shp_df %>%
select(-c(SAMPLE_W,SAMPLE_P)) %>%
distinct()
dissolved_shp <- foo_shp %>%
filter(.data[[id_field_name[[1]]]] %in% duplicated_ids) %>%
group_by(.data[[id_field_name[[1]]]]) %>%
summarise(geometry = sf::st_union(geometry)) %>%
ungroup() %>%
left_join(shp_df_mergeable, by = id_field_name)
foo_shp <- foo_shp %>%
filter(!(.data[[id_field_name[[1]]]] %in% unique(shp_df[duplicated(shp_df[,id_field_name]),id_field_name]))) %>%
rbind(dissolved_shp)
output_name <- paste0(output_name_pattern,
ifelse(output_tag == "" | is.null(output_tag),"",
paste0("_",output_tag,"_")),
"_seed_",seed,
"_scale_",probability_scale_factor,
"_target_",target_units,".shp")
info(log_logger,
paste0(" Writing shapefile to ",
output_directory,output_name))
st_write(foo_shp,
dsn = paste0(output_directory,output_name),
layer = strsplit(output_name,".shp")[[1]],
delete_layer = TRUE)
print("")
print("")
info(log_logger,
" Simulation COMPLETE! ")
}
```
### Polygon simulation - task farm
We now define our cluster task farm, command passed argument handling, and defining of fixed variables within the `simulate_aggregate_units_HPC.R` script. This script handles the input command arguments passed to the script by the job submission script, which retrieves the values from the job list. The main directory paths are hard coded as well as some other user defined parameters that are likely to be project specific and not change much. This could be shifted to the job list at some point, but would drastically expand the number of command arguments that need to be handled and passed for each job. We also source our `simulate_coarser_units_PARALLEL()` function during this script as well. Importantly, we have hard coded our random seeds within this script, which could be reworked in the future to be declared within the job list arguments as well.
```{r simulate_aggregate_units_HPC, eval = FALSE}
## COMMANDLINE ARGUMENT RETRIEVAL --------------------------------------------
args <- commandArgs(trailingOnly = TRUE)
target_units <- as.numeric(eval(parse(text = args[1])))
input_polygon_path <- sub('`(/.*[.]shp)`|(xxx)',
"\\1",
as.character(parse(text = args[2])),
perl = TRUE)
seed_indices <- seq(as.numeric(eval(parse(text = args[3]))),
as.numeric(eval(parse(text = args[4]))),
by = 1)
previous_target_units <- as.numeric(eval(parse(text = args[5])))
if (input_polygon_path == "xxx") {
seed_skip <- as.numeric(eval(parse(text = args[6])))}else{seed_skip <- 0}
cluster_workers <- as.numeric(eval(parse(text = args[7])))
## USER DEFINED PARAMETERS ---------------------------------------------------
hpc_root <- "/mnt/lustre/users/jjniev01/"
hpc_prj_dir <- paste0(hpc_root,"Research/Mexico_2021/")
source(paste0(hpc_prj_dir, "repo/DENSIFICAR/accessory/create_aggregate_test_units_PARALLEL_optimised.R"))
## Declare our hardcoded input values ----------------------------------------
output_directory <- paste0(hpc_prj_dir,
"Output/")
previous_directory <- paste0(hpc_prj_dir, "Census/Simulated/")
temporary_directory <- paste0(hpc_prj_dir,"tmp/")
output_name_pattern <- "MEX_admin_SIMULATED_Aggregation"
output_tag <- ""
overwrite <- TRUE
id_field_name <- "GUBID_INT"
pop_field_name <- "P2010"
pop_density_field_name <- NULL
area_field_name <- NULL
probability_scale_factor <- 4
##### ------- NOTHING BELOW HERE NEEDS TO BE CHANGED REGULARLY ------- #####
seed_list_master <- list(1244621,16542,343433,23574,23463,
44930,2345335,789211,1123,15550,
66503,78328,86937,16522,35699,
72550,765,11240,37511,99567,
2347,76866,69844,7684,3345,
88795,86732,12559,7693,6589,
65318, 9937,7646,881366,2388,
86443,76445,19873,29875,634529,
76329,48194,7459,357661,88353,
6583,339875,856334,24623,19640122,
853201,83535,74594,112994,322223,
274,85375,9189,8832,85732,
88233,75559,738412,28334,89553,
90045,23228,26535,876409,345992,
255,46677,749322,86355,27532,
5567,344465,85766,264891,183332,
8602,34855,86323,869345,12332,
86304,6623,8604,28563,68921,
873452,2863,96782,28953,76514,
849664,46658,55671,89934,907902)
seed_list <- seed_list_master[[seed_indices]]
if (input_polygon_path == "xxx") {
input_polygon_path <- paste0(previous_directory,
output_name_pattern,
## Output tag if it exists
ifelse(output_tag == "" | is.null(output_tag),"",
paste0("_",output_tag)),
## basic info on the simulation to include in the file name:
"_seed_",seed,
"_scale_",probability_scale_factor,
"_target_", previous_target_units,".shp")
id_field_name <- substr(id_field_name,1,10)
pop_field_name <- substr(pop_field_name,1,10)
}
sprintf("Values that have been retrieved from the command arguments in R:")
sprintf("Target Units: %s", target_units)
sprintf("Input Polygon Paths: %s", input_polygon_path)
sprintf("Seed Indices: %s", seed_indices)
sprintf("Previous Target Units: %s",previous_target_units)
sprintf("Seed Skip: %s",seed_skip)
sprintf("Cores: %s---",cluster_workers)