-
Notifications
You must be signed in to change notification settings - Fork 2
/
CCRP_Generate_Climate_Futures.Rmd
284 lines (167 loc) · 11.9 KB
/
CCRP_Generate_Climate_Futures.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
---
title: "Combine-climate-lite-scripts"
date: "`r format(Sys.time(), '%d %B %Y')`"
output: html_document
abstract: This script combines all scripts previously run under CCRP's Climate Lite protocol for Resource Stewardship Strategies (RSS).
---
NOTE: If you have trouble with packages loading from renv, go into your .Rprofile file and comment out the line ```source("renv/activate.R)```
Then restart R and re-run from your general package library (R will do this automatically upon restart if the above line is commented out). If you want to check what library R is accessing, type ```.libPaths()``` into your console.
##
```{r setup, include=FALSE}
knitr::opts_chunk$set(
echo = FALSE,
collapse = TRUE,
warning = TRUE, # set to FALSE when done
message = TRUE # set to FALSE when done
)
#renv::init() Only needs to be run 1x when project is initiated. No one should ever have to run this line again.
#renv::restore() # This line will restore packages to the versions recorded in the lockfile. Collaborators can use this command to keep their packages current. This line should be run once a week.
#renv::update(exclude = "WaterBalance") # This line should be run once a week by whoever is regularly using this script. The first time running this line, you might need to follow directions to create a Personal Access Token with GitHub. Simply follow directions printed in the console. If you run into trouble, contact Annie Kellner Dillon at [email protected]
# renv::snapshot() # This command takes a snapshot of the packages in their current state and records it in the lockfile. Renv will perform this task periodically. If a manual snapshot is desired, use this command to manually update the lockfile.
#Install WaterBalance package from Github repository
# install_github("CCRP-Adaptation/WaterBalance", subdir="WaterBalance")
#Install CFT
# remotes::install_github("earthlab/cft@*release",force=TRUE)
# packages = c("ggplot2","grid","cowplot","reshape2","ncdf4","WriteXLS","data.table","RColorBrewer","ggrepel","lubridate","dplyr","forcats","openxlsx","sf","raster","rgdal","R.utils","tmap","tmaptools","gridExtra","SPEI","tidyr","tibble","sp",
# "skimr")
# install.packages(packages)
library(here); library(plyr); # Use here::here when package lubridate is used
library(plotrix); library(zoo); library(ggplot2); library(grid); library(cowplot); library(reshape2); library(raster); library(ncdf4); library(reshape2); library(WriteXLS); library(data.table); library(RColorBrewer); library(ggrepel); library(lubridate); library(dplyr); library(forcats); library(openxlsx); library("WaterBalance"); library(sf); library(raster); library(rgdal); library(R.utils); library(tmap); library(tmaptools); library(ggmap); library(ggspatial);
library(gridExtra); library(SPEI); library(tidyr); library(tibble); library(sp); library(skimr); library(cft)
```
There are two code chunks in which the RCF user should enter information that is park-specific. The first chunk contains inputs that are often changed (i.e., with each new park). The second chunk contains user inputs that are *rarely* changed (i.e., project lead has requested a change).
**First user input chunk (please enter park-specific information):**
```{r user-inputs-1}
rm(list = ls())
# --------------- Input local folder information ----------------------------- #
# When this document has finished running, the files will be copied to a local directory and all newly created files (e.g., figures) will be deleted from the repo
project_root_dir <- 'C:/Users/gknowlton/OneDrive - DOI/Documents/Repos/CCRP_Climate_Futures_v1.0' # local directory where your repo is stored
local_rss_dir <- 'C:/Users/gknowlton/OneDrive - DOI/Documents/RSS/ANTI_new' # local directory where you want this repo copied. Should be something like 'C:/Users/adillon/Documents/RSS/CONG'
# -------------- Input site information -------------------------------------- #
SiteID = "ANTI"
state <- "Maryland"
Lat = 39.47010671
Lon = -77.7380518
# -------------- Inputs for NOAA ClimGrid Extraction --------------------------#
data.dir <- "E:/nClimGrid" # Location where NOAA ClimGrid data is stored, e.g. "E:/nClimGrid"
# -------------- Input information for Climate Futures analyses (MACA) ------- #
# Specify Climate Futures
FutureSubset <- c("Warm Wet","Hot Dry"); CFs = FutureSubset # Pick pair of climate futures.
colors2<- c("#9A9EE5","#E10720") # Select pair of climate futures - WarmWet/HotDry
#colors2<- c("#F3D3CB","#12045C") # Select pair of climate futures - HotWet/WarmDry
# -------------- Input information for Water Balance model ------------------- #
# WB_GCMs = c("MRI-CGCM3.rcp45","HadGEM2-ES365.rcp85") # Specific models need to be selected to run the Water Balance scripts
col<- c("darkgray","#9A9EE5","#E10720") # WarmWet/HotDry
#col<- c("darkgray","#F3D3CB","#12045C") # HotWet/WarmDry
```
**Second user input chunk (information that should only be changed when directly specified)**
```{r user-inputs-2}
CFs_all <- c("Warm Wet", "Hot Wet", "Central", "Warm Dry", "Hot Dry")
# ---------- Information for Historical Parsing and Plotting ------------------ #
# Parsing
Buffer <- 0.06 # dec degree
# Plotting
doP1 <- "YES" # Should a separate regression be calculated for the reference period (default 1900-1970)?
doP2 <- "YES" # Should a separate regression be calculate for the period after the reference period (default 1971-present)?
beginRefYr = 1900
endRefYr = 1970
# needed for rolling mean plot below.
stepYrs = 10 # for period plots
rollLen = 10 # period of calc for rolling average; default 10 = decadal
dpi = 600
# ----------- Information for MACA parsing script ---- ----------------------- #
#Date ranges to be extracted
Future_StartYear = 2006 #2006-2099
Future_EndYear = 2099 #2006-2099
Hist_StartYear = 1950 #1950-2005
Hist_EndYear = 2005 #1950-2005
#Variable and scenario names corresponding to MACA data directory structure
vars = c("pr", "tasmax", "tasmin","rhsmax","rhsmin")
scens = c("rcp45", "rcp85")
#Variable names for output tables
VarNames = c("PrecipCustom", "TmaxCustom", "TminCustom","RHmaxCustom","RHminCustom")
# GCMs to be extracted
GCMs = c('bcc-csm1-1','bcc-csm1-1-m','BNU-ESM','CanESM2','CCSM4','CNRM-CM5','CSIRO-Mk3-6-0',
'GFDL-ESM2G','GFDL-ESM2M','HadGEM2-CC365','HadGEM2-ES365',
'inmcm4','IPSL-CM5A-MR','IPSL-CM5A-LR','IPSL-CM5B-LR',
'MIROC5','MIROC-ESM','MIROC-ESM-CHEM','MRI-CGCM3','NorESM1-M')
Remove_files = "Y" # "N" #Removes all climate data files saved in directory
# This code can also be changed for GridMet
# --------- Information for Climate Futures Analyses (MACA) ------------------ #
# Specify parameters:
Year = 2040 #Central year
Range = 30 #Number of years to summarize (should be at least 30)
# Threshold percentages for defining Climate futures. Default low/high: 0.25, 0.75
CFLow = 0.25
CFHigh = 0.75
#Temperature/precip threshold values
HotTemp = 95 # deg F. Default should be about 100 deg F
ColdTemp = 32 # deg F
PrecipThreshold = 0.05 # inches per day. Precip Threshold (used to measure Drought duration). For many GCMs shoud not
# be 0 because models "drizzle". Some investigation necessary.
QuantileLow = 0.05 #Quantiles for temperature threshold calculations
QuantileHigh = 0.95
# -------------- Information for GridMET ------------------------------------ #
box = c(Lat+.5,Lat-.5,Lon+.5,Lon-.5)
startDate = "1979-01-01"
endDate = "2020-12-31"
# -------------- Information for Water Balance model ------------------- #
# The following needs to be inputted if the park centroid will not be used to select the MACA grid cell for the water balance model:
#MACA_lat <- 40.4465
#MACA_lon <- -108.7651
# ------------ Information for drought analyses ------------------------ #
## SPEI variables
SPEI_per<-6 # This is the value for the period SPEI is aggregated. 6-months is standard but could change if want.
truncation<- -.5 # SPEI value, under which drought events are considered
SPEI_start <- 1950
SPEI_end <- 1999
```
## Historical Trends
```{r parse-NOAA-Gridmet, message=FALSE, warning=FALSE, echo=FALSE}
source(here::here("scripts", "Historical-trends", "extract-site-format-trends.R")) # Parses NOAA data. Output = "PARK_lat_long_PRISM_nClimGrid_IntermediateFiles.RData"
source(here::here("scripts", "Historical-trends", "Gridmet-THREDD-download.R")) # Parse GridMET data. Output = "GridMet.csv"
```
```{r Historical-trends-plots, results=hide, eval=TRUE}
# Requires "PARK_lat_long_PRISM_PptTminTmax_IntermediateFiles.RData"
# Outputs plots into ./figures/Historical-trends
# If you get an error re: invalid 'description' argument, it means the data is missing
source(here::here("scripts", "Historical-trends", "RSS PRISM plots v1.2.R"), echo = FALSE)
```
## Climate Futures (MACA)
```{r Climate-Futures, message=FALSE, warning=FALSE, include=FALSE, results=HIDE}
#source(here::here("scripts", "Climate-Futures", "CFT_CF_parsing_v1.R")) # Parse MACA data. Output = "_init_parsed.RData". # 9-8-21: CFT parsing script is not working due to an issue with the package or MACA servers. ACR to talk to CU Boulder about the issue. For now, add _init_parsed.RData file manually to parsed-data folder.
source(here::here("scripts", "Climate-Futures", "RSS_MACA_Plot_Table_Creation.R"), local = knitr::knit_global()) # Requires "PARK_init_parsed.RData"; Output = "PARK_lat_long_Final_Environment.RData".
source(here::here("scripts", "Climate-Futures", "RSS_MACA_Scatter and diagnostic.R"), local = knitr::knit_global()) # Creates scatter and diagnostic plots. Outputs to Figs MACA folder.
```
```{r CF-plots}
if (exists("FutureSubset") == FALSE) stop("Please specify Climate Futures") # At the top of the script, please enter a combination of futures, e.g. Warm Wet/Hot Dry
source(here::here("scripts", "Climate-Futures", "RSS_Plotting_Bar_Charts.R")) # Requires "PARK_lat_long_Final_Environment.RData". Outputs plots and Excel Workbook
```
# Water Balance
The get_params.R script extracts site parameters for inputting into Dave Thoma's Water Balance model (see 'Daily_WB_batch_v2.R'). The create_site_maps.R script creates a suite of maps from which the project lead can select the most appropriate for use with the RSS Powerpoint presentation. Maps output into the './figures/maps' folder.
```{r Water-Balance, message=FALSE, warning=FALSE, echo = FALSE, results=HIDE}
source(here::here("scripts", "WaterBalance", "get_params.R")) # Extract site parameters
source(here::here("scripts", "Misc", "create_site_maps.R")) # Create site maps
```
```{r}
if (exists("WB_GCMs") == FALSE) stop("Please specify GCMs for Water Balance")
source(here::here("scripts", "WaterBalance", "Daily_WB_batch_v2.R")) # Run the Water Balance Model
```
# Summary Plots
```{r Summary-Plots, message=FALSE, warning=FALSE, echo = FALSE, results=HIDE}
source(here::here("scripts", "SummaryPlots", "Summary plots.R"))
source(here::here("scripts", "SummaryPlots", "Summary WB plots.R"))
```
# Additional Tables and Plots
```{r Additional-plots-and-tables, message= FALSE, warning=FALSE, echo=FALSE, results=HIDE}
source(here::here("scripts", "Additional-tables-plots", "RSS_MACA_drought_char.R"))
source(here::here("scripts", "Additional-tables-plots", "Return_Events.R"))
source(here::here("scripts", "Additional-tables-plots", "FLI FBI phenology plots.R"))
source(here::here("scripts", "Additional-tables-plots", "RSS Audubon summary.R"))
```
# Create metadata and copy/delete files
```{r Copy-and-delete-files, message=FALSE, warning=FALSE}
# This script is for copying and pasting files and folders unique to an RSS to a local folder, for the purposes of using, sharing, or archiving products. Files are then deleted from the Climate_Futures repo so that files are not inadvertently overwritten or confused with products from a different site.
source(here::here("scripts", "Misc", "write_metadata.R"))
source(here::here("scripts", "Misc", "copy_paste_delete_files.R")) # copies files and folders to specified local folder
```