-
Notifications
You must be signed in to change notification settings - Fork 3
/
5a2_GTD_Prj03v4_Extract_subsetPrj06.R
executable file
·661 lines (531 loc) · 29.1 KB
/
5a2_GTD_Prj03v4_Extract_subsetPrj06.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
647
648
649
650
651
652
653
654
655
656
657
658
659
660
################### EXTRACT RESULTS FROM SQL-DATABASE ##################
#
# Daniel Schlaepfer, 2015-2016
#
# Extract cell identification, variables and study area extent from overall SQLite-database for all climate scenarios
# Scripts '5a2_GTD_*.R' and '5a3_GTD_*.R' must be run before data can be loaded with '5a1_GTD_*.R'
# - 'done_data_extraction' will be stored as flag indicate whether this script has successfully completed
#
###################################################################
#---GLOBAL SETTINGS
comp <- "dropbox"
get_from_db <- FALSE #TRUE: extract from DB; FALSE: load RData which was previously extracted
redo <- FALSE
#-------------------------------
#---R packages
walltime_sec <- if (comp == "mtmoran") 3600 else Inf
pkg_reqd <- c("RSQLite")
has_loaded <- sapply(pkg_reqd,
function(lib) require(lib, character.only = TRUE, quietly = FALSE))
stopifnot(has_loaded)
#---Directories
if (comp == "eo") {
dir.gtd <- "/PATH_TO_PROJECT/Product_PowellCenter/6_Projects_Year1"
dir.gtd2 <- "/PATH_TO_PROJECT_ON_BIG_DRIVE/Product_PowellCenter"
} else if (comp %in% c("err", "eleos")) {
dir.gtd <- "/PATH_TO_PROJECT/Product_PowellCenter/6_Projects_Year1"
dir.gtd2 <- "/PATH_TO_PROJECT_ON_BIG_DRIVE/Product_PowellCenter"
} else if (comp == "mtmoran") {
dir.gtd <- "/PATH_TO_PROJECT/Product_PowellCenter/6_Projects_Year1"
dir.gtd2 <- "/PATH_TO_PROJECT_ON_BIG_DRIVE/Product_PowellCenter"
} else if (comp == "dropbox") {
dir.gtd <- "/PATH_TO_PROJECT/Product_PowellCenter/6_Projects_Year1"
dir.gtd2 <- "/PATH_TO_PROJECT_ON_BIG_DRIVE/Product_PowellCenter"
}
dir.dat <- file.path(dir.gtd2, "Prj03_GlobalVulnerability", "1_PC_TempDry_Simulations_Prj03_r2", "4_Data_SWOutputAggregated")
#---Load data and misc. functions
dir.prj <- file.path(dir.gtd, "Prj03_GlobalVulnerability", "4_Analysis", "4_Analysis_v4")
source(file.path(dir.prj, "5a1_GTD_Prj03v4_Helper.R"))
dir.create(dir.out_EX <- file.path(dir.sim_out, "Extraction"), showWarnings = FALSE)
#---File names
fname_ExpDes <- "SWRuns_InputData_ExperimentalDesign_Prj03_v03.csv"
#---Get database functionality
if (file.exists(ftemp <- file.path(dir.sana, "5_Database_Functions.R")) && get_from_db) {
source(ftemp)
}
#---Settings
if (!file.exists(ftemp <- file.path(dir.out_EX, paste0("Scenarios_", tag_dbScen, ".RData"))) && get_from_db) {
con <- dbConnect(drv, file.path(dir.dat, name.dbScen))
scenarios <- dbGetQuery(con, "SELECT * FROM scenario_labels;")$label
dbDisconnect(con)
stopifnot(scenarios[1] == currentSc)
if (comp == "err-test") {
climScen <- data.frame(matrix(unlist(strsplit(temp <- scenarios[!grepl(currentSc, scenarios)], split = ".", fixed = TRUE)), ncol = 2, byrow = TRUE), stringsAsFactors = FALSE)
reqGCMs <- unique(climScen[, 2])
reqRCPs <- unique(climScen[, 1])
} else {
climScen <- data.frame(matrix(unlist(strsplit(temp <- scenarios[!grepl(currentSc, scenarios)], split = ".", fixed = TRUE)), ncol = 3, byrow = TRUE), stringsAsFactors = FALSE)
reqGCMs <- unique(climScen[, 3])
reqRCPs <- unique(climScen[, 2])
}
rcp_gcm <- paste(rep(reqRCPs, each = length(reqGCMs)), rep(reqGCMs, times = length(reqRCPs)), sep = "_")
reqGCMs_wCur <- c(currentSc, reqGCMs)
reqRCPs_wCur <- c(currentSc, reqRCPs)
save(scenarios, climScen, reqGCMs, reqRCPs, rcp_gcm, reqGCMs_wCur, reqRCPs_wCur, file = ftemp)
} else {
load(ftemp)
}
#---Subset: Prj06 to Prj03 (only differences is in experimental treatments)
#---Design of simulation experiment
if (!file.exists(ftemp <- file.path(dir.out_EX, paste0("Experiment_", tag_dbScen, ".RData"))) && get_from_db) {
con <- dbConnect(drv, file.path(dir.dat, name.dbScen))
temp <- dbListFields(con,name = "treatments")[-(1:3)]#remove id experimental_id simulation_years_id
trNames_Experiment <- temp[!(temp %in% c("LookupWeatherFolder_id"))]
TreatmentDefinitions <- dbGetQuery(con, paste("SELECT DISTINCT Experimental_Label, ", paste0(paste0("\"", trNames_Experiment, "\"",sep = ""), collapse = ", "), " FROM header ORDER BY Experimental_Label;",sep = ""))
trLevels_Site <- dbGetQuery(con, "SELECT DISTINCT site_id FROM sites ORDER BY site_id;")$site_id
trLevels_Region <- dbGetQuery(con, "SELECT DISTINCT Region FROM sites ORDER BY Region;")$Region
trLevels_Experiment <- dbGetQuery(con, "SELECT DISTINCT label FROM experimental_labels ORDER BY label;")$label
trLevels_Experiment <- trLevels_Experiment[ie]
dbDisconnect(con)
save(trNames_Experiment, TreatmentDefinitions, trLevels_Site, trLevels_Region, trLevels_Experiment, file = ftemp)
} else {
load(ftemp)
}
#---ANALYSIS----------------------------
if (!file.exists(ftemp <- file.path(dir.out_EX, paste0("TablesFields_", tag_dbScen, ".RData"))) && get_from_db) {
dbScen.Tables <- list.dbTables(dbName = name.dbScen)
dbScen.OverallFields <- list.dbVariables(dbName = name.dbScen, dbTable = "aggregation_overall_mean")
save(dbScen.Tables, dbScen.OverallFields, file = ftemp)
} else {
load(ftemp)
}
scale_variables <- function(instructions, dat, target) {
for (i in seq_len(nrow(instructions))) if (instructions$data[i] == target) {
temp <- get(instructions$data[i])
iv <- grepl(instructions$vars[i], temp) & !grepl(instructions$varsnot[i], temp)
dat[, , , , iv] <- instructions$scale[i] * dat[, , , , iv]
}
dat
}
derive_variables <- function(instructions, dat, target) {
for (i in seq_len(nrow(instructions))) if (instructions$data[i] == target) {
temp <- get(instructions$data[i])
vars1 <- which(grepl(instructions$var1[i], temp) & !grepl(instructions$var2[i], temp))
var2 <- which(grepl(instructions$var2[i], temp) & !grepl(instructions$var1[i], temp))[1]
deriv_vars <- ifelse(is.na(instructions$var_out),
which(grepl(instructions$var1[i], temp) & grepl(instructions$var2[i], temp)),
instructions$var_out)
if (length(vars1) > 0 && length(var2) == 1 && length(vars1) == length(deriv_vars)) {
for (j in seq_along(vars1)) {
dat[, , , , deriv_vars[j]] <- match.fun(instructions$fun[i])(dat[, , , , vars1[j]], dat[, , , , var2])
}
}
}
dat
}
#---Modifiers to var_response
add_TopBottomSum <- c("_AvailableWater", "Layers_AnnualSum", "_mPERm_mean")
var_scaled <- data.frame(data = c("var_response", "var_response"),
vars = c("_AvailableWater", "Layers_AnnualSum"),
varsnot = c("/"),
unit_original = c("mm", "mmH2O"),
unit_replace = c("m", "m"),
scale = rep(1/1000, 2),
stringsAsFactors=FALSE)
derived_vars <- data.frame(data = c("var_response",
"var_response"),
var1 = c("_AvailableWater",
"_DrySpellsAllLayers_maxDuration_days"),
var2 = c("TeeriEtAl1976_NSadj_FreezeFreeGrowingPeriod_days",
"TeeriEtAl1976_NSadj_FreezeFreeGrowingPeriod_days"),
fun = c("/",
"/"),
var_out = c(NA, NA),
stringsAsFactors = FALSE)
ftemp1 <- file.path(dir.out_EX, paste0("ExtractedVariables_", tag_dbScen, ".RData"))
ftemp2 <- gsub(tag_dbScen, paste0("ToExtract_", tag_dbScen), ftemp1)
if (!file.exists(ftemp1) || !file.exists(ftemp2)) {
#---Target variables
var_definition <- var_definition_extract <- c("TemperateDryland12_Normals_TF", "UNAridityIndex_Normals_none", "TrewarthaD_Normals_TF", "MAT_C")
var_climate <- var_climate_extract <- c("MAP_mm", "MAT_C", "UNAridityIndex_Annual_none", "Seasonality_monthlyTandPPT_PearsonCor", "PET_mm")
var_response <- var_response_extract <- c("ThermalSnowfreeDryPeriods_SWPcrit3000kPa_topLayers_DrySpellsAllLayers_maxDuration_days", "ThermalSnowfreeDryPeriods_SWPcrit3000kPa_bottomLayers_DrySpellsAllLayers_maxDuration_days",
"ThermalSnowfreeWetPeriods_SWPcrit1500kPa_topLayers_AvailableWater_mm", "ThermalSnowfreeWetPeriods_SWPcrit1500kPa_bottomLayers_AvailableWater_mm",
"WetSoilPeriods_SWPcrit1500kPa_NSadj_topLayers_AllLayersWet_Duration_Total_days", "WetSoilPeriods_SWPcrit1500kPa_NSadj_bottomLayers_AllLayersWet_Duration_Total_days",
"TeeriEtAl1976_NSadj_FreezeFreeGrowingPeriod_days",
"TranspirationBottomToTranspirationTotal_fraction",
"TtoAET", "AET_mm",
"TmaxAbovePos34degC_days", "TmaxAbovePos40degC_days",
"Transpiration_DailyMax_doy", "SWP_topLayers_DailyMin_doy", "SWP_bottomLayers_DailyMin_doy", "SWP_topLayers_DailyMin_MPa", "SWP_bottomLayers_DailyMin_MPa",
"DrySoilPeriods_SWPcrit3000kPa_NSadj_topLayers_PeriodsForAtLeast10Days_Start_doy", "DrySoilPeriods_SWPcrit3000kPa_NSadj_bottomLayers_PeriodsForAtLeast10Days_Start_doy",
"ThermalSnowfreeDryPeriods_SWPcrit3000kPa_topLayers_DrySpellsAtLeast10DaysAllLayers_Start_doy", "ThermalSnowfreeDryPeriods_SWPcrit3000kPa_bottomLayers_DrySpellsAtLeast10DaysAllLayers_Start_doy",
"DrySoilPeriods_SWPcrit1500kPa_MissingWater_topLayers_AnnualSum_mmH2O", "DrySoilPeriods_SWPcrit1500kPa_MissingWater_bottomLayers_AnnualSum_mmH2O",
"DrySoilPeriods_SWPcrit1500kPa_MissingWater_topLayers_PerEventPerDay_mmH2O", "DrySoilPeriods_SWPcrit1500kPa_MissingWater_bottomLayers_PerEventPerDay_mmH2O")
var_transp <- var_transp_extract <- c("Soil_maxDepth_cm",
"Transpiration_Total_mm_mean",
"Transpiration_topLayers_mm_mean",
"Transpiration_bottomLayers_mm_mean",
"TranspirationBottomToTranspirationTotal_fraction_mean")
var_soils <- var_soils_extract <- c("Soil_maxDepth_cm", "Soil_topLayers_Sand", "Soil_topLayers_Clay")
var_veg <- var_veg_extract <- c("SWinput_Composition_Grasses_fraction_const", "SWinput_Composition_Shrubs_fraction_const", "SWinput_Composition_C3ofGrasses_fraction_const", "SWinput_Composition_C4ofGrasses_fraction_const",
"SWinput_PeakLiveBiomass_month_mean", "SWinput_PeakLiveBiomass_months_duration", "SWinput_GrowingSeason_Start_month_const", "SWinput_GrowingSeason_End_month_const",
"SWinput_Grass_TranspirationCoefficients_topLayer_fraction", "SWinput_Grass_TranspirationCoefficients_bottomLayer_fraction",
"SWinput_Shrub_TranspirationCoefficients_topLayer_fraction", "SWinput_Shrub_TranspirationCoefficients_bottomLayer_fraction")
var_ppt <- var_ppt_extract <- c("Precip_m1_mm_mean", "Precip_m2_mm_mean", "Precip_m3_mm_mean", "Precip_m4_mm_mean", "Precip_m5_mm_mean", "Precip_m6_mm_mean", "Precip_m7_mm_mean", "Precip_m8_mm_mean", "Precip_m9_mm_mean", "Precip_m10_mm_mean", "Precip_m11_mm_mean", "Precip_m12_mm_mean")
var_tempair <- var_tempair_extract <- c("TempAir_m1_C_mean", "TempAir_m2_C_mean", "TempAir_m3_C_mean", "TempAir_m4_C_mean", "TempAir_m5_C_mean", "TempAir_m6_C_mean", "TempAir_m7_C_mean", "TempAir_m8_C_mean", "TempAir_m9_C_mean", "TempAir_m10_C_mean", "TempAir_m11_C_mean", "TempAir_m12_C_mean")
var_vwc <- var_vwc_extract <- c("VWC_topLayers_m1_mPERm_mean", "VWC_topLayers_m2_mPERm_mean", "VWC_topLayers_m3_mPERm_mean", "VWC_topLayers_m4_mPERm_mean", "VWC_topLayers_m5_mPERm_mean", "VWC_topLayers_m6_mPERm_mean", "VWC_topLayers_m7_mPERm_mean", "VWC_topLayers_m8_mPERm_mean", "VWC_topLayers_m9_mPERm_mean", "VWC_topLayers_m10_mPERm_mean", "VWC_topLayers_m11_mPERm_mean", "VWC_topLayers_m12_mPERm_mean",
"VWC_bottomLayers_m1_mPERm_mean", "VWC_bottomLayers_m2_mPERm_mean", "VWC_bottomLayers_m3_mPERm_mean", "VWC_bottomLayers_m4_mPERm_mean", "VWC_bottomLayers_m5_mPERm_mean", "VWC_bottomLayers_m6_mPERm_mean", "VWC_bottomLayers_m7_mPERm_mean", "VWC_bottomLayers_m8_mPERm_mean", "VWC_bottomLayers_m9_mPERm_mean", "VWC_bottomLayers_m10_mPERm_mean", "VWC_bottomLayers_m11_mPERm_mean", "VWC_bottomLayers_m12_mPERm_mean")
var_budyko <- var_budyko_extract <- c("UNAridityIndex_Normals_none",
"PET_mm_mean", "MAP_mm_mean", "AET_mm_mean",
"AETtoPET_mean", "TtoPET_mean", "EStoPET_mean",
"Evaporation_Total_mm_mean",
"Evaporation_InterceptedByVegetation_mm_mean",
"Evaporation_InterceptedByLitter_mm_mean",
"Evaporation_Soil_Total_mm_mean",
"Transpiration_Total_mm_mean")
label_definition <- c("Temperate dryland (-)", "Aridity index (-)", "Temperateness (-)", "MAT (C)")
label_climate <- c("MAP (mm)", "MAT (C)", "Aridity index (-)", "Seasonality (-)", "PET (mm)")
label_response <- c("DDGP0 (days)","DDGP20 (days)",
"AWGP0 (mm x days)", "AWGP20 (mm x days)",
"WD0 (days)", "WD20 (days)",
"Growing period (days)",
"T[deep]/T[total] (-)",
"T/AET (-)", "AET (mm)",
"Hot days (Tmax > 34 C; days)", "Hot days (Tmax > 40 C; days)",
"Date of max transpiration (doy)", "Driest day 0-20 cm (doy)", "Driest day 20- cm (doy)", "Driest day 0-20 cm (MPa)", "Driest day 20- cm (MPa)",
"Start DP0 (doy)", "Start DP20 (doy)",
"Start DPGP0 (doy)", "Start DPGP20 (doy)",
"MW0 (mm x days)", "MW20 (mm x days)",
"MW0 (mm / dryday)", "MW20 (mm / dryday)")
label_transp <- c("Soil depth (cm)",
"Total T (mm)",
"T fed from 0-20 cm (mm)",
"T fed from > 20 cm (mm)",
"T[deep]/T[total] (-)")
label_soils <- c("Soil depth (cm)", "Sand0 (-)", "Clay0 (-)")
label_veg <- c("Grass fraction (-)", "Shrub fraction (-)", "C3 grass fraction (-)", "C4 grass fraction (-)",
"Peak live biomass (month)", "Peak live biomass duration (month)", "Growing season start (month)", "Growing season end (month)",
"Grass root fraction 0-20 cm (-)", "Grass root fraction > 20 cm (-)",
"Shrub root fraction 0-20 cm (-)", "Shrub root fraction > 20 cm (-)")
label_ppt <- c("PPT Jan (mm)", "PPT Feb (mm)", "PPT Mar (mm)", "PPT Apr (mm)", "PPT May (mm)", "PPT Jun (mm)", "PPT Jul (mm)", "PPT Aug (mm)", "PPT Sep (mm)", "PPT Oct (mm)", "PPT Nov (mm)", "PPT Dec (mm)")
label_tempair <- c("TempAir Jan (C)", "TempAir Feb (C)", "TempAir Mar (C)", "TempAir Apr (C)", "TempAir May (C)", "TempAir Jun (C)", "TempAir Jul (C)", "TempAir Aug (C)", "TempAir Sep (C)", "TempAir Oct (C)", "TempAir Nov (C)", "TempAir Dec (C)")
label_vwc <- paste("VWC", rep(month.abb, 2), rep(c("0-20 cm", "> 20 cm"), each = 12), "(m3 m-3)")
label_budyko <- c("Aridity index (-)",
"PET (mm)", "MAP (mm)", "AET (mm)",
"AET/PET (-)", "T/PET (-)", "Esoil/PET (-)",
"Total E (mm)",
"Veg-int E (mm)",
"Litter-int E (mm)",
"Soil E (mm)",
"Total T (mm)")
#---Test availability
stopifnot(sapply(c(var_definition_extract,
var_climate_extract,
var_response_extract,
var_soils_extract,
var_veg_extract,
var_ppt_extract,
var_tempair_extract,
var_vwc_extract,
var_transp_extract,
var_budyko_extract),
function(v) any(grepl(v, dbScen.OverallFields))))
#---Apply modifiers to var_ppt
var_ppt <- c(var_ppt, "Precip_winter_mm_mean")
label_ppt <- c(label_ppt, "PPT winter (mm)")
#---Apply modifiers to var_vwc
for (i in seq_along(add_TopBottomSum)) {
temp <- grep(add_TopBottomSum[i], var_vwc)[1:12]
if (!anyNA(temp)) {
var_vwc <- c(var_vwc, gsub("topLayers", "allLayers", var_vwc[temp]))
label_vwc <- c(label_vwc, gsub("0-20 cm ", "", label_vwc[temp]))
}
}
#---Apply modifiers to var_response
for (i in seq_along(add_TopBottomSum)) {
temp <- grep(add_TopBottomSum[i], var_response, value = TRUE)[1]
if (!anyNA(temp))
var_response <- c(var_response, gsub("topLayers", "allLayers", temp))
}
for (i in seq_len(nrow(derived_vars))) {
temp <- get(derived_vars$data[i])
vars1 <- grep(derived_vars$var1[i], temp)
var2 <- grep(derived_vars$var2[i], temp)[1]
if (length(vars1) > 0 && length(var2) == 1) {
for (j in seq_along(vars1)) {
temp <- c(temp,
if (is.na(derived_vars$var_out[i])) {
paste(temp[vars1[j]], as.character(derived_vars$fun[i]), temp[var2], sep="_")
} else {
derived_vars$var_out[i]
})
}
assign(derived_vars$data[i], temp)
}
}
label_response <- c(label_response, "AWGP (m x days)", "MW (m x days)", "AWGP0 (mm / GPday)", "AWGP20 (mm / GPday)", "AWGP (mm / GPday)", "DDGP0 (days / GP)", "DDGP20 (days / GP)")
#---Apply modifiers to var_budyko
var_budyko <- c(var_budyko, "AI_budyko_Normals_none", "AETtoMAP_mean")
label_budyko <- c(label_budyko, "AIb = E(potential) / P", "F = E(actual) / P")
#---Scale variables
for (i in seq_len(nrow(var_scaled))) {
temp <- get(var_scaled$data[i])
iv_scale <- grepl(var_scaled$vars[i], temp) & !grepl(var_scaled$varsnot[i], temp)
temp[iv_scale] <- gsub(paste0("_", var_scaled$unit_original[i]), paste0("_", var_scaled$unit_replace[i]), temp[iv_scale])
assign(var_scaled$data[i], temp)
}
#---Save objects
save(var_definition, var_climate, var_response, var_soils, var_veg, var_ppt, var_tempair, var_vwc, var_transp, var_budyko,
label_definition, label_climate, label_response, label_soils, label_veg, label_ppt, label_tempair, label_vwc, label_transp, label_budyko,
file = ftemp1)
save(var_definition_extract, var_climate_extract, var_response_extract, var_soils_extract, var_veg_extract, var_ppt_extract, var_tempair_extract, var_vwc_extract, var_transp_extract, var_budyko_extract,
file = ftemp2)
} else {
load(ftemp1)
load(ftemp2)
}
#-------------------------------
#-------------------------------
#---Data extractions
ie_whereClause <- paste0("Experimental_Label=", shQuote(trLevels_Experiment[ie]))
#Grid cells: Geographic coordinates
if (!file.exists(ftemp <- file.path(dir.out_EX, paste0("dLoc_", tag_dbScen, ".RData"))) && get_from_db) {
dLoc <- get.SeveralOverallVariables_Scenario(responseName = c("Region", "X_WGS84", "Y_WGS84"), MeanOrSD = "Mean", scenario = currentSc, whereClause = ie_whereClause)
save(dLoc, file = ftemp)
} else {
load(ftemp)
}
#Inclusion in study area or not
get_studyarea_v4 <- function(whereClause = ie_whereClause) {
print(paste(Sys.time(), ": start with extraction for study area"))
temp <- get.SeveralOverallVariables_Scenario(responseName = var.Study, MeanOrSD = "Mean", scenario = currentSc, whereClause = ie_whereClause)
res <- array(NA, dim = c(length(study_areas_v4), 1 + length(reqRCPs), 1 + length(reqGCMs), length(temp)), dimnames = list(study_areas_v4, c(currentSc, reqRCPs), c(currentSc, reqGCMs), NULL))
#--- Cells that are in study area under the climate condition specified by ircp and igcm
# Current data
res["MetDef_ThisCond", currentSc, currentSc, ] <- ifelse(temp > 0, 1, NA)
# Future scenario data
for (ircp in seq_along(reqRCPs)) {
for (igcm in seq_along(reqGCMs)) {
print(paste(Sys.time(), reqRCPs[ircp], reqGCMs[igcm]))
sc <- which(grepl(reqRCPs[ircp], scenarios, ignore.case = TRUE) & grepl(reqGCMs[igcm], scenarios, ignore.case = TRUE))
stopifnot(length(sc) == 1, sc != 1)
temp <- get.SeveralOverallVariables_Scenario(responseName = var.Study, MeanOrSD = "Mean", scenario = scenarios[sc], whereClause = ie_whereClause)
res["MetDef_ThisCond", 1 + ircp, 1 + igcm, ] <- ifelse(temp > 0, 1, NA)
}
}
res <- get_Any17Cond_v4(data = res)
return(res)
#str(res): num [1:2, 1:3, 1:17, 1:20021] NA NA NA NA NA NA NA NA NA NA ...
# - attr(*, "dimnames") = List of 4
# ..$ : chr [1:2] "MetDef_Any17Cond" "MetDef_ThisCond"
# ..$ : chr [1:3] "Current" "RCP45" "RCP85"
# ..$ : chr [1:17] "Current" "CanESM2" "CESM1-CAM5" "CSIRO-Mk3-6-0" ...
# ..$ : NULL
}
if (!file.exists(ftemp <- file.path(dir.out_EX, paste0("dStudy_", tag_dbScen, ".RData"))) && get_from_db) {
dStudy <- get_studyarea_v4()
# - "MetDef_Any17Cond" is specific to RCPs; hence dStudy["MetDef_Any17Cond", currentSc, , ] has no information, it can be found in dStudy["MetDef_Any17Cond", , currentSc, ] instead
# - "MetDef_ThisCond" is available for current in dStudy["MetDef_ThisCond", currentSc, currentSc, ] and for future in dStudy["MetDef_ThisCond", reqRCPs, reqGCMs, ]
#--- Cells that are in study area at least under one of the 17 climate conditions per RCP
# - this was for Any33Cond in v3: 12,638 cells
print(paste("Cells ('MetDef_Any17Cond', 'RCP45')", sum(!is.na(dStudy["MetDef_Any17Cond", "RCP45", currentSc, ])))) # 11510
print(paste("Cells ('MetDef_Any17Cond', 'RCP85')", sum(!is.na(dStudy["MetDef_Any17Cond", "RCP85", currentSc, ])))) # 12593
save(dStudy, file = ftemp)
} else {
load(ftemp)
}
# Extract variables
get_fields_v4 <- function(variables, dStudy, whereClause = ie_whereClause) {
print(paste(Sys.time(), ": start with extraction for variables:", paste(variables, collapse = ", ")))
stopifnot(!is.null(dStudy), unique(as.vector(dStudy)) %in% c(NA, 0, 1))
# Get current data and use it for dimensions to create result object
temp <- get.SeveralOverallVariables_Scenario(responseName = variables, MeanOrSD = "Mean", scenario = currentSc, whereClause = ie_whereClause)
stopifnot(!is.null(temp))
n_response_names <- ncol(temp)
names_response_names <- colnames(temp)
res <- array(NA, dim = c(length(study_areas_all), length(reqRCPs_wCur), length(reqGCMs_wCur), nrow(temp), n_response_names), dimnames = list(study_areas_all, reqRCPs_wCur, reqGCMs_wCur, NULL, names_response_names))
# Current data (must be repeated across reqRCPs_wCur so that "MetDef_Any17Cond" which is RCP-specific can access the data
temp <- as.matrix(temp)
for (ircp in seq_along(reqRCPs_wCur)) res["Simulation", ircp, currentSc, , ] <- temp
# Future scenario data
ftemp <- file.path(dir.out_EX, "temp_extraction.RData")
for (ircp in seq_along(reqRCPs)) {
for (igcm in seq_along(reqGCMs)) {
print(paste(Sys.time(), reqRCPs[ircp], reqGCMs[igcm]))
sc <- which(grepl(reqRCPs[ircp], scenarios, ignore.case = TRUE) & grepl(reqGCMs[igcm], scenarios, ignore.case = TRUE))
stopifnot(length(sc) == 1, sc != 1)
res["Simulation", 1 + ircp, 1 + igcm, , ] <- as.matrix(get.SeveralOverallVariables_Scenario(responseName = names_response_names, MeanOrSD = "Mean", scenario = scenarios[sc], whereClause = ie_whereClause))
save(res, ircp, igcm, file = ftemp)
}
}
# Limit data to study_areas, i.e., "MetDef_Any17Cond" and "MetDef_ThisCond"
res <- limit_to_study_area_v4(data = res, dStudy = dStudy)
return(list(res = res, ftemp = ftemp))
}
if (!file.exists(ftemp <- file.path(dir.out_EX, paste0("resDefinition_", tag_dbScen, ".RData"))) && get_from_db) {
temp <- get_fields_v4(variables = var_definition_extract, dStudy = dStudy)
resDefinition <- temp$res
ctemp <- test_coherence_among_study_areas(data = resDefinition)
stopifnot(nrow(ctemp) == 0)
save(resDefinition, file = ftemp)
unlink(temp$ftemp)
}
if (!file.exists(ftemp <- file.path(dir.out_EX, paste0("resClimate_", tag_dbScen, ".RData"))) && get_from_db) {
temp <- get_fields_v4(variables = var_climate_extract, dStudy = dStudy)
resClimate <- temp$res
ctemp <- test_coherence_among_study_areas(data = resClimate)
stopifnot(nrow(ctemp) == 0)
save(resClimate, file = ftemp)
unlink(temp$ftemp)
}
ftemp2 <- file.path(dir.out_EX, paste0("resResponse_", tag_dbScen, ".RData"))
ftemp1 <- gsub("resResponse_", "resResponsePreCalc_", ftemp2)
if (!file.exists(ftemp2) && get_from_db) {
temp <- get_fields_v4(variables = var_response_extract, dStudy = dStudy)
resResponse <- temp$res
save(resResponse, file = ftemp1)
#---Apply modifiers to var_response
# Increase dimension
dimn <- dim(resResponse)
dimn[length(dimn)] <- length(var_response)
dimns <- dimnames(resResponse)
dimns[[length(dimns)]] <- var_response
dat2 <- array(NA, dim = dimn, dimnames = dimns)
dat2[, , , , seq_along(var_response_extract)] <- resResponse
# Sum top and bottoms
for (i in seq_along(add_TopBottomSum)) {
temp <- grepl(add_TopBottomSum[i], var_response)
if (any(temp)) {
#order of 'iv_sum' by design: top and bottom layers, third: all layers
iv_sum <- which(temp & !apply(sapply(derived_vars$fun, function(f) grepl(f, var_response)), 1, any))
stopifnot(length(iv_sum) == 3)
dat2[, , , , iv_sum[3]] <- dat2[, , , , iv_sum[1]] + dat2[, , , , iv_sum[2]]
}
}
# Calculate derived variables
dat2 <- derive_variables(derived_vars, dat2, target = "var_response")
# Scale
dat2 <- scale_variables(var_scaled, dat2, target = "var_response")
# Checks
stopifnot(sapply(dimns[[5]], function(var) sum(is.finite(dat2[,,,, var])) > 0))
resResponse <- dat2
ctemp <- test_coherence_among_study_areas(data = resResponse)
stopifnot(nrow(ctemp) == 0)
# Save to disk
save(resResponse, file = ftemp2)
unlink(temp$ftemp)
}
if (!file.exists(ftemp <- file.path(dir.out_EX, paste0("resSoils_", tag_dbScen, ".RData"))) && get_from_db) {
temp <- get_fields_v4(variables = var_soils_extract, dStudy = dStudy)
resSoils <- temp$res
ctemp <- test_coherence_among_study_areas(data = resSoils)
stopifnot(nrow(ctemp) == 0)
save(resSoils, file = ftemp)
unlink(temp$ftemp)
}
if (!file.exists(ftemp <- file.path(dir.out_EX, paste0("resVeg_", tag_dbScen, ".RData"))) && get_from_db) {
temp <- get_fields_v4(variables = var_veg_extract, dStudy = dStudy)
resVeg <- temp$res
ctemp <- test_coherence_among_study_areas(data = resVeg)
stopifnot(nrow(ctemp) == 0)
save(resVeg, file = ftemp)
unlink(temp$ftemp)
}
if (!file.exists(ftemp <- file.path(dir.out_EX, paste0("resPPT_", tag_dbScen, ".RData"))) && get_from_db) {
temp <- get_fields_v4(variables = var_ppt_extract, dStudy = dStudy)
resPPT <- temp$res
#---Apply modifiers to var_ppt
# Increase dimension
dimn <- dim(resPPT)
dimn[length(dimn)] <- length(var_ppt)
dimns <- dimnames(resPPT)
dimns[[length(dimns)]] <- var_ppt
dat2 <- array(NA, dim = dimn, dimnames = dimns)
dat2[, , , , seq_along(var_ppt_extract)] <- resPPT
# Winter precipitation
# Trenberth KE (1983) What are the Seasons? Bulletin of the American Meteorological Society, 64, 1276-1282.
isNorth <- dLoc[, "Y_WGS84"] > 0
isSouth <- !isNorth
if (sum(isNorth) > 0) {
dat2[, , , isNorth, "Precip_winter_mm_mean"] <-
dat2[, , , isNorth, "Precip_m12_mm_mean"] + # December
dat2[, , , isNorth, "Precip_m1_mm_mean"] + # January
dat2[, , , isNorth, "Precip_m2_mm_mean"] # February
}
if (sum(isSouth) > 0) {
dat2[, , , isSouth, "Precip_winter_mm_mean"] <-
dat2[, , , isSouth, "Precip_m6_mm_mean"] + # June
dat2[, , , isSouth, "Precip_m7_mm_mean"] + # July
dat2[, , , isSouth, "Precip_m8_mm_mean"] # August
}
ctemp <- test_coherence_among_study_areas(data = dat2)
stopifnot(nrow(ctemp) == 0)
resPPT <- dat2
save(resPPT, file = ftemp)
unlink(temp$ftemp)
}
if (!file.exists(ftemp <- file.path(dir.out_EX, paste0("resTempAir_", tag_dbScen, ".RData"))) && get_from_db) {
temp <- get_fields_v4(variables = var_temp_extract, dStudy = dStudy)
resTempAir <- temp$res
ctemp <- test_coherence_among_study_areas(data = resTempAir)
stopifnot(nrow(ctemp) == 0)
save(resTempAir, file = ftemp)
unlink(temp$ftemp)
}
if (!file.exists(ftemp <- file.path(dir.out_EX, paste0("resVWC_", tag_dbScen, ".RData"))) && get_from_db) {
temp <- get_fields_v4(variables = var_vwc_extract, dStudy = dStudy)
resVWC <- temp$res
#---Apply modifiers to var_vwc
# Increase dimension
dimn <- dim(resVWC)
dimn[length(dimn)] <- length(var_vwc)
dimns <- dimnames(resVWC)
dimns[[length(dimns)]] <- var_vwc
dat2 <- array(NA, dim = dimn, dimnames = dimns)
dat2[, , , , seq_along(var_vwc_extract)] <- resVWC
# Sum top and bottoms
if (!exists(resSoils))
load(file = file.path(dir.out_EX, paste0("resSoils_", tag_dbScen, ".RData")))
soil_depth <- resSoils["Simulation", currentSc, currentSc, , "SWinput_Soil_maxDepth_cm"]
depth_top_rel <- ifelse(20 <= soil_depth, 20, soil_depth) / soil_depth
for (i in seq_along(add_TopBottomSum)) {
icol <- grepl(add_TopBottomSum[i], var_vwc)
if (any(icol)) {
#order of 'iv_sum' by design: top and bottom layers, third: all layers
iv_sum <- list(grep("topLayers", var_vwc),
grep("bottomLayers", var_vwc),
grep("allLayers", var_vwc))
# allLayers = weighted mean by depth of top and bottom layers
dat2[, , , , iv_sum[[3]]] <- depth_top_rel * dat2[, , , , iv_sum[[1]]] + (1 - depth_top_rel) * dat2[, , , , iv_sum[[2]]]
dat2[, , , , iv_sum[[3]]] <-
sweep(dat2[, , , , iv_sum[[1]]], 4, depth_top_rel, "*") +
sweep(dat2[, , , , iv_sum[[2]]], 4, 1 - depth_top_rel, "*")
}
}
ctemp <- test_coherence_among_study_areas(data = dat2)
stopifnot(nrow(ctemp) == 0)
resVWC <- dat2
save(resVWC, file = ftemp)
unlink(temp$ftemp)
}
if (!file.exists(ftemp <- file.path(dir.out_EX, paste0("resTransp_", tag_dbScen, ".RData"))) && get_from_db) {
temp <- get_fields_v4(variables = var_transp_extract, dStudy = dStudy)
resTransp <- temp$res
ctemp <- test_coherence_among_study_areas(data=resTransp)
stopifnot(nrow(ctemp) == 0)
save(resTransp, file=ftemp)
unlink(temp$ftemp)
}
if (!file.exists(ftemp <- file.path(dir.out_EX, paste0("resBudyko_", tag_dbScen, ".RData"))) && get_from_db) {
temp <- get_fields_v4(variables=var_budyko_extract, dStudy=dStudy)
resBudyko <- temp$res
#---Apply modifiers to var_budyko
# Increase dimension
dimn <- dim(resBudyko)
dimn[length(dimn)] <- length(var_budyko)
dimns <- dimnames(resBudyko)
dimns[[length(dimns)]] <- var_budyko
dat2 <- array(NA, dim = dimn, dimnames = dimns)
dat2[, , , , seq_along(var_budyko_extract)] <- resBudyko
# Bukyko-Framework
# Gudmundsson, L., Greve, P. & Seneviratne, S.I. (2016). The sensitivity of water availability to changes in the aridity index and other factors—A probabilistic analysis in the Budyko space. Geophys Res Lett, 43, 6985-6994.
# Aridity index: AI = PET / MAP
dat2[, , , , "AI_budyko_Normals_none"] <- 1 / dat2[, , , , "UNAridityIndex_Normals_none"] # identical to dat2[, , , , "PET_mm_mean"] / dat2[, , , , "MAP_mm_mean"]
# Water availability: F = E(actual) / MAP
dat2[, , , , "AETtoMAP_mean"] <- dat2[, , , , "AET_mm_mean"] / dat2[, , , , "MAP_mm_mean"]
ctemp <- test_coherence_among_study_areas(data = dat2)
stopifnot(nrow(ctemp) == 0)
resBudyko <- dat2
save(resBudyko, file = ftemp)
unlink(temp$ftemp)
}
saveRDS(TRUE, file = file.path(dir.sim_out, paste0("Flag_DataExtraction_", tag_dbScen, ".rds"))) #Indicate that this script has successfully completed