-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy path5b_GTD_Prj03v4_Analysis_StudyAreaExtent_v2.R
executable file
·646 lines (520 loc) · 28.9 KB
/
5b_GTD_Prj03v4_Analysis_StudyAreaExtent_v2.R
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
################### TABULATE AND MAP GTD EXTENTS ##################
#
# Daniel Schlaepfer, 2015-2016
#
# Calculate, tabulate, and map extents temperate dryland areas with
# all study_areas_and_shifts x RCP combinations
# - 'done_studyareaextents' will be stored as flag indicate whether this script has successfully completed
# - requests 'get_precalculations' from '5a1_GTD_*.R'
#
###################################################################
#-------------------------------
#---GLOBAL SETTINGS
comp <- "dropbox"
do_extent <- FALSE
do_tables <- FALSE
do_maps <- TRUE
map_inset_version <- "v0" # no histogram; relative areal contributions
map_inset_version <- "v1" # expanding agreement: white - blue color gradient
map_inset_version <- "v2" # expanding agreement: light blue - dark blue color gradient
map_inset_version <- "v3" # expanding agreement: sky blue - dark blue color gradient
do_climatezones <- FALSE
#-------------------------------
#---R packages
pkg_reqd <- c("geosphere", "rgeos", "digest", "reshape2")
has_loaded <- sapply(pkg_reqd,
function(lib) require(lib, character.only = TRUE, quietly = FALSE))
stopifnot(has_loaded)
#---Load data and misc. functions
if (comp %in% c("err", "eleos")) {
dir.gtd <- "/PATH_TO_PROJECT/Product_PowellCenter/6_Projects_Year1"
} else if (comp == "dropbox") {
dir.gtd <- "/PATH_TO_PROJECT/Product_PowellCenter/6_Projects_Year1"
}
dir.prj <- file.path(dir.gtd, "Prj03_GlobalVulnerability", "4_Analysis", "4_Analysis_v4")
get_precalculations <- TRUE
source(file.path(dir.prj, "5a1_GTD_Prj03v4_Helper.R"))
stopifnot(done_precalculations)
#---Directories
dir.create(dir.out_SA <- file.path(dir.sim_out, "StudyArea_Extent"), showWarnings = FALSE)
dir.create(dir.fig_SA <- file.path(dir.prj, "6_Results", "1_StudyArea"), showWarnings = FALSE)
dir.create(dir.fig_SA1 <- file.path(dir.fig_SA, "Maps"), showWarnings = FALSE)
dir.create(dir.fig_SA2 <- file.path(dir.fig_SA, "Shifted_and_Attribution"), showWarnings = FALSE)
dir.create(dir.fig_SA3 <- file.path(dir.fig_SA, "Tables"), showWarnings = FALSE)
dir.create(dir.cache <- file.path(dir.out_SA, "cache"), showWarnings = FALSE)
#-------------------------------
#------CALCULATE GEOGRAPHIC EXTENTS
if (do_extent) {
#- Load data
load(file.path(dir.sim_out, "PreCalculations", paste0("dShift2_Attribution_", tag_dbScen, ".RData")))
sa_names_att2 <- c(sa_names_def2, "dShift2_AI05", "dShift2_AI005", "dShift2_D", "dShift2_MAT0", "dShift2_Sand90")
#sa_names_att_ranks2 <- paste0(sa_names_att2, "_ranks")
masks_regions <- load_regional_masks(dir.gis = file.path(dir.gis, "CurrentFuture"), pattern = "Global")
m2_to_km2 <- 1e-6
cols1 <- c("orange", "darkgreen", "cyan", "purple", "pink")
cols2 <- c("red", "gray", "blue")
#- Main function
calc_extents <- function(dStudy, dShift, names_attshifts, reqScenarios1, reqScenarios2, plot = FALSE) {
#str(dStudy2): num [1:5, 1:3, 1:17, 1:20021] NA NA NA NA NA NA NA NA NA NA ...
# - attr(*, "dimnames") = List of 4
# ..$ : chr [1:5] "MetDef_Any17Cond" "MetDef_ThisCond" "trailing" "stable" ...
# ..$ : chr [1:3] "Current" "RCP45" "RCP85"
# ..$ : chr [1:17] "Current" "CanESM2" "CESM1-CAM5" "CSIRO-Mk3-6-0" ...
# ..$ : NULL
att_tag <- sapply(strsplit(names_attshifts, split = "_", fixed = TRUE), function(x) x[2])
resps <- c("Study_km2", "Study_relCur", paste0("DueTo", att_tag))
resExtent <- array(0, dim = c(length(study_areas_and_shifts), length(reqScenarios1), length(reqScenarios2), length(regions_N), length(resps)),
dimnames = list(study_areas_and_shifts, reqScenarios1, reqScenarios2, paste0("Region", regions_N), resps))
#Load data
if (all(grepl("ranks", names_attshifts))) {
attShifts <- sapply(names_attshifts, function(x) load(file.path(dir.sim_out, "PreCalculations", paste0(x, "_", tag_dbScen, ".RData")), envir = .GlobalEnv))
} else {
load(file.path(dir.sim_out, "PreCalculations", paste0("dShift2_Attribution_", tag_dbScen, ".RData")))
attShifts <- names_attshifts
}
for (ia in seq_along(study_areas_and_shifts)) {
if (study_areas_and_shifts[ia] == "MetDef_ThisCond") {
reqScenarios1mod <- reqScenarios1
} else {
reqScenarios1mod <- if (reqScenarios1[1] == currentSc) reqScenarios1[-1] else reqScenarios1
}
if (study_areas_and_shifts[ia] %in% study_areas_v4) {
reqScenarios2mod <- reqScenarios2
} else {
reqScenarios2mod <- if (reqScenarios2[1] == currentSc) reqScenarios2[-1] else reqScenarios2
}
for (isc1 in seq_along(reqScenarios1mod)) {
for (isc2 in seq_along(reqScenarios2mod)) {
tempAtt <- tempAttr <- list()
dg <- digest(list(dStudy, dShift, names_attshifts, as.integer(ia), reqScenarios1mod[isc1], reqScenarios2mod[isc2], 1L)) #http://gforge.se/2015/02/how-to-go-parallel-in-r-basics-tips/#Caching
cache_fn <- file.path(dir.cache, sprintf("Cache1_%s.Rdata", dg))
if (file.exists(cache_fn)) {
load(cache_fn)
} else {
# study area raster
tempSA <- calc.RasterFromData(Xcoord = dLoc$X_WGS84, Ycoord = dLoc$Y_WGS84, dataVector = dStudy[study_areas_and_shifts[ia], reqScenarios1mod[isc1], reqScenarios2mod[isc2], ], mask = mask_simulation)
# raster of causes for trailing and leading zones
if (all(!(reqScenarios1mod[isc1] == currentSc), cellStats(tempSA, 'sum') > 0, study_areas_and_shifts[ia] %in% c("trailing", "leading"))) {
for (iatt in seq_along(attShifts)) {
stemp <- get(attShifts[iatt])
# - "trailing": of interest is: cause of study area trailing zone, i.e., -1 in scenario data within trailing zone
# - "leading": of interest is: cause of study area leading zone, i.e., +1 in scenario data within leading zone
if (any(dimnames(stemp)[[1]] %in% shifts)) {
temp <- ifelse(!is.na(stemp[study_areas_and_shifts[ia], reqScenarios1mod[isc1], reqScenarios2mod[isc2], ]), 1, NA)
} else {
temp <- ifelse(!is.na(stemp[reqScenarios1mod[isc1], reqScenarios2mod[isc2], , study_areas_and_shifts[ia]]), 1, NA)
}
tempAtt[[iatt]] <- calc.RasterFromData(Xcoord = dLoc$X_WGS84, Ycoord = dLoc$Y_WGS84, dataVector = temp, mask = mask_simulation)
tempAtt[[iatt]] <- mask(tempAtt[[iatt]], tempSA)
}
# check that overlay of causes match up with entire trailing resp. leading zone
temp <- overlay(tempAtt[[1]], tempAtt[[2]], tempAtt[[3]], tempAtt[[5]], tempAtt[[5]], function(c1, c2, c3, c4, c5) ifelse(!is.na(c1) | !is.na(c2) | !is.na(c3) | !is.na(c4) | !is.na(c5), 1, NA))
stopifnot(cellStats(overlay(tempSA, temp, function(x, y) ifelse(x == y, 0, NA)), 'sum') == 0)
}
#Cache
save(tempSA, tempAtt, file = cache_fn)
}
if (cellStats(tempSA, 'sum') > 0) {
res <- matrix(NA, nrow = length(regions_N), ncol = length(resps), dimnames = list(regions_N, resps))
dg <- digest(list(dStudy, dShift, names_attshifts, as.integer(ia), reqScenarios1mod[isc1], reqScenarios2mod[isc2], 2L))
cache_fn <- file.path(dir.cache, sprintf("Cache2_%s.Rdata", dg))
if (file.exists(cache_fn)) {
load(cache_fn)
} else {
for (igr in seq_along(regions_N)) {
tempSAr <- mask(tempSA, masks_regions[[igr]])
if (cellStats(tempSAr, 'sum') > 0) {
res[igr, "Study_km2"] <- m2_to_km2 * areaPolygon(rasterToPolygons(tempSAr, dissolve = TRUE))
if (!(reqScenarios2mod[isc2] == currentSc) && reqScenarios2[1] == currentSc) {
ia_temp <- if (study_areas_and_shifts[ia] %in% study_areas_v4) study_areas_and_shifts[ia] else "MetDef_ThisCond"
irow1 <- if (ia_temp == "MetDef_ThisCond") currentSc else reqScenarios1mod[isc1]
res[igr, "Study_relCur"] <- res[igr, "Study_km2"] / resExtent[ia_temp, irow1, currentSc, igr, "Study_km2"]
}
if (study_areas_and_shifts[ia] %in% c("trailing", "leading")) {
for (iatt in seq_along(attShifts)) {
tempAttr[[iatt]] <- mask(tempAtt[[iatt]], masks_regions[[igr]])
icol <- paste0("DueTo", strsplit(attShifts[iatt], "_")[[1]][2])
if (cellStats(tempAttr[[iatt]], 'sum') > 0) res[igr, icol] <- m2_to_km2 * areaPolygon(rasterToPolygons(tempAttr[[iatt]], dissolve = TRUE))
}
}
print(paste(Sys.time(), study_areas_and_shifts[ia], reqScenarios1mod[isc1], reqScenarios2mod[isc2], label.regions[igr], paste(round(res[igr, ], 1), resps, collapse = ", "), sep = ", "))
if (plot && !(reqScenarios1mod[isc1] == currentSc) && study_areas_and_shifts[ia] %in% c("trailing", "leading")) {
temp1 <- trim(tempSAr)
if (nrow(temp1) > 1 || packageVersion("raster") > "2.3.40") {
pdf(height = 2*6, width = 4*6, file = file.path(dir.fig_SA2, paste0("Fig_", study_areas_and_shifts[ia], "_", reqScenarios1mod[isc1], "_", reqScenarios2mod[isc2], "_", label.regions[igr], ".pdf")))
op <- par(mfcol = c(2, 4))
image(temp1, maxpixels = ncell(temp1), asp = 1, col = "darkgray")
image(tempSA, maxpixels = ncell(tempSA), col = adjustcolor(cols2, alpha.f = 0.3), add = T)
title(main = paste(study_areas_and_shifts[ia], reqScenarios1mod[isc1], reqScenarios2mod[isc2], label.regions[igr]))
image(temp1, maxpixels = ncell(temp1), asp = 1, col = "gray")
title(main = "Attribution")
for (iatt in seq_along(attShifts)) if (cellStats(tempAttr[[iatt]], 'sum') > 0) image(tempAttr[[iatt]], maxpixels = ncell(tempAttr[[iatt]]), col = adjustcolor(cols1[iatt], alpha.f = 0.3), add = T)
legend("bottomleft", legend = att_tag, col = cols1, pch = 15, pt.cex = 2)
for (iatt in seq_along(attShifts)) {
image(temp1, maxpixels = ncell(temp1), asp = 1, col = "gray")
title(main = paste("Shifts in factor", attShifts[iatt]))
stemp <- get(attShifts[iatt])
for (ish in seq_along(shifts)) {
if (any(dimnames(stemp)[[1]] %in% shifts)) {
temp <- ifelse(!is.na(stemp[shifts[ish], reqScenarios1mod[isc1], reqScenarios2mod[isc2], ]), 1, NA)
} else {
temp <- ifelse(!is.na(stemp[reqScenarios1mod[isc1], reqScenarios2mod[isc2], , shifts[ish]]), 1, NA)
}
temp3 <- calc.RasterFromData(Xcoord = dLoc$X_WGS84, Ycoord = dLoc$Y_WGS84, dataVector = temp, mask = mask_simulation)
image(temp3, maxpixels = ncell(temp3), col = adjustcolor(cols2[ish], alpha.f = 0.3), add = T)
}
}
par(op)
dev.off()
}
}
}
}
#Cache
save(res, file = cache_fn)
}
resExtent[ia, reqScenarios1mod[isc1], reqScenarios2mod[isc2], , ] <- res
}
}
}
}
return(resExtent)
}
# 1) Calculate area extents and attribution for each GCM
if (!file.exists(ftemp <- file.path(dir.out_SA, paste0("resExtent2_", tag_dbScen, ".RData")))) {
resExtent2 <- calc_extents(dStudy = dStudy2, dShift = dShift2, names_attshifts = sa_names_att2[-(1:2)], reqScenarios1 = reqRCPs_wCur, reqScenarios2 = reqGCMs_wCur, plot = TRUE)
save(resExtent2, file = ftemp)
} else {
load(ftemp)
}
# 2) Calculate ranks across GCM aggregations
if (!file.exists(ftemp <- file.path(dir.out_SA, paste0("resExtent2_ranks_", tag_dbScen, ".RData")))) {
ndim <- dim(resExtent2)
ndim[3] <- 1 + length(ranks)
ndimnames <- dimnames(resExtent2)
ndimnames[[3]] <- c(currentSc, paste0("rank", ranks))
resExtent2_ranks <- array(NA, dim = ndim, dimnames = ndimnames)
resExtent2_ranks[, , currentSc, , ] <- resExtent2[, , currentSc, , ]
temp <- apply(resExtent2[, -1, -1, , ], MARGIN = c(1:2, 4:5), calc_ensemble4) #larger area -> less agreement
for (ir in seq_along(ranks)) {
resExtent2_ranks[, -1, paste0("rank", ranks[ir]), , ] <- temp[ir, , , , ]
}
save(resExtent2_ranks, file = ftemp)
} else {
load(ftemp)
}
}
if (do_climatezones && exists("resTempAir2")) {
#Test that both resTempAir2 and resDefintion2 have same coverage
ctemp <- which(is.na(apply(resTempAir2, 1:4, sum)) == !is.na(resDefinition2[, , , , "TrewarthaD_Normals_TF_mean"]))
stopifnot(length(ctemp) == 0)
res_trewartha <- array(NA, dim = dim(resTempAir2)[2:4], dimnames = dimnames(resTempAir2)[2:4])
iarea <- "Simulation" # "Simulation", "MetDef_Any17Cond", "MetDef_ThisCond", "trailing", "leading
for (ircp in seq_along(reqRCPs_wCur)) {
reqGCMs_wCur2 <- if (reqRCPs_wCur[ircp] == "Current") reqGCMs_wCur[1] else reqGCMs_wCur[-1]
for (igcm in seq_along(reqGCMs_wCur2)) {
#Trewartha, G.T. & Horn, L.H. (1980). An introduction to climate. 5th edn. McGraw-Hill, New York.
# - tropical: sum(Tmonth >= 18) == 12
# - subtropical: sum(Tmonth >= 10) >= 8 && sum(Tmonth >= 18) < 12
# - temperate: sum(Tmonth >= 10) >= 4 && sum(Tmonth >= 10) < 8
# - boreal: sum(Tmonth >= 10) > 0 && sum(Tmonth >= 10) < 4
dat <- resTempAir2[iarea, reqRCPs_wCur[ircp], reqGCMs_wCur2[igcm], , ]
temp_tropical <- apply(dat[1:2, ], 1, function(x) sum(x >= 18) == 12)
temp_subtropical <- apply(dat, 1, function(x) sum(x >= 10) >= 8 & sum(x >= 18) < 12)
temp_temperate <- apply(dat, 1, function(x) {temp <- sum(x >= 10); temp >= 4 & temp < 8})
temp_boreal <- apply(dat, 1, function(x) {temp <- sum(x >= 10); temp > 0 & temp < 4})
testD <- resDefinition2[iarea, reqRCPs_wCur[ircp], reqGCMs_wCur2[igcm], , "TrewarthaD_Normals_TF_mean"]
if (!(sum(which(temp_temperate) %in% which(testD == 1)) == sum(temp_temperate, na.rm = TRUE)))
stop(paste(ircp, igcm, reqRCPs_wCur[ircp], reqGCMs_wCur2[igcm], sum(temp_temperate, na.rm = TRUE), sum(which(temp_temperate) %in% which(testD == 1))))
if (sum(temp_tropical, na.rm = TRUE) > 0) res_trewartha[reqRCPs_wCur[ircp], reqGCMs_wCur2[igcm], temp_tropical] <- "tropical"
if (sum(temp_subtropical, na.rm = TRUE) > 0) res_trewartha[reqRCPs_wCur[ircp], reqGCMs_wCur2[igcm], temp_subtropical] <- "subtropical"
if (sum(temp_temperate, na.rm = TRUE) > 0) res_trewartha[reqRCPs_wCur[ircp], reqGCMs_wCur2[igcm], temp_temperate] <- "temperate"
if (sum(temp_boreal, na.rm = TRUE) > 0) res_trewartha[reqRCPs_wCur[ircp], reqGCMs_wCur2[igcm], temp_boreal] <- "boreal"
}
}
table(res_trewartha)
#Simulation
# boreal subtropical temperate
# 39823 89793 518678
#MetDef_Any17Cond
# boreal subtropical temperate
# 4942 75442 284217
#MetDef_ThisCond
#temperate
# 243421
#trailing
#subtropical temperate
# 72613 13751
#leading
#temperate
# 24667
ircp <- igcm <- 1
dat <- res_trewartha[reqRCPs_wCur[ircp], reqGCMs_wCur[igcm], ]
table(dat)
#Simulation
# boreal subtropical temperate
# 2210 42 16679
#MetDef_Any17Cond x RCP45
# boreal subtropical temperate
# 176 1204 9500
#MetDef_Any17Cond x RCP85
# boreal subtropical temperate
# 204 2561 9155
#MetDef_ThisCond
#temperate
# 9246
#- Map
library(maps)
ips <- list(c(ircp = 1, igcm = 1), c(ircp = 2, igcm = 2), c(ircp = 3, igcm = 2), c(ircp = 3, igcm = 17))
pdf(height = 8, width = 12, file = file.path(dir.fig_SA1, "Map_ClimateZones_SimulationExtent.pdf"))
op <- par(mfrow = c(2, 2), mar = c(2, 2, 1, 0.5), mgp = c(2, 0.5, 0))
for (ip in seq_along(ips)) {
dat <- res_trewartha[reqRCPs_wCur[ips[[ip]]["ircp"]], reqGCMs_wCur[ips[[ip]]["igcm"]], ]
dat <- factor(dat, levels = cz <- c("tropical", "subtropical", "temperate", "boreal"))
temp <- calc.RasterFromData(dLoc$X_WGS84, Ycoord = dLoc$Y_WGS84, dataVector = dat, mask = mask_simulation)
temp[1:4] <- 1:4
raster::image(temp, col = cols <- c("green", "orange", "gray", "blue"), asp = 1)
map(add = TRUE)
if (ip == 1) legend(x = "bottomright", bg = "white", pch = 16, legend = cz, col = cols)
title(main = paste(reqRCPs_wCur[ips[[ip]]["ircp"]], reqGCMs_wCur[ips[[ip]]["igcm"]]))
}
par(op)
dev.off()
}
#-------------------------------
#------WITHIN TEXT RESULTS: GEOGRAPHIC EXTENT AND SHIFTING ZONES
if (do_tables) {
temp_dat <- resExtent2[shifts, -1, -1, , "Study_km2"]
temp_diff <- temp_dat["leading", , , ] - temp_dat["trailing", , , ]
temp_cur_reg <- resExtent2["MetDef_ThisCond", currentSc, currentSc, , "Study_km2"]
#-Extent of study area under current conditions in km2 and % of global terrestrial surface
extent_current_km2 <- sum(temp_cur_reg)
# 8295146 km2
GlobalTerrestrialSurface <- 148940000 # km2 from http://en.wikipedia.org/wiki/Earth; TODO: find better reference
antartica <- 14000000 #https://en.wikipedia.org/wiki/Antarctica
extent_current_PercentageOfGlobalTerrestrialSurface <- round(100 * extent_current_km2 / GlobalTerrestrialSurface, 2)
# 5.57%
#---Feng, S., and Q. Fu. 2013. Expansion of global drylands under a warming climate. Atmospheric Chemistry and Physics 13:10081-10094.
extent_current_dryland_global_km2 <- 60.9 * 1e6 # Fig. 3a, mean 1961-1990
extent_current_dryland_global_km2 / GlobalTerrestrialSurface #0.4088895
extent_current_aridandsemiarid_global_km2 <- (22 + 19.1) * 1e6 # Fig. 3c,d, mean 1961-1990
extent_current_km2 / extent_current_aridandsemiarid_global_km2 # 0.2018284
extent_futureRCP85_aridandsemiarid_global_change_relative <- (2.1 + 1.8) * 1e6 / extent_current_aridandsemiarid_global_km2 # 0.04692249
extent_futureRCP45_aridandsemiarid_global_change_relative <- (1.0 + 1.0) * 1e6 / extent_current_aridandsemiarid_global_km2 # 0.09149886
#---Huang, J., H. Yu, X. Guan, G. Wang, and R. Guo. 2015. Accelerated dryland expansion under climate change. Nature Climate Change.
extent_current_dryland_global_relative <- 0.56 / 1.23 # 0.456 RCP85 (relative to 1961-1990); 0.5 / 1.11 # 0.450 RCP45
extent_current_dryland_global_km2 <- extent_current_dryland_global_relative * GlobalTerrestrialSurface # 67.81 * 1e6
extent_current_aridandsemiarid_global_relative <- (20.3 + 14.9) / 100 / 1.23 #0.2861789 RCP85; (19.0 + 14.4) / 100 / 1.11 #0.3009009 RCP45
extent_current_aridandsemiarid_global_km2 <- extent_current_aridandsemiarid_global_relative * GlobalTerrestrialSurface # 42.623480 * 1e6
extent_futureRCP85_aridandsemiarid_global_change_relative <- (20.3 + 14.9) / 100 / extent_current_aridandsemiarid_global_relative - 1 #0.23
extent_futureRCP45_aridandsemiarid_global_change_relative <- (19.0 + 14.4) / 100 / extent_current_aridandsemiarid_global_relative - 1 #0.167102
#-Global shifts relative to current extents
global_relative_shifts2 <- apply(apply(temp_dat, 1:3, sum, na.rm = TRUE), 1:2, calc_ensemble4) / extent_current_km2
#, , RCP45
#
# trailing stable leading
#[1,] 0.1121001 0.6753725 0.04134797
#[2,] 0.2222163 0.7756046 0.06690099
#[3,] 0.3246275 0.8878999 0.10548215
#
#, , RCP85
#
# trailing stable leading
#[1,] 0.2416284 0.4933347 0.05857144
#[2,] 0.3633220 0.6089384 0.09166373
#[3,] 0.5066653 0.7583716 0.20424021
#-Global net changes
global_absolute_net <- apply(apply(temp_diff, 1:2, sum, na.rm = TRUE), 1, calc_ensemble4)
# RCP45 RCP85
#[1,] -2177793.0 -3326797
#[2,] -1396398.4 -2357017
#[3,] -458278.4 -1242930
global_relative_net <- global_absolute_net / extent_current_km2
# RCP45 RCP85
#[1,] -0.26253822 -0.4010534
#[2,] -0.16833921 -0.2841441
#[3,] -0.05524658 -0.1498382
global_relative_net <- apply(resExtent2_ranks[c("stable", "leading"), -1, -1, , "Study_km2"], 2:3, sum, na.rm = TRUE) / extent_current_km2 - 1
# rank1 rank8 rank16
#RCP45 -0.3384297 -0.1678777 0.008579521
#RCP85 -0.5225394 -0.3115873 -0.025123257
#-Regional net relative change
temp <- sweep(x = temp_diff, MARGIN = 3, STATS = temp_cur_reg, '/')
regional_net_relative_shifts <- apply(temp, c(1, 3), calc_ensemble4)
#, , Region1
#
# RCP45 RCP85
#[1,] -0.26738772 -0.4243465
#[2,] -0.19416913 -0.3080354
#[3,] -0.07514185 -0.2048365
#
#, , Region2
#
# RCP45 RCP85
#[1,] NA NA
#[2,] NA NA
#[3,] NA NA
#
#, , Region3
#
# RCP45 RCP85
#[1,] -0.11619923 -0.14234860
#[2,] 0.03722390 -0.02804738
#[3,] 0.07615328 0.06190511
#
#, , Region4
#
# RCP45 RCP85
#[1,] -0.3604447 -0.6321608
#[2,] -0.2601194 -0.4174965
#[3,] -0.1152800 -0.2203688
#
#, , Region5
#
# RCP45 RCP85
#[1,] -0.9104305 -0.9802877
#[2,] -0.7897807 -0.9302924
#[3,] -0.4944209 -0.7661646
#
#, , Region6
#
# RCP45 RCP85
#[1,] -0.5878366 -0.8241845
#[2,] -0.2966341 -0.5269785
#[3,] -0.0351219 -0.2423236
#-------------------------------
#------TABLES AND FIGURES
temp_dat_reg_ranked <- apply(temp_dat[, , , regions_n], c(1:2, 4), calc_ensemble4)
dimnames(temp_dat_reg_ranked)[[1]] <- paste0("rank", ranks)
temp_dat_reg_ranked <- aperm(temp_dat_reg_ranked, c(2:3, 1, 4))
temp_diff_reg_ranked <- apply(temp_diff[, , regions_n], c(1, 3), calc_ensemble4)
dimnames(temp_diff_reg_ranked)[[1]] <- paste0("rank", ranks)
temp_diff_reg_ranked <- aperm(temp_diff_reg_ranked, c(2, 1, 3))
#-Table S3. Extent of global temperate drylands (1000 km2) by region, RCP scenario for the end of the 21st century, GCM-rank, and shifting zone.
temp1 <- data.frame(Var3 = currentSc, Var2 = "", Var1 = "", round(t(temp_cur_reg[regions_n]) / 1e3))
temp2 <- melt(temp_dat_reg_ranked / 1e3)
temp2$Var3 <- factor(x = temp2$Var3, levels = paste0("rank", ranks), labels = rank.labels)
temp2$value <- round(temp2$value)
table_S3 <- rbind(temp1, dcast(temp2, Var2 + Var1 + Var3 ~ Var4))
table_S3[is.na(table_S3)] <- 0
write.csv(table_S3, file = file.path(dir.fig_SA3, "Table_S3_Extent of global temperate drylands.csv"))
#-Table S4. Percent decrease, increase, and net change of global temperate dryland area relative to current geographic extent (in 1000 km2) by region, RCP scenario for the end of the 21st century, and GCM-rank.
temp1a <- sweep(x = temp_dat_reg_ranked, MARGIN = 4, STATS = temp_cur_reg[regions_n], '/')
temp2a <- melt(temp1a)
temp2a[is.na(temp2a)] <- 0
temp1b <- sweep(x = temp_diff_reg_ranked, MARGIN = 3, STATS = temp_cur_reg[regions_n], '/')
temp2b <- melt(temp1b)
temp2b[is.na(temp2b)] <- 0
temp3b <- data.frame(Var1 = "net", temp2b)
colnames(temp3b) <- c("Var1", "Var2", "Var3", "Var4", "value")
temp4 <- rbind(temp2a[temp2a$Var1 == "leading", ], temp2a[temp2a$Var1 == "trailing", ], temp3b)
temp4$value <- round(temp4$value, 2)
temp5 <- melt(regional_net_relative_shifts[,, regions_n])
all.equal(temp5[do.call(order, temp5[, c(2, 1, 3)]), "value"], temp3b[do.call(order, temp3b), "value"])
tabel_S4 <- dcast(temp4, Var2 + Var1 + Var3 ~ Var4)
write.csv(tabel_S4, file = file.path(dir.fig_SA3, "Table_S4_Change of global temperate dryland area relative to current geographic extent_v2.csv"))
#-Table S5. Relative contributions of aridity (A < 0.05, A > 0.5), temperateness (T), and MAT (< 0 C) to geographic shifts (percent of edge type area, Table S3) of global temperate drylands by region, RCP scenario for the end of the 21st century, GCM-rank, and zone type.
temp1 <- sweep(x = resExtent2[shifts, -1, -1, regions_n, -(1:2)], MARGIN = 1:4, STATS = resExtent2[shifts, -1, -1, regions_n, "Study_km2"], '/')
temp1 <- apply(temp1, c(1:2, 4:5), calc_ensemble4)
dimnames(temp1)[[1]] <- paste0("rank", ranks)
temp1 <- aperm(temp1, c(2:3, 1, 4:5))
temp2 <- melt(temp1)
temp2[is.na(temp2)] <- 0
temp2$Var3 <- factor(x = temp2$Var3, levels = paste0("rank", ranks), labels = rank.labels)
temp2$value <- round(temp2$value, 2)
temp2 <- temp2[temp2$Var1 %in% c("trailing", "leading") & !(temp2$Var5 == "DueToSand90"), ]
#table_S5 <- dcast(temp2, Var4 + Var5 ~ Var2 + Var1, fun.aggregate = function(x) {x <- formatC(x, digits = 2, format = "f"); paste0(x[2], " (", x[1], ", ", x[3], ")")})
table_S5a <- dcast(temp2, Var4 + Var5 ~ Var2 + Var1, fun.aggregate = function(x) {x <- formatC(x, digits = 2, format = "f"); x[2]})
table_S5b <- dcast(temp2, Var4 + Var5 ~ Var2 + Var1, fun.aggregate = function(x) {x <- formatC(x, digits = 2, format = "f"); paste0("(", x[1], ", ", x[3], ")")})
temp3 <- cbind(table_S5a, table_S5b)
table_S5 <- temp3[, c(1:3, 9, 4, 10, 5, 11, 6, 12)]
write.csv(table_S5, file = file.path(dir.fig_SA3, "Table_S5_Relative attribution to geographic shifts_v2.csv"))
}
#-------------------------------
#------GEOGRAPHIC EXTENT MAPS
#-Figure 1. Maps showing the geographic distribution of the study area in each region under current and end of 21st century climate conditions under RCP4.5 and 8.5 with the varying agreement among GCMs
#-------------------------------
# Create maps with 6 panels to be used as main figure
# - first panel: current values on word-map with country borders and our 5 regions
# - one panel each per region: shifting zones and their agreement
if (do_maps) {
print("DrylandResponse: regional agreement map")
#- Load data
masks_regions <- lapply(reqRCPs, function(rcp) load_regional_masks(dir.gis = file.path(dir.gis, "Any17Cond"), pattern = "Region", rcp = rcp))
masks_gregions <- lapply(reqRCPs, function(rcp) load_regional_masks(dir.gis = file.path(dir.gis, "Any17Cond"), pattern = "Global", rcp = rcp))
# get data objects
dAgreement <- apply(dStudy2[shifts, reqRCPs, reqGCMs, ], MARGIN = c(1:2, 4), function(x) sum(!is.na(x) & x == 1))
# In-text result: Count agreement levels
agree16 <- matrix(NA, nrow = length(regions_n), ncol = length(reqRCPs) * 2, dimnames = list(label.regions[regions_n], paste0(rep(c("trailing_stable", "leading"), times = length(reqRCPs)), "_", rep(reqRCPs, each = 2))))
for (ircp in seq_along(reqRCPs)) {
for (i in seq_along(regions_n)) {
ids <- dLoc$Region == regions_n[i]
temp <- lapply(list(dTrail = dAgreement["trailing", reqRCPs[ircp], ids],
dStable = dAgreement["stable", reqRCPs[ircp], ids],
dLead = dAgreement["leading", reqRCPs[ircp], ids]), function(x) table(x))
hs <- matrix(NA, nrow = 3, ncol = 1 + length(reqGCMs))
for (ish in seq_along(shifts)) hs[ish, 1 + as.integer(names(temp[[ish]]))] <- temp[[ish]]
agree16[i, 1:2 + (ircp - 1) * 2] <- c((hs[2, 2] + hs[1, 17]) / (hs[2, 2] + sum(hs[1, -1], na.rm = TRUE)), leading = hs[3, 17] / sum(hs[3, -1], na.rm = TRUE))
}
}
# trailing_stable_RCP45 leading_RCP45 trailing_stable_RCP85 leading_RCP85
#South America 0.28518519 0.08737864 0.4836957 0.10769231
#Eastern Asia 0.08011869 0.12929062 0.1921865 0.13162393
#Western & Central Asia 0.21380090 0.08585859 0.3015981 0.04509583
#Western Mediterranean 0.51658768 NA 0.8018433 NA
#North America 0.10779436 NA 0.1927711 NA
# Colors
mcols <- list()
mcols$cols_cur <- "darkgreen"
if (map_inset_version == "v1") {
relArealBar <- TRUE
relAgreementHist <- FALSE
temp12 <- colorRampPalette(cols_shifts[2:1])(1 + length(reqGCMs))
mcols$shifts[[1]] <- c("transparent", temp12[-1])
mcols$shifts[[2]] <- c("transparent", rev(temp12)[-1])
mcols$shifts[[3]] <- sapply(seq(0, 1, length.out = 1 + length(reqGCMs)), function(x) adjustcolor(cols_shifts[3], alpha.f = x))
} else if (map_inset_version == "v1") {
relArealBar <- FALSE
relAgreementHist <- TRUE
temp12 <- colorRampPalette(cols_shifts[2:1])(1 + length(reqGCMs))
mcols$shifts[[1]] <- c("transparent", temp12[-1])
mcols$shifts[[2]] <- c("transparent", rev(temp12)[-1])
mcols$shifts[[3]] <- sapply(seq(0, 1, length.out = 1 + length(reqGCMs)), function(x) adjustcolor(cols_shifts[3], alpha.f = x))
} else if (map_inset_version == "v2") {
relArealBar <- FALSE
relAgreementHist <- TRUE
temp12 <- colorRampPalette(cols_shifts[2:1])(1 + length(reqGCMs))
mcols$shifts[[1]] <- c("transparent", temp12[-1])
mcols$shifts[[2]] <- c("transparent", rev(temp12)[-1])
mcols$shifts[[3]] <- c("transparent", sapply(seq(0.3, 1, length.out = length(reqGCMs)), function(x) adjustcolor(cols_shifts[3], alpha.f = x)))
} else if (map_inset_version == "v3") {
relArealBar <- FALSE
relAgreementHist <- TRUE
temp12 <- colorRampPalette(cols_shifts[2:1])(1 + length(reqGCMs))
mcols$shifts[[1]] <- c("transparent", temp12[-1])
mcols$shifts[[2]] <- c("transparent", rev(temp12)[-1])
mcols$shifts[[3]] <- c("transparent", colorRampPalette(c("lightblue", "blue", "darkblue"))(length(reqGCMs)))
}
mcols$legend <- if (relArealBar) {
cols_shifts
} else if (relAgreementHist) {
list(cols_shifts12 = c(cols_shifts[1], cols_shifts[2]),
cols_shift3 = c("white", mcols$shifts[[3]][-1]))
} else {
NULL
}
# Plots
for (ircp in seq_along(reqRCPs)) {
stopifnot(apply(dAgreement[c("trailing", "stable"), ircp, ], 2, sum) %in% c(0, length(reqGCMs))) # since current == const, then trailing + stable == 16
#---Plot
plot_agreement_regional_grids(ircp, mask_global = mask_simulation, mask_regions = masks_regions[[ircp]], mask_gregions = masks_gregions[[ircp]],
dat_cur = dStudy2["MetDef_ThisCond", currentSc, currentSc, ],
dat_shifts = dAgreement, #expected array: shifts, RCPs, value
cex = 1, # lists of length 4: current + 3 shifts
mapcols = mcols,
relArealBar = relArealBar, relAgreementHist = relAgreementHist,
dir.out = dir.fig_SA1, fname = paste0("AgreementMap_", reqRCPs[ircp], "_", map_inset_version, ".pdf"))
}
}
#-------------------------------
saveRDS(TRUE, file = file.path(dir.sim_out, paste0("Flag_StudyAreaExtents_", tag_dbScen, ".rds"))) #Indicate that this script has successfully completed