-
Notifications
You must be signed in to change notification settings - Fork 2
/
sp_chinook_ISU.Rmd
220 lines (198 loc) · 9.56 KB
/
sp_chinook_ISU.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
---
title: Columbia Spring Chinook Inseason Forecast for Counts 1/1-6/15 @ Bonneville Dam
author: Thomas Buehrens ([email protected])
output:
html_document:
code_folding: hide
fig_caption: yes
theme: cerulean
toc: yes
toc_depth: 3
toc_float: yes
pdf_document:
toc: yes
toc_depth: '3'
---
<script>
$(document).ready(function() {
$head = $('#header');
$head.prepend('<img src=\"https://privatelands.wdfw.wa.gov/wdfwlogo_clrnotxt.png"\" style=\"float: right;width: 150px;\"/>')
});
</script>
***
Last Updated `r format(Sys.time(), '%m/%d/%Y')`.
***
# Overview
This script fits Seasonal Auto-Regressive Integrated Moving Average (SARIMA) models to in-season salmon return data to predict total return. It does this by aggregating the run-size into two periods: counts prior to a particular date (often the date of the most recent observation), and counts after that date (i.e., the remainder of the run). It then predicts the remainder of the run using the pattern of abundance before and after that date in previous years, in conjunction with covariates. This software evaluates the model's skill at predicting the remainder of the runsize based on data collected up to a particular date. A forecast for the final year, including confidence intervals, is produced.
<!-- ## Setup -->
<!-- All analyses require R software [**(link)**](https://cran.r-project.org/) (v3.4.3) for data retrieval, data processing, and summarizing model results. Here we configure R to perform our analysis and generate our outputs -->
```{r set_options, echo = TRUE, message = FALSE}
options(width = 100)
knitr::opts_chunk$set(message = FALSE)
set.seed(123)
```
<!-- We also need a couple of helper functions which we will define -->
```{r load_funcs, message = FALSE, warning = FALSE,results = "hide"}
wd_functions<-"functions"
sapply(FUN = source, paste(wd_functions, list.files(wd_functions), sep="/"))
```
<!-- Here we will load & install packages we need to use (needs internet connection if packages not already installed) -->
```{r load_packages, message = FALSE, warning = FALSE,results = "hide"}
packages_list<-c("tidyverse"
,"forecast"
,"mgcv"
,"ggplot2"
,"MASS"
,"RColorBrewer"
,"kableExtra"
,"lubridate"
,"modelr"
,"kableExtra"
,"reshape2"
,"ggfortify"
,"clock"
,"smooth"
,"scales"
)
install_or_load_pack(pack = packages_list)
```
## User Inputs
Look at this section to see user inputs regarding the years and dates of data analyzed and covariates used.
```{r user_inputs_data, message = FALSE, warning = FALSE,results = "show"}
#=========
# Raw Data
#=========
yr_start<-2000
yr_end<-year(Sys.Date())
dam="BON"
species="Chin"
#===========================
# Summarization for analysis
#===========================
date_start_analysis<-ymd("2002/1/1") #this will be the first date of data used in the analysis (and this month/day first in years thereafter)
date_end_analysis<-ymd("2022/6/15") #this will be the last date of data used in the analysis (and this month/day last in years preceding)
forecast_period_start_m<-1 #this will be the month associated with the first month/day of the seasonal estimate period each year...can be after first data used to estimate it or the same
forecast_period_start_d<-1 #this will be the month day associated with the first month/day of the seasonal estimate period each year...can be after first data used to estimate it or the same
use_freshest_data = T #use all data up to "today" or only up to beginning of forecast period
covariates<-c("lag1_NPGO","lag2_NPGO","lag1_PDO","lag2_PDO","lag1_log_jCK","lag2_PC1")
#==================
#forecasting params
#==================
leave_yrs<- 12
covariates<-c("lag1_NPGO","lag2_NPGO","lag1_PDO","lag2_PDO","lag1_log_jCK","lag2_PC1")
plot_results = F
first_forecast_period = 2
write_model_summaries = TRUE
```
## Get Raw Data
Data is loaded here a a snapshot of the data used in the analysis (before aggregation into the two periods described) is provided.
```{r get_data, message=FALSE, warning=FALSE, results="show"}
dat<-get_dam_data(
yr_start = yr_start,
yr_end = yr_end,
dam = dam,
species = species
)
#=========================================================
#get PDO data
#=========================================================
PDO<-read_table("https://psl.noaa.gov/pdo/data/pdo.timeseries.ersstv5.csv",skip=1,col_names=F,comment="#")%>%
dplyr::rename(Date=X1,PDO=X2)%>%
filter(!PDO < -99)%>%
mutate(Date=as.Date(Date),Month=month(Date),Year=year(Date))%>%
group_by(Year)%>%
add_tally()%>%
#filter(!Month>6)%>% #use only spring (Jan-June) NPGO
#filter(!n < 12)%>% #use only complete years
group_by(Year)%>%
dplyr::summarise(PDO=mean(PDO))%>%
mutate(lag2_PDO = lag(PDO,2), lag1_PDO = lag(PDO,1))%>%
dplyr::select(year=Year,lag2_PDO, lag1_PDO)
# #=========================================================
# #get NPGO data
# #=========================================================
NPGO<-read_table("http://www.o3d.org/npgo/npgo.php",skip=29,col_names=F,comment="#")%>%
filter(!is.na(X2))%>%
dplyr::rename(Year=X1,Month=X2,NPGO=X3)%>%
mutate(Year=as.numeric(Year))%>%
group_by(Year)%>%
add_tally()%>%
#filter(!Month>6)%>% #use only spring (Jan-June) NPGO
filter(!n < 12)%>% #use only complete years
group_by(Year)%>%
dplyr::summarise(NPGO=mean(NPGO))%>%
mutate(Year=Year+1, lag1_NPGO = NPGO,lag2_NPGO = lag(NPGO))%>%
dplyr::select(year=Year,lag1_NPGO,lag2_NPGO)
#=========================================================
#get NOAA indicator data, wrangle into usable format, plot
#=========================================================
#indicators<-read_csv("https://media.fisheries.noaa.gov/2021-04/Stoplight%20csv.csv?null",skip=1)%>%
indicators<-read_csv("https://raw.githubusercontent.com/tbuehrens/Salmon_Forecast_Example/main/data/Stoplight%20csv.csv",skip=1)%>%
filter(!is.na(`Ecosystem Indicators`))%>%
pivot_longer(names_to = "Year",
cols=c(starts_with("1"),starts_with("2")),
values_to = "value")%>%
pivot_wider(names_from=`Ecosystem Indicators`,values_from=value)%>%
mutate(year=as.numeric(Year)+2, lag2_PC1 = scale(`Principal Component scores (PC1)`))%>%
dplyr::select(year,lag2_PC1)
#======
# Jacks
#======
jCK<-read_csv("http://www.cbr.washington.edu/dart/cs/php/rpt/adult_annual.php?sc=1&outputFormat=csv&proj=BON&startdate=1%2F1&enddate=6%2F15")%>%
arrange(Year)%>%
dplyr::select(year=Year, `Jack Chinook`)%>%
mutate(year = year+1, lag1_log_jCK = log(ifelse(`Jack Chinook`==0,NA,`Jack Chinook`)))%>%
filter(!is.na(year) & !is.na(lag1_log_jCK))%>%
dplyr::select(year,lag1_log_jCK)
#================================================================
dat<-dat%>%
left_join(PDO)%>%
left_join(NPGO)%>%
left_join(jCK)%>%
left_join(indicators)
print(head(dat))
```
<!-- ## Summarize Data for Analysis -->
```{r summarize_data, message=FALSE, warning=FALSE, results="show"}
series<-prepare_data(series = dat,
date_start_analysis = date_start_analysis,
date_end_analysis = date_end_analysis,
forecast_period_start_m = forecast_period_start_m, #inclusive
forecast_period_start_d = forecast_period_start_d, #inclusive
use_freshest_data = use_freshest_data,
covariates = covariates,
p1_covariates_only = NULL
)
```
## Results
This section present a a results table showing the performance of the prediction model in previous years as well as a forecast in the current year. The results in the table are graphed below.
```{r Analysis_v2, message=FALSE, warning=FALSE, results="show"}
results<-inseason_forecast(series$series,
leave_yrs,
covariates,
first_forecast_period = first_forecast_period,
plot_results = plot_results,
write_model_summaries = write_model_summaries,
forecast_period_start_m = forecast_period_start_m, #inclusive
forecast_period_start_d = forecast_period_start_d, #inclusive
obs_period_2 = series$obs_period_2,
p1_covariates_only=NULL
)
p_2_start_m<-series$p_2_start_m
p_2_start_d<-series$p_2_start_d
results%>%
ungroup()%>%
dplyr::select(!c("period","train_test"))%>%
kbl(caption = paste0("Table 2. Forecasts of ",dam," dam counts of ",species, " from ",forecast_period_start_m,"/",forecast_period_start_d,"-",month(date_end_analysis),"/",mday(date_end_analysis)," using only past years' data for the forecast period and in-season counts from ", month(date_start_analysis),"/",mday(date_start_analysis)," through ", month(max(dat$date)),"/",mday(max(dat$date)), " in each year. Additional covariates are included in the table below."),digits =2)%>%
kable_classic(full_width = F, html_font = "Cambria")
print(paste0("Mean Absolute Percent Error (MAPE) = ",mean(abs((results$error/results$abundance)*100),na.rm = T)))
print(paste0("Median Symmetric Accuracy; MSA) = ",100*(exp(median(abs(log(results$predicted_abundance/results$abundance)),na.rm = T))-1)))
p<-ggplot(results,aes(x=year,y=predicted_abundance))+
geom_ribbon(aes(ymin=`Lo 95`,ymax=`Hi 95`),color=NA,alpha=0.5,fill = "cadetblue")+
geom_ribbon(aes(ymin=`Lo 50`,ymax=`Hi 50`),color=NA,alpha=0.5,fill = "cadetblue")+
geom_line()+
geom_point(aes(x=year,y=abundance))+
scale_x_continuous(breaks=results$year)+
ylim(0,NA)
print(p)
```