├── .Rbuildignore ├── .github ├── .gitignore └── workflows │ ├── R-CMD-check.xxxyaml │ ├── check-standard.yaml │ └── test-coverage.yaml ├── .gitignore ├── DESCRIPTION ├── NAMESPACE ├── R ├── .DS_Store ├── .Rapp.history ├── atsar-package.R ├── fit_stan.R └── stanmodels.R ├── README-figs └── plot-1.png ├── README.Rmd ├── README.md ├── atsa.Rproj ├── configure ├── configure.win ├── docs ├── 404.html ├── articles │ ├── dlm.html │ ├── dlm_files │ │ ├── accessible-code-block-0.0.1 │ │ │ └── empty-anchor.js │ │ ├── figure-html │ │ │ └── unnamed-chunk-8-1.png │ │ └── header-attrs-2.9 │ │ │ └── header-attrs.js │ ├── fit_stan.html │ ├── fit_stan_files │ │ ├── accessible-code-block-0.0.1 │ │ │ └── empty-anchor.js │ │ ├── figure-html │ │ │ ├── unnamed-chunk-6-1.png │ │ │ └── unnamed-chunk-7-1.png │ │ └── header-attrs-2.9 │ │ │ └── header-attrs.js │ └── index.html ├── authors.html ├── bootstrap-toc.css ├── bootstrap-toc.js ├── docsearch.css ├── docsearch.js ├── extra.css ├── index.html ├── link.svg ├── pkgdown.css ├── pkgdown.js ├── pkgdown.yml └── reference │ ├── atsar-package.html │ ├── fit_stan.html │ └── index.html ├── inst ├── .DS_Store ├── include │ └── stan_meta_header.hpp ├── marss_example.R └── stan │ ├── .DS_Store │ ├── ar.stan │ ├── dlm.stan │ ├── dlm_int.stan │ ├── dlm_slope.stan │ ├── include │ └── license.stan │ ├── ma.stan │ ├── ma1.stan │ ├── marss.stan │ ├── regression.stan │ ├── regression_cor.stan │ ├── rw.stan │ ├── ss_ar.stan │ ├── ss_ar_mean.stan │ └── ss_rw.stan ├── man ├── atsar-package.Rd └── fit_stan.Rd ├── pkgdown └── extra.css ├── src ├── Makevars ├── Makevars.win ├── RcppExports.cpp ├── stanExports_ar.cc ├── stanExports_ar.h ├── stanExports_dlm.cc ├── stanExports_dlm.h ├── stanExports_dlm_int.cc ├── stanExports_dlm_int.h ├── stanExports_dlm_slope.cc ├── stanExports_dlm_slope.h ├── stanExports_ma.cc ├── stanExports_ma.h ├── stanExports_ma1.cc ├── stanExports_ma1.h ├── stanExports_marss.cc ├── stanExports_marss.h ├── stanExports_regression.cc ├── stanExports_regression.h ├── stanExports_regression_cor.cc ├── stanExports_regression_cor.h ├── stanExports_rw.cc ├── stanExports_rw.h ├── stanExports_ss_ar.cc ├── stanExports_ss_ar.h ├── stanExports_ss_ar_mean.cc ├── stanExports_ss_ar_mean.h ├── stanExports_ss_rw.cc └── stanExports_ss_rw.h ├── tests ├── tests.R └── testthat │ └── testfits.R └── vignettes ├── dlm.Rmd └── fit_stan.Rmd /.Rbuildignore: -------------------------------------------------------------------------------- 1 | ^.*\.Rproj$ 2 | ^\.Rproj\.user$ 3 | ^README.Rmd 4 | ^README-* 5 | ^README\.Rmd 6 | ^appveyor\.yml$ 7 | ^doc$ 8 | ^Meta$ 9 | ^\.github$ 10 | -------------------------------------------------------------------------------- /.github/.gitignore: -------------------------------------------------------------------------------- 1 | *.html 2 | -------------------------------------------------------------------------------- /.github/workflows/R-CMD-check.xxxyaml: -------------------------------------------------------------------------------- 1 | # For help debugging build failures open an issue on the RStudio community with the 'github-actions' tag. 2 | # https://community.rstudio.com/new-topic?category=Package%20development&tags=github-actions 3 | on: 4 | push: 5 | branches: 6 | - main 7 | - master 8 | pull_request: 9 | branches: 10 | - main 11 | - master 12 | 13 | name: R-CMD-check 14 | 15 | jobs: 16 | R-CMD-check: 17 | runs-on: ${{ matrix.config.os }} 18 | 19 | name: ${{ matrix.config.os }} (${{ matrix.config.r }}) 20 | 21 | strategy: 22 | fail-fast: false 23 | matrix: 24 | config: 25 | - {os: windows-latest, r: 'release'} 26 | - {os: macOS-latest, r: 'release'} 27 | - {os: ubuntu-20.04, r: 'release', rspm: "https://packagemanager.rstudio.com/cran/__linux__/focal/latest"} 28 | #- {os: ubuntu-20.04, r: 'devel', rspm: "https://packagemanager.rstudio.com/cran/__linux__/focal/latest"} 29 | 30 | env: 31 | R_REMOTES_NO_ERRORS_FROM_WARNINGS: true 32 | RSPM: ${{ matrix.config.rspm }} 33 | GITHUB_PAT: ${{ secrets.GITHUB_TOKEN }} 34 | 35 | steps: 36 | - uses: actions/checkout@v2 37 | 38 | - uses: r-lib/actions/setup-r@v2 39 | with: 40 | r-version: ${{ matrix.config.r }} 41 | 42 | - uses: r-lib/actions/setup-pandoc@v1 43 | 44 | - name: Query dependencies 45 | run: | 46 | install.packages('remotes') 47 | saveRDS(remotes::dev_package_deps(dependencies = TRUE), ".github/depends.Rds", version = 2) 48 | writeLines(sprintf("R-%i.%i", getRversion()$major, getRversion()$minor), ".github/R-version") 49 | shell: Rscript {0} 50 | 51 | - name: Cache R packages 52 | if: runner.os != 'Windows' 53 | uses: actions/cache@v2 54 | with: 55 | path: ${{ env.R_LIBS_USER }} 56 | key: ${{ runner.os }}-${{ hashFiles('.github/R-version') }}-1-${{ hashFiles('.github/depends.Rds') }} 57 | restore-keys: ${{ runner.os }}-${{ hashFiles('.github/R-version') }}-1- 58 | 59 | - name: Install system dependencies 60 | if: runner.os == 'Linux' 61 | run: | 62 | while read -r cmd 63 | do 64 | eval sudo $cmd 65 | done < <(Rscript -e 'writeLines(remotes::system_requirements("ubuntu", "20.04"))') 66 | 67 | - name: Install dependencies 68 | run: | 69 | remotes::install_deps(dependencies = TRUE) 70 | remotes::install_cran("rcmdcheck") 71 | shell: Rscript {0} 72 | 73 | - name: Check 74 | env: 75 | _R_CHECK_CRAN_INCOMING_REMOTE_: false 76 | run: rcmdcheck::rcmdcheck(args = c("--no-manual", "--as-cran"), error_on = "warning", check_dir = "check") 77 | shell: Rscript {0} 78 | 79 | - name: Upload check results 80 | if: failure() 81 | uses: actions/upload-artifact@main 82 | with: 83 | name: ${{ runner.os }}-r${{ matrix.config.r }}-results 84 | path: check 85 | -------------------------------------------------------------------------------- /.github/workflows/check-standard.yaml: -------------------------------------------------------------------------------- 1 | # Workflow derived from https://github.com/r-lib/actions/tree/v2/examples 2 | # Need help debugging build failures? Start at https://github.com/r-lib/actions#where-to-find-help 3 | on: 4 | push: 5 | branches: [main, master] 6 | pull_request: 7 | branches: [main, master] 8 | 9 | name: R-CMD-check 10 | 11 | jobs: 12 | R-CMD-check: 13 | runs-on: ${{ matrix.config.os }} 14 | 15 | name: ${{ matrix.config.os }} (${{ matrix.config.r }}) 16 | 17 | strategy: 18 | fail-fast: false 19 | matrix: 20 | config: 21 | - {os: macos-latest, r: 'release'} 22 | - {os: windows-latest, r: 'release'} 23 | - {os: ubuntu-latest, r: 'devel', http-user-agent: 'release'} 24 | - {os: ubuntu-latest, r: 'release'} 25 | - {os: ubuntu-latest, r: 'oldrel-1'} 26 | 27 | env: 28 | GITHUB_PAT: ${{ secrets.GITHUB_TOKEN }} 29 | R_KEEP_PKG_SOURCE: yes 30 | 31 | steps: 32 | - uses: actions/checkout@v3 33 | 34 | - uses: r-lib/actions/setup-pandoc@v2 35 | 36 | - uses: r-lib/actions/setup-r@v2 37 | with: 38 | r-version: ${{ matrix.config.r }} 39 | http-user-agent: ${{ matrix.config.http-user-agent }} 40 | use-public-rspm: true 41 | 42 | - uses: r-lib/actions/setup-r-dependencies@v2 43 | with: 44 | extra-packages: any::rcmdcheck 45 | needs: check 46 | 47 | - uses: r-lib/actions/check-r-package@v2 48 | with: 49 | upload-snapshots: true -------------------------------------------------------------------------------- /.github/workflows/test-coverage.yaml: -------------------------------------------------------------------------------- 1 | # Workflow derived from https://github.com/r-lib/actions/tree/v2/examples 2 | # Need help debugging build failures? Start at https://github.com/r-lib/actions#where-to-find-help 3 | on: 4 | push: 5 | branches: [main, master] 6 | pull_request: 7 | branches: [main, master] 8 | 9 | name: test-coverage 10 | 11 | permissions: read-all 12 | 13 | jobs: 14 | test-coverage: 15 | runs-on: ubuntu-latest 16 | env: 17 | GITHUB_PAT: ${{ secrets.GITHUB_TOKEN }} 18 | 19 | steps: 20 | - uses: actions/checkout@v4 21 | 22 | - uses: r-lib/actions/setup-r@v2 23 | with: 24 | use-public-rspm: true 25 | 26 | - uses: r-lib/actions/setup-r-dependencies@v2 27 | with: 28 | extra-packages: any::covr, any::xml2 29 | needs: coverage 30 | 31 | - name: Test coverage 32 | run: | 33 | cov <- covr::package_coverage( 34 | quiet = FALSE, 35 | clean = FALSE, 36 | install_path = file.path(normalizePath(Sys.getenv("RUNNER_TEMP"), winslash = "/"), "package") 37 | ) 38 | covr::to_cobertura(cov) 39 | shell: Rscript {0} 40 | 41 | - uses: codecov/codecov-action@v4 42 | with: 43 | fail_ci_if_error: ${{ github.event_name != 'pull_request' && true || false }} 44 | file: ./cobertura.xml 45 | plugin: noop 46 | disable_search: true 47 | token: ${{ secrets.CODECOV_TOKEN }} 48 | 49 | - name: Show testthat output 50 | if: always() 51 | run: | 52 | ## -------------------------------------------------------------------- 53 | find '${{ runner.temp }}/package' -name 'testthat.Rout*' -exec cat '{}' \; || true 54 | shell: bash 55 | 56 | - name: Upload test results 57 | if: failure() 58 | uses: actions/upload-artifact@v4 59 | with: 60 | name: coverage-test-failures 61 | path: ${{ runner.temp }}/package 62 | 63 | - name: Upload coverage reports to Codecov 64 | uses: codecov/codecov-action@v4.0.1 65 | with: 66 | token: ${{ secrets.CODECOV_TOKEN }} -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .Rproj.user 2 | .Rhistory 3 | .RData 4 | .Ruserdata 5 | doc 6 | Meta 7 | .DS_Store 8 | atsar.Rproj 9 | R/.DS_Store 10 | -------------------------------------------------------------------------------- /DESCRIPTION: -------------------------------------------------------------------------------- 1 | Package: atsar 2 | Type: Package 3 | Title: Stan Routines For Univariate And Multivariate Time Series 4 | Version: 0.1.6 5 | Authors@R: c( 6 | person(c("Eric", "J."), "Ward", role = c("aut", "cre"), 7 | email = "eric.ward@noaa.gov"), 8 | person(c("Mark", "D."), "Scheuerell", role = "aut"), 9 | person(c("Elizabeth", "E."), "Holmes", role = "aut"), 10 | person(c("Kiva", "L."), "Oken", role = "aut"), 11 | person("Trustees of", "Columbia University", role = "cph")) 12 | Maintainer: Eric J. Ward 13 | Description: Bundles univariate and multivariate STAN scripts for FISH 507 class. 14 | License: GPL (>=3) 15 | Depends: 16 | R (>= 3.4.0) 17 | Imports: 18 | methods, 19 | Rcpp (>= 0.12.18), 20 | RcppParallel (>= 5.0.1), 21 | rstan (>= 2.18.2), 22 | rstantools (>= 1.5.1), 23 | ggplot2, 24 | viridisLite, 25 | loo (>= 2.0.0), 26 | rlang (>= 0.3.1) 27 | LinkingTo: BH (>= 1.66.0), 28 | Rcpp (>= 0.12.18), 29 | RcppEigen (>= 0.3.3.3.0), 30 | RcppParallel (>= 5.0.1), 31 | rstan (>= 2.18.2), 32 | StanHeaders (>= 2.18.1) 33 | Suggests: 34 | testthat, 35 | knitr, 36 | rmarkdown 37 | Encoding: UTF-8 38 | LazyData: true 39 | URL: https://atsa-es.github.io/atsar/ 40 | BugReports: https://github.com/atsa-es/atsar/issues 41 | RoxygenNote: 7.2.3 42 | SystemRequirements: GNU make 43 | Biarch: true 44 | VignetteBuilder: knitr 45 | -------------------------------------------------------------------------------- /NAMESPACE: -------------------------------------------------------------------------------- 1 | # Generated by roxygen2: do not edit by hand 2 | 3 | export(fit_stan) 4 | import(Rcpp) 5 | import(methods) 6 | importFrom(rstan,sampling) 7 | useDynLib(atsar, .registration = TRUE) 8 | -------------------------------------------------------------------------------- /R/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/atsa-es/atsar/a423d23978dac21fd50a51339b60600aecc4b1d4/R/.DS_Store -------------------------------------------------------------------------------- /R/.Rapp.history: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/atsa-es/atsar/a423d23978dac21fd50a51339b60600aecc4b1d4/R/.Rapp.history -------------------------------------------------------------------------------- /R/atsar-package.R: -------------------------------------------------------------------------------- 1 | #' The 'atsar' package. 2 | #' 3 | #' @description A DESCRIPTION OF THE PACKAGE 4 | #' 5 | #' @docType package 6 | #' @name atsar-package 7 | #' @aliases atsar 8 | #' @useDynLib atsar, .registration = TRUE 9 | #' @import methods 10 | #' @import Rcpp 11 | #' @importFrom rstan sampling 12 | #' 13 | #' @references 14 | #' Stan Development Team (2020). RStan: the R interface to Stan. R package version 2.21.2. https://mc-stan.org 15 | #' 16 | NULL 17 | -------------------------------------------------------------------------------- /R/fit_stan.R: -------------------------------------------------------------------------------- 1 | #' fit_stan is the primary function which calls pre-written stan scripts for time series data. 2 | #' 3 | #' @param y The response variable (numeric) 4 | #' @param x The predictors, either a vector or matrix 5 | #' @param model_name The specific name of the model to be fitted. Currently supported are 'regression', 'ar', 'rw', 'ma', 'ss_ar' (state space univariate AR), or 'ss_rw' (state space univariate random walk). 6 | #' @param est_drift Whether or not to estimate a drift parameter (default = FALSE). Only applicable to the rw and ar models. 7 | #' @param est_mean Whether to estimate a mean or not (for state space autoregressive model only) 8 | #' @param P The order of the ar model, with minimum value = 1 (default). 9 | #' @param Q The order of the ma model, with minimum value = 1 (default). 10 | #' @param mcmc_list A list of MCMC control parameters. These include the number of 'iterations' (default = 1000), burn in or warmup (default = 500), chains (default = 3), and thinning (default = 1) 11 | #' @param family A named distribution for the observation model, defaults to gaussian 12 | #' @param est_nu Boolean, whether to model process deviations as Student-t or not (default). 13 | #' @param marss A named list containing the following elements for specifying marss models: (states=NULL, obsVariances=NULL, proVariances=NULL, trends=NULL 14 | #' @param map_estimation Whether to do maximum a posteriori estimation via [rstan::optimizing()] (defualts to FALSE) 15 | #' @param hessian Whether to return hessian if map_estimation is TRUE via [rstan::optimizing()] 16 | #' @param ... Any other arguments passed to [rstan::sampling()]. 17 | #' @return an object of class 'rstan' 18 | #' @importFrom rstan sampling 19 | #' @export 20 | #' 21 | fit_stan <- function(y, x = NA, model_name = NA, 22 | est_drift = FALSE, 23 | est_mean = FALSE, 24 | P = 1, 25 | Q = 1, 26 | mcmc_list = list(n_mcmc = 1000, n_burn = 500, n_chain = 3, n_thin = 1), 27 | family = "gaussian", 28 | est_nu = FALSE, 29 | marss = list(states = NULL, obsVariances = NULL, proVariances = NULL, trends = NULL), 30 | map_estimation = FALSE, 31 | hessian = FALSE, ...) { 32 | dist <- c("gaussian", "binomial", "poisson", "gamma", "lognormal") 33 | family <- which(dist == family) 34 | 35 | # process potential NAs in data 36 | if (!is.matrix(y)) { 37 | N <- length(y) 38 | pos_indx <- which(!is.na(y)) 39 | y <- y[pos_indx] 40 | n_pos <- length(pos_indx) 41 | # catch case where -- needs to be 2 elements for stan vec 42 | if (length(pos_indx) == 0) { 43 | pos_indx <- rep(0, 2) 44 | } else { 45 | pos_indx <- c(pos_indx, 0, 0) 46 | } 47 | 48 | if (length(pos_indx) != (length(y) + 2)) { 49 | # include any other errors? 50 | if (model_name %in% c("regression", "regression_cor", "ar", "rw", "ma", "arma11")) { 51 | stop("Error: data cannot contain NAs for the specified model") 52 | } 53 | } 54 | } 55 | 56 | data <- NA 57 | if (model_name == "regression") { 58 | if (is.matrix(x) == FALSE) x <- matrix(x, ncol = 1) 59 | object <- stanmodels$regression 60 | data <- list("N" = length(y), "K" = dim(x)[2], "x" = x, "y" = y, "y_int" = round(y), "family" = family) 61 | pars <- c("beta", "sigma", "pred", "log_lik") 62 | } 63 | if (model_name == "regression_cor") { 64 | if (is.matrix(x) == FALSE) x <- matrix(x, ncol = 1) 65 | object <- stanmodels$regression_cor 66 | data <- list("N" = length(y), "K" = dim(x)[2], "x" = x, "y" = y, "y_int" = round(y), "family" = family) 67 | pars <- c("beta", "sigma", "pred", "phi", "sigma_cor", "log_lik") 68 | } 69 | if (model_name == "rw") { 70 | object <- stanmodels$rw 71 | data <- list( 72 | "y" = y, "N" = length(y), est_drift = ifelse(est_drift == FALSE, 0, 1), 73 | est_nu = ifelse(est_nu == FALSE, 0, 1) 74 | ) 75 | pars <- c("sigma", "pred") 76 | if (est_drift == TRUE) pars <- c(pars, "mu") 77 | if (est_nu == TRUE) pars <- c(pars, "nu") 78 | } 79 | if (model_name == "ar") { 80 | object <- stanmodels$ar 81 | data <- list( 82 | "y" = y, "N" = length(y), est_drift = ifelse(est_drift == FALSE, 0, 1), 83 | est_nu = ifelse(est_nu == FALSE, 0, 1) 84 | ) 85 | pars <- c("sigma", "pred", "phi") 86 | if (est_drift == TRUE) pars <- c(pars, "mu") 87 | if (est_nu == TRUE) pars <- c(pars, "nu") 88 | } 89 | if (model_name == "ma" & Q == 1) { 90 | object <- stanmodels$ma1 91 | data <- list("y" = y, "N" = length(y), est_nu = ifelse(est_nu == FALSE, 0, 1)) 92 | pars <- c("sigma", "pred", "mu", "theta") 93 | if (est_nu == TRUE) pars <- c(pars, "nu") 94 | } 95 | if (model_name == "ma" & Q > 1) { 96 | object <- stanmodels$ma 97 | data <- list("Q" = Q, "y" = y, "N" = length(y), est_nu = ifelse(est_nu == FALSE, 0, 1)) 98 | pars <- c("sigma", "pred", "mu", "theta") 99 | if (est_nu == TRUE) pars <- c(pars, "nu") 100 | } 101 | if (model_name == "ss_rw") { 102 | object <- stanmodels$ss_rw 103 | data <- list( 104 | "y" = y, "N" = N, "n_pos" = n_pos, "pos_indx" = pos_indx, "y_int" = round(y), 105 | est_drift = ifelse(est_drift == FALSE, 0, 1), 106 | "family" = family, 107 | est_nu = ifelse(est_nu == FALSE, 0, 1) 108 | ) 109 | pars <- c("sigma_process", "pred", "sigma_obs") 110 | if (est_drift == TRUE) pars <- c(pars, "mu") 111 | if (est_nu == TRUE) pars <- c(pars, "nu") 112 | } 113 | if (model_name == "ss_ar" & est_mean == FALSE) { 114 | object <- stanmodels$ss_ar 115 | data <- list( 116 | "y" = y, "N" = N, "n_pos" = n_pos, "pos_indx" = pos_indx, "y_int" = round(y), 117 | est_drift = ifelse(est_drift == FALSE, 0, 1), 118 | "family" = family, 119 | est_nu = ifelse(est_nu == FALSE, 0, 1) 120 | ) 121 | pars <- c("sigma_process", "pred", "sigma_obs", "phi") 122 | if (est_drift == TRUE) pars <- c(pars, "mu") 123 | if (est_nu == TRUE) pars <- c(pars, "nu") 124 | } 125 | if (model_name == "ss_ar" & est_mean == TRUE) { 126 | object <- stanmodels$ss_ar_mean 127 | data <- list( 128 | "y" = y, "N" = N, "n_pos" = n_pos, "pos_indx" = pos_indx, "y_int" = round(y), 129 | "family" = family, 130 | est_nu = ifelse(est_nu == FALSE, 0, 1) 131 | ) 132 | pars <- c("sigma_process", "pred", "sigma_obs", "mu", "phi") 133 | if (est_nu == TRUE) pars <- c(pars, "nu") 134 | } 135 | # if(model_name == "arma11") { 136 | # object <- stanmodels$arma11 137 | # data <- list("y"=y,"N"=length(y)) 138 | # pars <- c("sigma", "theta", "mu", "phi") 139 | # } 140 | if (model_name == "dlm-intercept") { 141 | object <- stanmodels$dlm_int 142 | # constant slope, and time -varying intercept model 143 | if (is.na(x)) { 144 | x <- matrix(0, nrow = length(y), ncol = 1) 145 | } 146 | if (is.matrix(x) == FALSE) x <- matrix(x, ncol = 1) 147 | data <- list("N" = N, "K" = dim(x)[2], "x" = x, "y" = y, "y_int" = round(y), "family" = family, "n_pos" = n_pos, "pos_indx" = pos_indx) 148 | pars <- c("beta", "sigma_obs", "sigma_process", "pred", "intercept", "log_lik") 149 | } 150 | if (model_name == "dlm-slope") { 151 | object <- stanmodels$dlm_slope 152 | # constant estimated intercept, and time varying slopes 153 | if (is.matrix(x) == FALSE) x <- matrix(x, ncol = 1) 154 | data <- list("N" = N, "K" = dim(x)[2], "x" = x, "y" = y, "y_int" = round(y), "family" = family, "n_pos" = n_pos, "pos_indx" = pos_indx) 155 | pars <- c("beta", "sigma_obs", "sigma_process", "pred", "log_lik") 156 | } 157 | if (model_name == "dlm") { 158 | object <- stanmodels$dlm 159 | # this is just a time-varying model with time varying intercept and slopes 160 | if (is.matrix(x) == FALSE) x <- matrix(x, ncol = 1) 161 | data <- list("N" = N, "K" = dim(x)[2], "x" = x, "y" = y, "y_int" = round(y), "family" = family, "n_pos" = n_pos, "pos_indx" = pos_indx) 162 | pars <- c("beta", "sigma_obs", "sigma_process", "pred", "log_lik") 163 | } 164 | if (model_name == "marss") { 165 | object <- stanmodels$marss 166 | if (is.null(marss$states)) marss$states <- rep(1, nrow(y)) 167 | if(length(marss$states) != nrow(y)) stop("Error: state vector must be same length as number of time series in y") 168 | if (is.null(marss$obsVariances)) marss$obsVariances <- rep(1, nrow(y)) 169 | if(length(marss$obsVariances) != nrow(y)) stop("Error: vector of observation error variances must be same length as number of time series in y") 170 | if (is.null(marss$proVariances)) marss$proVariances <- rep(1, max(marss$states)) 171 | if(length(marss$proVariances) < max(marss$states)) stop("Error: vector of process error variances is fewer than the number of states") 172 | if(length(marss$proVariances) > max(marss$states)) stop("Error: vector of process error variances is larger than the number of states") 173 | if (is.null(marss$trends)) marss$trends <- rep(1, max(marss$states)) 174 | if(length(marss$trends) < max(marss$states)) stop("Error: vector of trends is fewer than the number of states") 175 | if(length(marss$trends) > max(marss$states)) stop("Error: vector of trends is larger than the number of states") 176 | if (marss$est_trend == FALSE) est_trend = FALSE 177 | if (marss$est_trend == TRUE) est_trend = TRUE 178 | if (marss$est_B == FALSE) est_B = FALSE 179 | if (marss$est_B == TRUE) est_B = TRUE 180 | proVariances <- c(marss$proVariances, 0) # to keep types in stan constant 181 | trends <- c(marss$trends, 0) # to keep types in stan constant 182 | N <- ncol(y) 183 | M <- nrow(y) 184 | row_indx_pos <- matrix((rep(1:M, N)), M, N)[which(!is.na(y))] 185 | col_indx_pos <- matrix(sort(rep(1:N, M)), M, N)[which(!is.na(y))] 186 | n_pos <- length(row_indx_pos) 187 | y <- y[which(!is.na(y))] 188 | 189 | est_A <- rep(1, M) 190 | for(i in 1:max(marss$states)) { 191 | indx <- which(marss$states==i) 192 | est_A[indx[1]] <- 0 193 | } 194 | est_A <- which(est_A > 0) 195 | est_A <- c(est_A, 0) 196 | n_A <- length(est_A) - 1 197 | 198 | data = list("N"=N,"M"=M, "y"=y, 199 | "states"=marss$states, "S" = max(marss$states), "obsVariances"=marss$obsVariances, 200 | "n_obsvar" = max(marss$obsVariances), "proVariances" = proVariances, 201 | "n_provar" = max(proVariances), 202 | "trends"=trends, "n_trends" = max(trends), 203 | "n_pos" = n_pos, 204 | "col_indx_pos" = col_indx_pos, 205 | "row_indx_pos" = row_indx_pos, 206 | "est_A" = est_A, 207 | "n_A" = n_A, 208 | "y_int"=round(y), 209 | "family"=1, 210 | "est_trend" = as.numeric(est_trend), 211 | "est_B" = as.numeric(est_B)) 212 | 213 | pars = c("pred", "log_lik","sigma_process","sigma_obs","x0") 214 | if(marss$est_B) pars = c(pars, "B") 215 | if(marss$est_trend) pars = c(pars, "U") 216 | if(n_A > 0) pars = c(pars,"A") 217 | } 218 | if (map_estimation == FALSE) { 219 | out <- rstan::sampling( 220 | object = object, 221 | data = data, 222 | pars = pars, 223 | control = list(adapt_delta = 0.95, max_treedepth = 13), 224 | warmup = mcmc_list$n_burn, 225 | iter = mcmc_list$n_mcmc, 226 | thin = mcmc_list$n_thin, 227 | chains = mcmc_list$n_chain, ... 228 | ) 229 | } else { 230 | out <- rstan::optimizing( 231 | object = object, 232 | data = data, 233 | hessian = hessian, ... 234 | ) 235 | } 236 | 237 | return(out) 238 | } 239 | -------------------------------------------------------------------------------- /R/stanmodels.R: -------------------------------------------------------------------------------- 1 | # Generated by rstantools. Do not edit by hand. 2 | 3 | # names of stan models 4 | stanmodels <- c("ar", "dlm", "dlm_int", "dlm_slope", "ma", "ma1", "marss", "regression", "regression_cor", "rw", "ss_ar", "ss_ar_mean", "ss_rw") 5 | 6 | # load each stan module 7 | Rcpp::loadModule("stan_fit4ar_mod", what = TRUE) 8 | Rcpp::loadModule("stan_fit4dlm_mod", what = TRUE) 9 | Rcpp::loadModule("stan_fit4dlm_int_mod", what = TRUE) 10 | Rcpp::loadModule("stan_fit4dlm_slope_mod", what = TRUE) 11 | Rcpp::loadModule("stan_fit4ma_mod", what = TRUE) 12 | Rcpp::loadModule("stan_fit4ma1_mod", what = TRUE) 13 | Rcpp::loadModule("stan_fit4marss_mod", what = TRUE) 14 | Rcpp::loadModule("stan_fit4regression_mod", what = TRUE) 15 | Rcpp::loadModule("stan_fit4regression_cor_mod", what = TRUE) 16 | Rcpp::loadModule("stan_fit4rw_mod", what = TRUE) 17 | Rcpp::loadModule("stan_fit4ss_ar_mod", what = TRUE) 18 | Rcpp::loadModule("stan_fit4ss_ar_mean_mod", what = TRUE) 19 | Rcpp::loadModule("stan_fit4ss_rw_mod", what = TRUE) 20 | 21 | # instantiate each stanmodel object 22 | stanmodels <- sapply(stanmodels, function(model_name) { 23 | # create C++ code for stan model 24 | stan_file <- if(dir.exists("stan")) "stan" else file.path("inst", "stan") 25 | stan_file <- file.path(stan_file, paste0(model_name, ".stan")) 26 | stanfit <- rstan::stanc_builder(stan_file, 27 | allow_undefined = TRUE, 28 | obfuscate_model_name = FALSE) 29 | stanfit$model_cpp <- list(model_cppname = stanfit$model_name, 30 | model_cppcode = stanfit$cppcode) 31 | # create stanmodel object 32 | methods::new(Class = "stanmodel", 33 | model_name = stanfit$model_name, 34 | model_code = stanfit$model_code, 35 | model_cpp = stanfit$model_cpp, 36 | mk_cppmodule = function(x) get(paste0("rstantools_model_", model_name))) 37 | }) 38 | -------------------------------------------------------------------------------- /README-figs/plot-1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/atsa-es/atsar/a423d23978dac21fd50a51339b60600aecc4b1d4/README-figs/plot-1.png -------------------------------------------------------------------------------- /README.Rmd: -------------------------------------------------------------------------------- 1 | --- 2 | output: 3 | md_document: 4 | variant: gfm 5 | --- 6 | 7 | ```{r, echo = FALSE} 8 | knitr::opts_chunk$set( 9 | collapse = TRUE, 10 | comment = "#>", 11 | fig.path = "README-figs/", 12 | cache.path = "README-cache/" 13 | ) 14 | ``` 15 | 16 | 17 | [![atsar status badge](https://atsa-es.r-universe.dev/badges/atsar)](https://atsa-es.r-universe.dev)[![R-CMD-check](https://github.com/nwfsc-timeseries/atsar/workflows/R-CMD-check/badge.svg)](https://github.com/nwfsc-timeseries/atsar/actions) 18 | 19 | 20 | 21 | [![Codecov test coverage](https://codecov.io/gh/atsa-es/atsar/branch/master/graph/badge.svg)](https://app.codecov.io/gh/atsa-es/atsar?branch=master) 22 | 23 | 24 | 41 | 42 | 50 | 51 | The atsar R package implements Bayesian time series models using Stan, primarily for illustrative purposes and teaching (University of Washington's Fish 507, Winter quarters). The Stan webpage, and appropriate citation guidelines are [here](http://mc-stan.org/). 52 | 53 | 54 | ### INSTALL {#install} 55 | 56 | # Install atsar from the atsa-es r-universe repository (binaries for Windows and Mac-Intel) 57 | ``` 58 | install.packages('atsar', repos = c('https://atsa-es.r-universe.dev', 'https://cloud.r-project.org')) 59 | ``` 60 | 61 | You can build the development version of the package from the source here. Note you need to use this if you have a M1/M2 Mac. 62 | 63 | ```{r, eval=FALSE} 64 | # install.packages("remotes") 65 | remotes::install_github("nwfsc-timeseries/atsar") 66 | ``` 67 | 68 | ### EXAMPLE {#example} 69 | 70 | Simulate data: 71 | 72 | ```{r simulate} 73 | library(rstan) 74 | library(atsar) 75 | set.seed(123) 76 | s = cumsum(rnorm(50)) 77 | ``` 78 | 79 | ```{r plot} 80 | plot(s) 81 | ``` 82 | 83 | Fit several models to this data: 84 | 85 | ```{r fit, eval = FALSE} 86 | # Regression, no slope 87 | regression_model = fit_stan(y = s, x = model.matrix(lm(s~1)), model_name="regression") 88 | 89 | # Regression, with slope 90 | regression_model = fit_stan(y = s, x = model.matrix(lm(s~seq(1,length(s)))), model_name="regression") 91 | 92 | # AR(1) time series model 93 | ar1_model = fit_stan(y = s, est_drift=FALSE, P = 1, model_name = "ar") 94 | 95 | # ARMA(1,1) time series model 96 | arma1_model = fit_stan(y = s, model_name = "arma11") 97 | 98 | # univariate ss model -- without drift but mean reversion estimated 99 | ss_model = fit_stan(y = s, model_name = "ss_ar", est_drift=FALSE) 100 | ``` 101 | 102 | To see the Stan mode code behind each of these, look in the `inst/stan` folder on the GitHub repository. Note that `fit_stan.R` does some data preparation to deal with Stan not accepting NAs in the data. 103 | 104 | ### DOCUMENTATION {#documentation} 105 | 106 | - [ATSA lab book](https://nwfsc-timeseries.github.io/atsa-labs/) - Many applications are covered in our Applied Time Series Analysis book developed from the labs in our course. 107 | - [ATSA course website](https://nwfsc-timeseries.github.io/atsa/) - We have lectures and all material from our course on our course website. 108 | - Additional information can be found on the NWFSC time series page which includes several additional books and packages, 109 | [NWFSC time series page](https://nwfsc-timeseries.github.io/) 110 | 111 | ### CITATION {#citation} 112 | 113 | Ward, E.J., M.D. Scheuerell, and E.E. Holmes. 2018. 'atsar': Applied Time Series Analysis in R: an introduction to time series analysis for ecological and fisheries data with Stan. [![DOI](https://zenodo.org/badge/DOI/10.5281/zenodo.1158021.svg)](https://doi.org/10.5281/zenodo.1158021) 114 | 115 | ### NOAA Disclaimer 116 | 117 | This repository is a scientific product and is not official communication of the National Oceanic and 118 | Atmospheric Administration, or the United States Department of Commerce. All NOAA GitHub project code is 119 | provided on an ‘as is’ basis and the user assumes responsibility for its use. Any claims against the Department of 120 | Commerce or Department of Commerce bureaus stemming from the use of this GitHub project will be governed 121 | by all applicable Federal law. Any reference to specific commercial products, processes, or services by service 122 | mark, trademark, manufacturer, or otherwise, does not constitute or imply their endorsement, recommendation or 123 | favoring by the Department of Commerce. The Department of Commerce seal and logo, or the seal and logo of a 124 | DOC bureau, shall not be used in any manner to imply endorsement of any commercial product or activity by 125 | DOC or the United States Government. 126 | 127 | NOAA Fisheries 128 | 129 | [U.S. Department of Commerce](https://www.commerce.gov/) | [National Oceanographic and Atmospheric Administration](https://www.noaa.gov) | [NOAA Fisheries](https://www.fisheries.noaa.gov/) 130 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | [![atsar status 2 | badge](https://atsa-es.r-universe.dev/badges/atsar)](https://atsa-es.r-universe.dev)[![R-CMD-check](https://github.com/nwfsc-timeseries/atsar/workflows/R-CMD-check/badge.svg)](https://github.com/nwfsc-timeseries/atsar/actions) 3 | 4 | 5 | [![Codecov test 6 | coverage](https://codecov.io/gh/atsa-es/atsar/branch/master/graph/badge.svg)](https://app.codecov.io/gh/atsa-es/atsar?branch=master) 7 | 8 | 9 | 26 | 46 | 47 | The atsar R package implements Bayesian time series models using Stan, 48 | primarily for illustrative purposes and teaching (University of 49 | Washington’s Fish 507, Winter quarters). The Stan webpage, and 50 | appropriate citation guidelines are [here](http://mc-stan.org/). 51 | 52 | ### INSTALL 53 | 54 | # Install atsar from the atsa-es r-universe repository (binaries for Windows and Mac-Intel) 55 | 56 | install.packages('atsar', repos = c('https://atsa-es.r-universe.dev', 'https://cloud.r-project.org')) 57 | 58 | You can build the development version of the package from the source 59 | here. Note you need to use this if you have a M1/M2 Mac. 60 | 61 | ``` r 62 | # install.packages("remotes") 63 | remotes::install_github("nwfsc-timeseries/atsar") 64 | ``` 65 | 66 | ### EXAMPLE 67 | 68 | Simulate data: 69 | 70 | ``` r 71 | library(rstan) 72 | #> Warning: package 'rstan' was built under R version 4.3.2 73 | #> Loading required package: StanHeaders 74 | #> Warning: package 'StanHeaders' was built under R version 4.3.2 75 | #> 76 | #> rstan version 2.32.6 (Stan version 2.32.2) 77 | #> For execution on a local, multicore CPU with excess RAM we recommend calling 78 | #> options(mc.cores = parallel::detectCores()). 79 | #> To avoid recompilation of unchanged Stan programs, we recommend calling 80 | #> rstan_options(auto_write = TRUE) 81 | #> For within-chain threading using `reduce_sum()` or `map_rect()` Stan functions, 82 | #> change `threads_per_chain` option: 83 | #> rstan_options(threads_per_chain = 1) 84 | library(atsar) 85 | set.seed(123) 86 | s = cumsum(rnorm(50)) 87 | ``` 88 | 89 | ``` r 90 | plot(s) 91 | ``` 92 | 93 | ![](README-figs/plot-1.png) 94 | 95 | Fit several models to this data: 96 | 97 | ``` r 98 | # Regression, no slope 99 | regression_model = fit_stan(y = s, x = model.matrix(lm(s~1)), model_name="regression") 100 | 101 | # Regression, with slope 102 | regression_model = fit_stan(y = s, x = model.matrix(lm(s~seq(1,length(s)))), model_name="regression") 103 | 104 | # AR(1) time series model 105 | ar1_model = fit_stan(y = s, est_drift=FALSE, P = 1, model_name = "ar") 106 | 107 | # ARMA(1,1) time series model 108 | arma1_model = fit_stan(y = s, model_name = "arma11") 109 | 110 | # univariate ss model -- without drift but mean reversion estimated 111 | ss_model = fit_stan(y = s, model_name = "ss_ar", est_drift=FALSE) 112 | ``` 113 | 114 | To see the Stan mode code behind each of these, look in the `inst/stan` 115 | folder on the GitHub repository. Note that `fit_stan.R` does some data 116 | preparation to deal with Stan not accepting NAs in the data. 117 | 118 | ### DOCUMENTATION 119 | 120 | - [ATSA lab book](https://nwfsc-timeseries.github.io/atsa-labs/) - Many 121 | applications are covered in our Applied Time Series Analysis book 122 | developed from the labs in our course. 123 | - [ATSA course website](https://nwfsc-timeseries.github.io/atsa/) - We 124 | have lectures and all material from our course on our course website. 125 | - Additional information can be found on the NWFSC time series page 126 | which includes several additional books and packages, [NWFSC time 127 | series page](https://nwfsc-timeseries.github.io/) 128 | 129 | ### CITATION 130 | 131 | Ward, E.J., M.D. Scheuerell, and E.E. Holmes. 2018. ‘atsar’: Applied 132 | Time Series Analysis in R: an introduction to time series analysis for 133 | ecological and fisheries data with Stan. 134 | [![DOI](https://zenodo.org/badge/DOI/10.5281/zenodo.1158021.svg)](https://doi.org/10.5281/zenodo.1158021) 135 | 136 | ### NOAA Disclaimer 137 | 138 | This repository is a scientific product and is not official 139 | communication of the National Oceanic and Atmospheric Administration, or 140 | the United States Department of Commerce. All NOAA GitHub project code 141 | is provided on an ‘as is’ basis and the user assumes responsibility for 142 | its use. Any claims against the Department of Commerce or Department of 143 | Commerce bureaus stemming from the use of this GitHub project will be 144 | governed by all applicable Federal law. Any reference to specific 145 | commercial products, processes, or services by service mark, trademark, 146 | manufacturer, or otherwise, does not constitute or imply their 147 | endorsement, recommendation or favoring by the Department of Commerce. 148 | The Department of Commerce seal and logo, or the seal and logo of a DOC 149 | bureau, shall not be used in any manner to imply endorsement of any 150 | commercial product or activity by DOC or the United States Government. 151 | 152 | NOAA Fisheries 153 | 154 | [U.S. Department of Commerce](https://www.commerce.gov/) \| [National 155 | Oceanographic and Atmospheric Administration](https://www.noaa.gov) \| 156 | [NOAA Fisheries](https://www.fisheries.noaa.gov/) 157 | -------------------------------------------------------------------------------- /atsa.Rproj: -------------------------------------------------------------------------------- 1 | Version: 1.0 2 | 3 | RestoreWorkspace: Default 4 | SaveWorkspace: Default 5 | AlwaysSaveHistory: Default 6 | 7 | EnableCodeIndexing: Yes 8 | UseSpacesForTab: Yes 9 | NumSpacesForTab: 2 10 | Encoding: UTF-8 11 | 12 | RnwWeave: Sweave 13 | LaTeX: pdfLaTeX 14 | 15 | BuildType: Package 16 | PackageUseDevtools: Yes 17 | PackageInstallArgs: --no-multiarch --with-keep.source 18 | -------------------------------------------------------------------------------- /configure: -------------------------------------------------------------------------------- 1 | # Generated by rstantools. Do not edit by hand. 2 | 3 | #! /bin/sh 4 | "${R_HOME}/bin/Rscript" -e "rstantools::rstan_config()" 5 | -------------------------------------------------------------------------------- /configure.win: -------------------------------------------------------------------------------- 1 | # Generated by rstantools. Do not edit by hand. 2 | 3 | #! /bin/sh 4 | "${R_HOME}/bin${R_ARCH_BIN}/Rscript.exe" -e "rstantools::rstan_config()" 5 | -------------------------------------------------------------------------------- /docs/404.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | Page not found (404) • atsar 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 | 57 | 58 | 59 | 60 | 61 | 62 | 63 |
64 |
65 | 119 | 120 | 121 | 122 |
123 | 124 |
125 |
126 | 129 | 130 | Content not found. Please use links in the navbar. 131 | 132 |
133 | 134 | 139 | 140 |
141 | 142 | 143 | 144 |
145 | 148 | 149 |
150 |

Site built with pkgdown 1.6.1.

151 |
152 | 153 |
154 |
155 | 156 | 157 | 158 | 159 | 160 | 161 | 162 | 163 | -------------------------------------------------------------------------------- /docs/articles/dlm_files/accessible-code-block-0.0.1/empty-anchor.js: -------------------------------------------------------------------------------- 1 | // Hide empty tag within highlighted CodeBlock for screen reader accessibility (see https://github.com/jgm/pandoc/issues/6352#issuecomment-626106786) --> 2 | // v0.0.1 3 | // Written by JooYoung Seo (jooyoung@psu.edu) and Atsushi Yasumoto on June 1st, 2020. 4 | 5 | document.addEventListener('DOMContentLoaded', function() { 6 | const codeList = document.getElementsByClassName("sourceCode"); 7 | for (var i = 0; i < codeList.length; i++) { 8 | var linkList = codeList[i].getElementsByTagName('a'); 9 | for (var j = 0; j < linkList.length; j++) { 10 | if (linkList[j].innerHTML === "") { 11 | linkList[j].setAttribute('aria-hidden', 'true'); 12 | } 13 | } 14 | } 15 | }); 16 | -------------------------------------------------------------------------------- /docs/articles/dlm_files/figure-html/unnamed-chunk-8-1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/atsa-es/atsar/a423d23978dac21fd50a51339b60600aecc4b1d4/docs/articles/dlm_files/figure-html/unnamed-chunk-8-1.png -------------------------------------------------------------------------------- /docs/articles/dlm_files/header-attrs-2.9/header-attrs.js: -------------------------------------------------------------------------------- 1 | // Pandoc 2.9 adds attributes on both header and div. We remove the former (to 2 | // be compatible with the behavior of Pandoc < 2.8). 3 | document.addEventListener('DOMContentLoaded', function(e) { 4 | var hs = document.querySelectorAll("div.section[class*='level'] > :first-child"); 5 | var i, h, a; 6 | for (i = 0; i < hs.length; i++) { 7 | h = hs[i]; 8 | if (!/^h[1-6]$/i.test(h.tagName)) continue; // it should be a header h1-h6 9 | a = h.attributes; 10 | while (a.length > 0) h.removeAttribute(a[0].name); 11 | } 12 | }); 13 | -------------------------------------------------------------------------------- /docs/articles/fit_stan_files/accessible-code-block-0.0.1/empty-anchor.js: -------------------------------------------------------------------------------- 1 | // Hide empty tag within highlighted CodeBlock for screen reader accessibility (see https://github.com/jgm/pandoc/issues/6352#issuecomment-626106786) --> 2 | // v0.0.1 3 | // Written by JooYoung Seo (jooyoung@psu.edu) and Atsushi Yasumoto on June 1st, 2020. 4 | 5 | document.addEventListener('DOMContentLoaded', function() { 6 | const codeList = document.getElementsByClassName("sourceCode"); 7 | for (var i = 0; i < codeList.length; i++) { 8 | var linkList = codeList[i].getElementsByTagName('a'); 9 | for (var j = 0; j < linkList.length; j++) { 10 | if (linkList[j].innerHTML === "") { 11 | linkList[j].setAttribute('aria-hidden', 'true'); 12 | } 13 | } 14 | } 15 | }); 16 | -------------------------------------------------------------------------------- /docs/articles/fit_stan_files/figure-html/unnamed-chunk-6-1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/atsa-es/atsar/a423d23978dac21fd50a51339b60600aecc4b1d4/docs/articles/fit_stan_files/figure-html/unnamed-chunk-6-1.png -------------------------------------------------------------------------------- /docs/articles/fit_stan_files/figure-html/unnamed-chunk-7-1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/atsa-es/atsar/a423d23978dac21fd50a51339b60600aecc4b1d4/docs/articles/fit_stan_files/figure-html/unnamed-chunk-7-1.png -------------------------------------------------------------------------------- /docs/articles/fit_stan_files/header-attrs-2.9/header-attrs.js: -------------------------------------------------------------------------------- 1 | // Pandoc 2.9 adds attributes on both header and div. We remove the former (to 2 | // be compatible with the behavior of Pandoc < 2.8). 3 | document.addEventListener('DOMContentLoaded', function(e) { 4 | var hs = document.querySelectorAll("div.section[class*='level'] > :first-child"); 5 | var i, h, a; 6 | for (i = 0; i < hs.length; i++) { 7 | h = hs[i]; 8 | if (!/^h[1-6]$/i.test(h.tagName)) continue; // it should be a header h1-h6 9 | a = h.attributes; 10 | while (a.length > 0) h.removeAttribute(a[0].name); 11 | } 12 | }); 13 | -------------------------------------------------------------------------------- /docs/articles/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | Articles • atsar 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 | 57 | 58 | 59 | 60 | 61 | 62 | 63 |
64 |
65 | 119 | 120 | 121 | 122 |
123 | 124 |
125 |
126 | 129 | 130 |
131 |

All vignettes

132 |

133 | 134 |
135 |
Dynamic linear models in package atsar
136 |
137 |
Fitting time series models in package atsar
138 |
139 |
140 |
141 |
142 |
143 | 144 | 145 |
146 | 149 | 150 |
151 |

Site built with pkgdown 1.6.1.

152 |
153 | 154 |
155 |
156 | 157 | 158 | 159 | 160 | 161 | 162 | 163 | 164 | -------------------------------------------------------------------------------- /docs/authors.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | Authors • atsar 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 | 57 | 58 | 59 | 60 | 61 | 62 | 63 |
64 |
65 | 119 | 120 | 121 | 122 |
123 | 124 |
125 |
126 | 129 | 130 |
    131 |
  • 132 |

    Eric J. Ward. Author, maintainer. 133 |

    134 |
  • 135 |
  • 136 |

    Mark D. Scheuerell. Author. 137 |

    138 |
  • 139 |
  • 140 |

    Elizabeth E. Holmes. Author. 141 |

    142 |
  • 143 |
  • 144 |

    Kiva L. Oken. Author. 145 |

    146 |
  • 147 |
  • 148 |

    Trustees of Columbia University. Copyright holder. 149 |

    150 |
  • 151 |
152 | 153 |
154 | 155 |
156 | 157 | 158 | 159 |
160 | 163 | 164 |
165 |

Site built with pkgdown 1.6.1.

166 |
167 | 168 |
169 |
170 | 171 | 172 | 173 | 174 | 175 | 176 | 177 | 178 | -------------------------------------------------------------------------------- /docs/bootstrap-toc.css: -------------------------------------------------------------------------------- 1 | /*! 2 | * Bootstrap Table of Contents v0.4.1 (http://afeld.github.io/bootstrap-toc/) 3 | * Copyright 2015 Aidan Feldman 4 | * Licensed under MIT (https://github.com/afeld/bootstrap-toc/blob/gh-pages/LICENSE.md) */ 5 | 6 | /* modified from https://github.com/twbs/bootstrap/blob/94b4076dd2efba9af71f0b18d4ee4b163aa9e0dd/docs/assets/css/src/docs.css#L548-L601 */ 7 | 8 | /* All levels of nav */ 9 | nav[data-toggle='toc'] .nav > li > a { 10 | display: block; 11 | padding: 4px 20px; 12 | font-size: 13px; 13 | font-weight: 500; 14 | color: #767676; 15 | } 16 | nav[data-toggle='toc'] .nav > li > a:hover, 17 | nav[data-toggle='toc'] .nav > li > a:focus { 18 | padding-left: 19px; 19 | color: #563d7c; 20 | text-decoration: none; 21 | background-color: transparent; 22 | border-left: 1px solid #563d7c; 23 | } 24 | nav[data-toggle='toc'] .nav > .active > a, 25 | nav[data-toggle='toc'] .nav > .active:hover > a, 26 | nav[data-toggle='toc'] .nav > .active:focus > a { 27 | padding-left: 18px; 28 | font-weight: bold; 29 | color: #563d7c; 30 | background-color: transparent; 31 | border-left: 2px solid #563d7c; 32 | } 33 | 34 | /* Nav: second level (shown on .active) */ 35 | nav[data-toggle='toc'] .nav .nav { 36 | display: none; /* Hide by default, but at >768px, show it */ 37 | padding-bottom: 10px; 38 | } 39 | nav[data-toggle='toc'] .nav .nav > li > a { 40 | padding-top: 1px; 41 | padding-bottom: 1px; 42 | padding-left: 30px; 43 | font-size: 12px; 44 | font-weight: normal; 45 | } 46 | nav[data-toggle='toc'] .nav .nav > li > a:hover, 47 | nav[data-toggle='toc'] .nav .nav > li > a:focus { 48 | padding-left: 29px; 49 | } 50 | nav[data-toggle='toc'] .nav .nav > .active > a, 51 | nav[data-toggle='toc'] .nav .nav > .active:hover > a, 52 | nav[data-toggle='toc'] .nav .nav > .active:focus > a { 53 | padding-left: 28px; 54 | font-weight: 500; 55 | } 56 | 57 | /* from https://github.com/twbs/bootstrap/blob/e38f066d8c203c3e032da0ff23cd2d6098ee2dd6/docs/assets/css/src/docs.css#L631-L634 */ 58 | nav[data-toggle='toc'] .nav > .active > ul { 59 | display: block; 60 | } 61 | -------------------------------------------------------------------------------- /docs/bootstrap-toc.js: -------------------------------------------------------------------------------- 1 | /*! 2 | * Bootstrap Table of Contents v0.4.1 (http://afeld.github.io/bootstrap-toc/) 3 | * Copyright 2015 Aidan Feldman 4 | * Licensed under MIT (https://github.com/afeld/bootstrap-toc/blob/gh-pages/LICENSE.md) */ 5 | (function() { 6 | 'use strict'; 7 | 8 | window.Toc = { 9 | helpers: { 10 | // return all matching elements in the set, or their descendants 11 | findOrFilter: function($el, selector) { 12 | // http://danielnouri.org/notes/2011/03/14/a-jquery-find-that-also-finds-the-root-element/ 13 | // http://stackoverflow.com/a/12731439/358804 14 | var $descendants = $el.find(selector); 15 | return $el.filter(selector).add($descendants).filter(':not([data-toc-skip])'); 16 | }, 17 | 18 | generateUniqueIdBase: function(el) { 19 | var text = $(el).text(); 20 | var anchor = text.trim().toLowerCase().replace(/[^A-Za-z0-9]+/g, '-'); 21 | return anchor || el.tagName.toLowerCase(); 22 | }, 23 | 24 | generateUniqueId: function(el) { 25 | var anchorBase = this.generateUniqueIdBase(el); 26 | for (var i = 0; ; i++) { 27 | var anchor = anchorBase; 28 | if (i > 0) { 29 | // add suffix 30 | anchor += '-' + i; 31 | } 32 | // check if ID already exists 33 | if (!document.getElementById(anchor)) { 34 | return anchor; 35 | } 36 | } 37 | }, 38 | 39 | generateAnchor: function(el) { 40 | if (el.id) { 41 | return el.id; 42 | } else { 43 | var anchor = this.generateUniqueId(el); 44 | el.id = anchor; 45 | return anchor; 46 | } 47 | }, 48 | 49 | createNavList: function() { 50 | return $(''); 51 | }, 52 | 53 | createChildNavList: function($parent) { 54 | var $childList = this.createNavList(); 55 | $parent.append($childList); 56 | return $childList; 57 | }, 58 | 59 | generateNavEl: function(anchor, text) { 60 | var $a = $(''); 61 | $a.attr('href', '#' + anchor); 62 | $a.text(text); 63 | var $li = $('
  • '); 64 | $li.append($a); 65 | return $li; 66 | }, 67 | 68 | generateNavItem: function(headingEl) { 69 | var anchor = this.generateAnchor(headingEl); 70 | var $heading = $(headingEl); 71 | var text = $heading.data('toc-text') || $heading.text(); 72 | return this.generateNavEl(anchor, text); 73 | }, 74 | 75 | // Find the first heading level (`

    `, then `

    `, etc.) that has more than one element. Defaults to 1 (for `

    `). 76 | getTopLevel: function($scope) { 77 | for (var i = 1; i <= 6; i++) { 78 | var $headings = this.findOrFilter($scope, 'h' + i); 79 | if ($headings.length > 1) { 80 | return i; 81 | } 82 | } 83 | 84 | return 1; 85 | }, 86 | 87 | // returns the elements for the top level, and the next below it 88 | getHeadings: function($scope, topLevel) { 89 | var topSelector = 'h' + topLevel; 90 | 91 | var secondaryLevel = topLevel + 1; 92 | var secondarySelector = 'h' + secondaryLevel; 93 | 94 | return this.findOrFilter($scope, topSelector + ',' + secondarySelector); 95 | }, 96 | 97 | getNavLevel: function(el) { 98 | return parseInt(el.tagName.charAt(1), 10); 99 | }, 100 | 101 | populateNav: function($topContext, topLevel, $headings) { 102 | var $context = $topContext; 103 | var $prevNav; 104 | 105 | var helpers = this; 106 | $headings.each(function(i, el) { 107 | var $newNav = helpers.generateNavItem(el); 108 | var navLevel = helpers.getNavLevel(el); 109 | 110 | // determine the proper $context 111 | if (navLevel === topLevel) { 112 | // use top level 113 | $context = $topContext; 114 | } else if ($prevNav && $context === $topContext) { 115 | // create a new level of the tree and switch to it 116 | $context = helpers.createChildNavList($prevNav); 117 | } // else use the current $context 118 | 119 | $context.append($newNav); 120 | 121 | $prevNav = $newNav; 122 | }); 123 | }, 124 | 125 | parseOps: function(arg) { 126 | var opts; 127 | if (arg.jquery) { 128 | opts = { 129 | $nav: arg 130 | }; 131 | } else { 132 | opts = arg; 133 | } 134 | opts.$scope = opts.$scope || $(document.body); 135 | return opts; 136 | } 137 | }, 138 | 139 | // accepts a jQuery object, or an options object 140 | init: function(opts) { 141 | opts = this.helpers.parseOps(opts); 142 | 143 | // ensure that the data attribute is in place for styling 144 | opts.$nav.attr('data-toggle', 'toc'); 145 | 146 | var $topContext = this.helpers.createChildNavList(opts.$nav); 147 | var topLevel = this.helpers.getTopLevel(opts.$scope); 148 | var $headings = this.helpers.getHeadings(opts.$scope, topLevel); 149 | this.helpers.populateNav($topContext, topLevel, $headings); 150 | } 151 | }; 152 | 153 | $(function() { 154 | $('nav[data-toggle="toc"]').each(function(i, el) { 155 | var $nav = $(el); 156 | Toc.init($nav); 157 | }); 158 | }); 159 | })(); 160 | -------------------------------------------------------------------------------- /docs/docsearch.css: -------------------------------------------------------------------------------- 1 | /* Docsearch -------------------------------------------------------------- */ 2 | /* 3 | Source: https://github.com/algolia/docsearch/ 4 | License: MIT 5 | */ 6 | 7 | .algolia-autocomplete { 8 | display: block; 9 | -webkit-box-flex: 1; 10 | -ms-flex: 1; 11 | flex: 1 12 | } 13 | 14 | .algolia-autocomplete .ds-dropdown-menu { 15 | width: 100%; 16 | min-width: none; 17 | max-width: none; 18 | padding: .75rem 0; 19 | background-color: #fff; 20 | background-clip: padding-box; 21 | border: 1px solid rgba(0, 0, 0, .1); 22 | box-shadow: 0 .5rem 1rem rgba(0, 0, 0, .175); 23 | } 24 | 25 | @media (min-width:768px) { 26 | .algolia-autocomplete .ds-dropdown-menu { 27 | width: 175% 28 | } 29 | } 30 | 31 | .algolia-autocomplete .ds-dropdown-menu::before { 32 | display: none 33 | } 34 | 35 | .algolia-autocomplete .ds-dropdown-menu [class^=ds-dataset-] { 36 | padding: 0; 37 | background-color: rgb(255,255,255); 38 | border: 0; 39 | max-height: 80vh; 40 | } 41 | 42 | .algolia-autocomplete .ds-dropdown-menu .ds-suggestions { 43 | margin-top: 0 44 | } 45 | 46 | .algolia-autocomplete .algolia-docsearch-suggestion { 47 | padding: 0; 48 | overflow: visible 49 | } 50 | 51 | .algolia-autocomplete .algolia-docsearch-suggestion--category-header { 52 | padding: .125rem 1rem; 53 | margin-top: 0; 54 | font-size: 1.3em; 55 | font-weight: 500; 56 | color: #00008B; 57 | border-bottom: 0 58 | } 59 | 60 | .algolia-autocomplete .algolia-docsearch-suggestion--wrapper { 61 | float: none; 62 | padding-top: 0 63 | } 64 | 65 | .algolia-autocomplete .algolia-docsearch-suggestion--subcategory-column { 66 | float: none; 67 | width: auto; 68 | padding: 0; 69 | text-align: left 70 | } 71 | 72 | .algolia-autocomplete .algolia-docsearch-suggestion--content { 73 | float: none; 74 | width: auto; 75 | padding: 0 76 | } 77 | 78 | .algolia-autocomplete .algolia-docsearch-suggestion--content::before { 79 | display: none 80 | } 81 | 82 | .algolia-autocomplete .ds-suggestion:not(:first-child) .algolia-docsearch-suggestion--category-header { 83 | padding-top: .75rem; 84 | margin-top: .75rem; 85 | border-top: 1px solid rgba(0, 0, 0, .1) 86 | } 87 | 88 | .algolia-autocomplete .ds-suggestion .algolia-docsearch-suggestion--subcategory-column { 89 | display: block; 90 | padding: .1rem 1rem; 91 | margin-bottom: 0.1; 92 | font-size: 1.0em; 93 | font-weight: 400 94 | /* display: none */ 95 | } 96 | 97 | .algolia-autocomplete .algolia-docsearch-suggestion--title { 98 | display: block; 99 | padding: .25rem 1rem; 100 | margin-bottom: 0; 101 | font-size: 0.9em; 102 | font-weight: 400 103 | } 104 | 105 | .algolia-autocomplete .algolia-docsearch-suggestion--text { 106 | padding: 0 1rem .5rem; 107 | margin-top: -.25rem; 108 | font-size: 0.8em; 109 | font-weight: 400; 110 | line-height: 1.25 111 | } 112 | 113 | .algolia-autocomplete .algolia-docsearch-footer { 114 | width: 110px; 115 | height: 20px; 116 | z-index: 3; 117 | margin-top: 10.66667px; 118 | float: right; 119 | font-size: 0; 120 | line-height: 0; 121 | } 122 | 123 | .algolia-autocomplete .algolia-docsearch-footer--logo { 124 | background-image: url("data:image/svg+xml;utf8,"); 125 | background-repeat: no-repeat; 126 | background-position: 50%; 127 | background-size: 100%; 128 | overflow: hidden; 129 | text-indent: -9000px; 130 | width: 100%; 131 | height: 100%; 132 | display: block; 133 | transform: translate(-8px); 134 | } 135 | 136 | .algolia-autocomplete .algolia-docsearch-suggestion--highlight { 137 | color: #FF8C00; 138 | background: rgba(232, 189, 54, 0.1) 139 | } 140 | 141 | 142 | .algolia-autocomplete .algolia-docsearch-suggestion--text .algolia-docsearch-suggestion--highlight { 143 | box-shadow: inset 0 -2px 0 0 rgba(105, 105, 105, .5) 144 | } 145 | 146 | .algolia-autocomplete .ds-suggestion.ds-cursor .algolia-docsearch-suggestion--content { 147 | background-color: rgba(192, 192, 192, .15) 148 | } 149 | -------------------------------------------------------------------------------- /docs/docsearch.js: -------------------------------------------------------------------------------- 1 | $(function() { 2 | 3 | // register a handler to move the focus to the search bar 4 | // upon pressing shift + "/" (i.e. "?") 5 | $(document).on('keydown', function(e) { 6 | if (e.shiftKey && e.keyCode == 191) { 7 | e.preventDefault(); 8 | $("#search-input").focus(); 9 | } 10 | }); 11 | 12 | $(document).ready(function() { 13 | // do keyword highlighting 14 | /* modified from https://jsfiddle.net/julmot/bL6bb5oo/ */ 15 | var mark = function() { 16 | 17 | var referrer = document.URL ; 18 | var paramKey = "q" ; 19 | 20 | if (referrer.indexOf("?") !== -1) { 21 | var qs = referrer.substr(referrer.indexOf('?') + 1); 22 | var qs_noanchor = qs.split('#')[0]; 23 | var qsa = qs_noanchor.split('&'); 24 | var keyword = ""; 25 | 26 | for (var i = 0; i < qsa.length; i++) { 27 | var currentParam = qsa[i].split('='); 28 | 29 | if (currentParam.length !== 2) { 30 | continue; 31 | } 32 | 33 | if (currentParam[0] == paramKey) { 34 | keyword = decodeURIComponent(currentParam[1].replace(/\+/g, "%20")); 35 | } 36 | } 37 | 38 | if (keyword !== "") { 39 | $(".contents").unmark({ 40 | done: function() { 41 | $(".contents").mark(keyword); 42 | } 43 | }); 44 | } 45 | } 46 | }; 47 | 48 | mark(); 49 | }); 50 | }); 51 | 52 | /* Search term highlighting ------------------------------*/ 53 | 54 | function matchedWords(hit) { 55 | var words = []; 56 | 57 | var hierarchy = hit._highlightResult.hierarchy; 58 | // loop to fetch from lvl0, lvl1, etc. 59 | for (var idx in hierarchy) { 60 | words = words.concat(hierarchy[idx].matchedWords); 61 | } 62 | 63 | var content = hit._highlightResult.content; 64 | if (content) { 65 | words = words.concat(content.matchedWords); 66 | } 67 | 68 | // return unique words 69 | var words_uniq = [...new Set(words)]; 70 | return words_uniq; 71 | } 72 | 73 | function updateHitURL(hit) { 74 | 75 | var words = matchedWords(hit); 76 | var url = ""; 77 | 78 | if (hit.anchor) { 79 | url = hit.url_without_anchor + '?q=' + escape(words.join(" ")) + '#' + hit.anchor; 80 | } else { 81 | url = hit.url + '?q=' + escape(words.join(" ")); 82 | } 83 | 84 | return url; 85 | } 86 | -------------------------------------------------------------------------------- /docs/extra.css: -------------------------------------------------------------------------------- 1 | @import url("https://nmfs-general-modeling-tools.github.io/nmfspalette/extra.css"); 2 | -------------------------------------------------------------------------------- /docs/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | Stan Routines For Univariate And Multivariate Time Series • atsar 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 21 | 22 | 23 |
    24 |
    79 | 80 | 81 | 82 | 83 |
    84 |
    85 | 86 | 87 | 104 | 124 |

    The atsar R package implements Bayesian time series models using Stan, primarily for illustrative purposes and teaching (University of Washington’s Fish 550, Winter quarters). The Stan webpage, and appropriate citation guidelines are here.

    125 |
    126 |

    127 | INSTALL

    128 |

    You can install the development version of the package with:

    129 |
    130 | # install.packages("devtools")
    131 | devtools::install_github("atsa-es/atsar")
    132 |
    133 |
    134 |

    135 | EXAMPLE

    136 |

    Simulate data:

    137 |
    138 | library(rstan)
    139 | #> Loading required package: StanHeaders
    140 | #> Loading required package: ggplot2
    141 | #> rstan (Version 2.21.2, GitRev: 2e1f913d3ca3)
    142 | #> For execution on a local, multicore CPU with excess RAM we recommend calling
    143 | #> options(mc.cores = parallel::detectCores()).
    144 | #> To avoid recompilation of unchanged Stan programs, we recommend calling
    145 | #> rstan_options(auto_write = TRUE)
    146 | library(atsar)
    147 | set.seed(123)
    148 | s = cumsum(rnorm(50))
    149 |
    150 | plot(s)
    151 |

    152 |

    Fit several models to this data:

    153 |
    154 | # Regression, no slope
    155 | regression_model = fit_stan(y = s, x = model.matrix(lm(s~1)), model_name="regression")
    156 | 
    157 | # Regression, with slope
    158 | regression_model = fit_stan(y = s, x = model.matrix(lm(s~seq(1,length(s)))), model_name="regression")
    159 | 
    160 | # AR(1) time series model
    161 | ar1_model = fit_stan(y = s, est_drift=FALSE, P = 1, model_name = "ar")
    162 | 
    163 | # ARMA(1,1) time series model
    164 | arma1_model = fit_stan(y = s, model_name = "arma11")
    165 | 
    166 | # univariate ss model -- without drift but mean reversion estimated
    167 | ss_model = fit_stan(y = s, model_name = "ss_ar", est_drift=FALSE)
    168 |

    To see the Stan mode code behind each of these, look in the inst/stan folder on the GitHub repository. Note that fit_stan.R does some data preparation to deal with Stan not accepting NAs in the data.

    169 |
    170 |
    171 |

    172 | DOCUMENTATION

    173 |
      174 |
    • 175 | ATSA lab book - Many applications are covered in our Applied Time Series Analysis book developed from the labs in our course.
    • 176 |
    • 177 | ATSA course website - We have lectures and all material from our course on our course website.
    • 178 |
    • Additional information can be found on the NWFSC time series page which includes several additional books and packages, NWFSC time series page 179 |
    • 180 |
    181 |
    182 |
    183 |

    184 | CITATION

    185 |

    Ward, E.J., M.D. Scheuerell, and E.E. Holmes. 2018. ‘atsar’: Applied Time Series Analysis in R: an introduction to time series analysis for ecological and fisheries data with Stan. DOI

    186 |
    187 |
    188 |

    189 | NOAA Disclaimer

    190 |

    This repository is a scientific product and is not official communication of the National Oceanic and Atmospheric Administration, or the United States Department of Commerce. All NOAA GitHub project code is provided on an ‘as is’ basis and the user assumes responsibility for its use. Any claims against the Department of Commerce or Department of Commerce bureaus stemming from the use of this GitHub project will be governed by all applicable Federal law. Any reference to specific commercial products, processes, or services by service mark, trademark, manufacturer, or otherwise, does not constitute or imply their endorsement, recommendation or favoring by the Department of Commerce. The Department of Commerce seal and logo, or the seal and logo of a DOC bureau, shall not be used in any manner to imply endorsement of any commercial product or activity by DOC or the United States Government.

    191 |
    192 | 193 |
    194 | 195 | 229 |
    230 | 231 | 232 |
    235 | 236 |
    237 |

    Site built with pkgdown 1.6.1.

    238 |
    239 | 240 |
    241 |
    242 | 243 | 244 | 245 | 246 | 247 | 248 | -------------------------------------------------------------------------------- /docs/link.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 5 | 8 | 12 | 13 | -------------------------------------------------------------------------------- /docs/pkgdown.css: -------------------------------------------------------------------------------- 1 | /* Sticky footer */ 2 | 3 | /** 4 | * Basic idea: https://philipwalton.github.io/solved-by-flexbox/demos/sticky-footer/ 5 | * Details: https://github.com/philipwalton/solved-by-flexbox/blob/master/assets/css/components/site.css 6 | * 7 | * .Site -> body > .container 8 | * .Site-content -> body > .container .row 9 | * .footer -> footer 10 | * 11 | * Key idea seems to be to ensure that .container and __all its parents__ 12 | * have height set to 100% 13 | * 14 | */ 15 | 16 | html, body { 17 | height: 100%; 18 | } 19 | 20 | body { 21 | position: relative; 22 | } 23 | 24 | body > .container { 25 | display: flex; 26 | height: 100%; 27 | flex-direction: column; 28 | } 29 | 30 | body > .container .row { 31 | flex: 1 0 auto; 32 | } 33 | 34 | footer { 35 | margin-top: 45px; 36 | padding: 35px 0 36px; 37 | border-top: 1px solid #e5e5e5; 38 | color: #666; 39 | display: flex; 40 | flex-shrink: 0; 41 | } 42 | footer p { 43 | margin-bottom: 0; 44 | } 45 | footer div { 46 | flex: 1; 47 | } 48 | footer .pkgdown { 49 | text-align: right; 50 | } 51 | footer p { 52 | margin-bottom: 0; 53 | } 54 | 55 | img.icon { 56 | float: right; 57 | } 58 | 59 | img { 60 | max-width: 100%; 61 | } 62 | 63 | /* Fix bug in bootstrap (only seen in firefox) */ 64 | summary { 65 | display: list-item; 66 | } 67 | 68 | /* Typographic tweaking ---------------------------------*/ 69 | 70 | .contents .page-header { 71 | margin-top: calc(-60px + 1em); 72 | } 73 | 74 | dd { 75 | margin-left: 3em; 76 | } 77 | 78 | /* Section anchors ---------------------------------*/ 79 | 80 | a.anchor { 81 | margin-left: -30px; 82 | display:inline-block; 83 | width: 30px; 84 | height: 30px; 85 | visibility: hidden; 86 | 87 | background-image: url(./link.svg); 88 | background-repeat: no-repeat; 89 | background-size: 20px 20px; 90 | background-position: center center; 91 | } 92 | 93 | .hasAnchor:hover a.anchor { 94 | visibility: visible; 95 | } 96 | 97 | @media (max-width: 767px) { 98 | .hasAnchor:hover a.anchor { 99 | visibility: hidden; 100 | } 101 | } 102 | 103 | 104 | /* Fixes for fixed navbar --------------------------*/ 105 | 106 | .contents h1, .contents h2, .contents h3, .contents h4 { 107 | padding-top: 60px; 108 | margin-top: -40px; 109 | } 110 | 111 | /* Navbar submenu --------------------------*/ 112 | 113 | .dropdown-submenu { 114 | position: relative; 115 | } 116 | 117 | .dropdown-submenu>.dropdown-menu { 118 | top: 0; 119 | left: 100%; 120 | margin-top: -6px; 121 | margin-left: -1px; 122 | border-radius: 0 6px 6px 6px; 123 | } 124 | 125 | .dropdown-submenu:hover>.dropdown-menu { 126 | display: block; 127 | } 128 | 129 | .dropdown-submenu>a:after { 130 | display: block; 131 | content: " "; 132 | float: right; 133 | width: 0; 134 | height: 0; 135 | border-color: transparent; 136 | border-style: solid; 137 | border-width: 5px 0 5px 5px; 138 | border-left-color: #cccccc; 139 | margin-top: 5px; 140 | margin-right: -10px; 141 | } 142 | 143 | .dropdown-submenu:hover>a:after { 144 | border-left-color: #ffffff; 145 | } 146 | 147 | .dropdown-submenu.pull-left { 148 | float: none; 149 | } 150 | 151 | .dropdown-submenu.pull-left>.dropdown-menu { 152 | left: -100%; 153 | margin-left: 10px; 154 | border-radius: 6px 0 6px 6px; 155 | } 156 | 157 | /* Sidebar --------------------------*/ 158 | 159 | #pkgdown-sidebar { 160 | margin-top: 30px; 161 | position: -webkit-sticky; 162 | position: sticky; 163 | top: 70px; 164 | } 165 | 166 | #pkgdown-sidebar h2 { 167 | font-size: 1.5em; 168 | margin-top: 1em; 169 | } 170 | 171 | #pkgdown-sidebar h2:first-child { 172 | margin-top: 0; 173 | } 174 | 175 | #pkgdown-sidebar .list-unstyled li { 176 | margin-bottom: 0.5em; 177 | } 178 | 179 | /* bootstrap-toc tweaks ------------------------------------------------------*/ 180 | 181 | /* All levels of nav */ 182 | 183 | nav[data-toggle='toc'] .nav > li > a { 184 | padding: 4px 20px 4px 6px; 185 | font-size: 1.5rem; 186 | font-weight: 400; 187 | color: inherit; 188 | } 189 | 190 | nav[data-toggle='toc'] .nav > li > a:hover, 191 | nav[data-toggle='toc'] .nav > li > a:focus { 192 | padding-left: 5px; 193 | color: inherit; 194 | border-left: 1px solid #878787; 195 | } 196 | 197 | nav[data-toggle='toc'] .nav > .active > a, 198 | nav[data-toggle='toc'] .nav > .active:hover > a, 199 | nav[data-toggle='toc'] .nav > .active:focus > a { 200 | padding-left: 5px; 201 | font-size: 1.5rem; 202 | font-weight: 400; 203 | color: inherit; 204 | border-left: 2px solid #878787; 205 | } 206 | 207 | /* Nav: second level (shown on .active) */ 208 | 209 | nav[data-toggle='toc'] .nav .nav { 210 | display: none; /* Hide by default, but at >768px, show it */ 211 | padding-bottom: 10px; 212 | } 213 | 214 | nav[data-toggle='toc'] .nav .nav > li > a { 215 | padding-left: 16px; 216 | font-size: 1.35rem; 217 | } 218 | 219 | nav[data-toggle='toc'] .nav .nav > li > a:hover, 220 | nav[data-toggle='toc'] .nav .nav > li > a:focus { 221 | padding-left: 15px; 222 | } 223 | 224 | nav[data-toggle='toc'] .nav .nav > .active > a, 225 | nav[data-toggle='toc'] .nav .nav > .active:hover > a, 226 | nav[data-toggle='toc'] .nav .nav > .active:focus > a { 227 | padding-left: 15px; 228 | font-weight: 500; 229 | font-size: 1.35rem; 230 | } 231 | 232 | /* orcid ------------------------------------------------------------------- */ 233 | 234 | .orcid { 235 | font-size: 16px; 236 | color: #A6CE39; 237 | /* margins are required by official ORCID trademark and display guidelines */ 238 | margin-left:4px; 239 | margin-right:4px; 240 | vertical-align: middle; 241 | } 242 | 243 | /* Reference index & topics ----------------------------------------------- */ 244 | 245 | .ref-index th {font-weight: normal;} 246 | 247 | .ref-index td {vertical-align: top; min-width: 100px} 248 | .ref-index .icon {width: 40px;} 249 | .ref-index .alias {width: 40%;} 250 | .ref-index-icons .alias {width: calc(40% - 40px);} 251 | .ref-index .title {width: 60%;} 252 | 253 | .ref-arguments th {text-align: right; padding-right: 10px;} 254 | .ref-arguments th, .ref-arguments td {vertical-align: top; min-width: 100px} 255 | .ref-arguments .name {width: 20%;} 256 | .ref-arguments .desc {width: 80%;} 257 | 258 | /* Nice scrolling for wide elements --------------------------------------- */ 259 | 260 | table { 261 | display: block; 262 | overflow: auto; 263 | } 264 | 265 | /* Syntax highlighting ---------------------------------------------------- */ 266 | 267 | pre { 268 | word-wrap: normal; 269 | word-break: normal; 270 | border: 1px solid #eee; 271 | } 272 | 273 | pre, code { 274 | background-color: #f8f8f8; 275 | color: #333; 276 | } 277 | 278 | pre code { 279 | overflow: auto; 280 | word-wrap: normal; 281 | white-space: pre; 282 | } 283 | 284 | pre .img { 285 | margin: 5px 0; 286 | } 287 | 288 | pre .img img { 289 | background-color: #fff; 290 | display: block; 291 | height: auto; 292 | } 293 | 294 | code a, pre a { 295 | color: #375f84; 296 | } 297 | 298 | a.sourceLine:hover { 299 | text-decoration: none; 300 | } 301 | 302 | .fl {color: #1514b5;} 303 | .fu {color: #000000;} /* function */ 304 | .ch,.st {color: #036a07;} /* string */ 305 | .kw {color: #264D66;} /* keyword */ 306 | .co {color: #888888;} /* comment */ 307 | 308 | .message { color: black; font-weight: bolder;} 309 | .error { color: orange; font-weight: bolder;} 310 | .warning { color: #6A0366; font-weight: bolder;} 311 | 312 | /* Clipboard --------------------------*/ 313 | 314 | .hasCopyButton { 315 | position: relative; 316 | } 317 | 318 | .btn-copy-ex { 319 | position: absolute; 320 | right: 0; 321 | top: 0; 322 | visibility: hidden; 323 | } 324 | 325 | .hasCopyButton:hover button.btn-copy-ex { 326 | visibility: visible; 327 | } 328 | 329 | /* headroom.js ------------------------ */ 330 | 331 | .headroom { 332 | will-change: transform; 333 | transition: transform 200ms linear; 334 | } 335 | .headroom--pinned { 336 | transform: translateY(0%); 337 | } 338 | .headroom--unpinned { 339 | transform: translateY(-100%); 340 | } 341 | 342 | /* mark.js ----------------------------*/ 343 | 344 | mark { 345 | background-color: rgba(255, 255, 51, 0.5); 346 | border-bottom: 2px solid rgba(255, 153, 51, 0.3); 347 | padding: 1px; 348 | } 349 | 350 | /* vertical spacing after htmlwidgets */ 351 | .html-widget { 352 | margin-bottom: 10px; 353 | } 354 | 355 | /* fontawesome ------------------------ */ 356 | 357 | .fab { 358 | font-family: "Font Awesome 5 Brands" !important; 359 | } 360 | 361 | /* don't display links in code chunks when printing */ 362 | /* source: https://stackoverflow.com/a/10781533 */ 363 | @media print { 364 | code a:link:after, code a:visited:after { 365 | content: ""; 366 | } 367 | } 368 | -------------------------------------------------------------------------------- /docs/pkgdown.js: -------------------------------------------------------------------------------- 1 | /* http://gregfranko.com/blog/jquery-best-practices/ */ 2 | (function($) { 3 | $(function() { 4 | 5 | $('.navbar-fixed-top').headroom(); 6 | 7 | $('body').css('padding-top', $('.navbar').height() + 10); 8 | $(window).resize(function(){ 9 | $('body').css('padding-top', $('.navbar').height() + 10); 10 | }); 11 | 12 | $('[data-toggle="tooltip"]').tooltip(); 13 | 14 | var cur_path = paths(location.pathname); 15 | var links = $("#navbar ul li a"); 16 | var max_length = -1; 17 | var pos = -1; 18 | for (var i = 0; i < links.length; i++) { 19 | if (links[i].getAttribute("href") === "#") 20 | continue; 21 | // Ignore external links 22 | if (links[i].host !== location.host) 23 | continue; 24 | 25 | var nav_path = paths(links[i].pathname); 26 | 27 | var length = prefix_length(nav_path, cur_path); 28 | if (length > max_length) { 29 | max_length = length; 30 | pos = i; 31 | } 32 | } 33 | 34 | // Add class to parent
  • , and enclosing
  • if in dropdown 35 | if (pos >= 0) { 36 | var menu_anchor = $(links[pos]); 37 | menu_anchor.parent().addClass("active"); 38 | menu_anchor.closest("li.dropdown").addClass("active"); 39 | } 40 | }); 41 | 42 | function paths(pathname) { 43 | var pieces = pathname.split("/"); 44 | pieces.shift(); // always starts with / 45 | 46 | var end = pieces[pieces.length - 1]; 47 | if (end === "index.html" || end === "") 48 | pieces.pop(); 49 | return(pieces); 50 | } 51 | 52 | // Returns -1 if not found 53 | function prefix_length(needle, haystack) { 54 | if (needle.length > haystack.length) 55 | return(-1); 56 | 57 | // Special case for length-0 haystack, since for loop won't run 58 | if (haystack.length === 0) { 59 | return(needle.length === 0 ? 0 : -1); 60 | } 61 | 62 | for (var i = 0; i < haystack.length; i++) { 63 | if (needle[i] != haystack[i]) 64 | return(i); 65 | } 66 | 67 | return(haystack.length); 68 | } 69 | 70 | /* Clipboard --------------------------*/ 71 | 72 | function changeTooltipMessage(element, msg) { 73 | var tooltipOriginalTitle=element.getAttribute('data-original-title'); 74 | element.setAttribute('data-original-title', msg); 75 | $(element).tooltip('show'); 76 | element.setAttribute('data-original-title', tooltipOriginalTitle); 77 | } 78 | 79 | if(ClipboardJS.isSupported()) { 80 | $(document).ready(function() { 81 | var copyButton = ""; 82 | 83 | $(".examples, div.sourceCode").addClass("hasCopyButton"); 84 | 85 | // Insert copy buttons: 86 | $(copyButton).prependTo(".hasCopyButton"); 87 | 88 | // Initialize tooltips: 89 | $('.btn-copy-ex').tooltip({container: 'body'}); 90 | 91 | // Initialize clipboard: 92 | var clipboardBtnCopies = new ClipboardJS('[data-clipboard-copy]', { 93 | text: function(trigger) { 94 | return trigger.parentNode.textContent; 95 | } 96 | }); 97 | 98 | clipboardBtnCopies.on('success', function(e) { 99 | changeTooltipMessage(e.trigger, 'Copied!'); 100 | e.clearSelection(); 101 | }); 102 | 103 | clipboardBtnCopies.on('error', function() { 104 | changeTooltipMessage(e.trigger,'Press Ctrl+C or Command+C to copy'); 105 | }); 106 | }); 107 | } 108 | })(window.jQuery || window.$) 109 | -------------------------------------------------------------------------------- /docs/pkgdown.yml: -------------------------------------------------------------------------------- 1 | pandoc: 2.11.4 2 | pkgdown: 1.6.1 3 | pkgdown_sha: ~ 4 | articles: 5 | dlm: dlm.html 6 | fit_stan: fit_stan.html 7 | last_built: 2021-10-04T16:53Z 8 | 9 | -------------------------------------------------------------------------------- /docs/reference/atsar-package.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | The 'atsar' package. — atsar-package • atsar 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 | 58 | 59 | 60 | 61 | 62 | 63 | 64 |
    65 |
    66 | 120 | 121 | 122 | 123 |
    124 | 125 |
    126 |
    127 | 132 | 133 |
    134 |

    A DESCRIPTION OF THE PACKAGE

    135 |
    136 | 137 | 138 | 139 |

    References

    140 | 141 |

    Stan Development Team (2020). RStan: the R interface to Stan. R package version 2.21.2. https://mc-stan.org

    142 | 143 |
    144 | 149 |
    150 | 151 | 152 |
    153 | 156 | 157 |
    158 |

    Site built with pkgdown 1.6.1.

    159 |
    160 | 161 |
    162 |
    163 | 164 | 165 | 166 | 167 | 168 | 169 | 170 | 171 | -------------------------------------------------------------------------------- /docs/reference/fit_stan.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | fit_stan is the primary function which calls pre-written stan scripts for time series data. — fit_stan • atsar 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 | 58 | 59 | 60 | 61 | 62 | 63 | 64 |
    65 |
    66 | 120 | 121 | 122 | 123 |
    124 | 125 |
    126 |
    127 | 132 | 133 |
    134 |

    fit_stan is the primary function which calls pre-written stan scripts for time series data.

    135 |
    136 | 137 |
    fit_stan(
    138 |   y,
    139 |   x = NA,
    140 |   model_name = NA,
    141 |   est_drift = FALSE,
    142 |   est_mean = FALSE,
    143 |   P = 1,
    144 |   Q = 1,
    145 |   mcmc_list = list(n_mcmc = 1000, n_burn = 500, n_chain = 3, n_thin = 1),
    146 |   family = "gaussian",
    147 |   est_nu = FALSE,
    148 |   marss = list(states = NULL, obsVariances = NULL, proVariances = NULL, trends = NULL),
    149 |   map_estimation = FALSE,
    150 |   hessian = FALSE,
    151 |   ...
    152 | )
    153 | 154 |

    Arguments

    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 |
    y

    The response variable (numeric)

    x

    The predictors, either a vector or matrix

    model_name

    The specific name of the model to be fitted. Currently supported are 'regression', 'ar', 'rw', 'ma', 'ss_ar' (state space univariate AR), or 'ss_rw' (state space univariate random walk).

    est_drift

    Whether or not to estimate a drift parameter (default = FALSE). Only applicable to the rw and ar models.

    est_mean

    Whether to estimate a mean or not (for state space autoregressive model only)

    P

    The order of the ar model, with minimum value = 1 (default).

    Q

    The order of the ma model, with minimum value = 1 (default).

    mcmc_list

    A list of MCMC control parameters. These include the number of 'iterations' (default = 1000), burn in or warmup (default = 500), chains (default = 3), and thinning (default = 1)

    family

    A named distribution for the observation model, defaults to gaussian

    est_nu

    Boolean, whether to model process deviations as Student-t or not (default).

    marss

    A named list containing the following elements for specifying marss models: (states=NULL, obsVariances=NULL, proVariances=NULL, trends=NULL

    map_estimation

    Whether to do maximum a posteriori estimation via [rstan::optimizing()] (defualts to FALSE)

    hessian

    Whether to return hessian if map_estimation is TRUE via [rstan::optimizing()]

    ...

    Any other arguments passed to [rstan::sampling()].

    214 | 215 |

    Value

    216 | 217 |

    an object of class 'rstan'

    218 | 219 |
    220 | 225 |
    226 | 227 | 228 |
    229 | 232 | 233 |
    234 |

    Site built with pkgdown 1.6.1.

    235 |
    236 | 237 |
    238 |
    239 | 240 | 241 | 242 | 243 | 244 | 245 | 246 | 247 | -------------------------------------------------------------------------------- /docs/reference/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | Function reference • atsar 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 | 57 | 58 | 59 | 60 | 61 | 62 | 63 |
    64 |
    65 | 119 | 120 | 121 | 122 |
    123 | 124 |
    125 |
    126 | 129 | 130 | 131 | 132 | 133 | 134 | 135 | 136 | 137 | 138 | 139 | 140 | 144 | 145 | 146 | 147 | 148 | 149 | 150 | 151 | 152 | 155 | 156 | 157 | 158 | 161 | 162 | 163 | 164 |
    141 |

    All functions

    142 |

    143 |
    153 |

    atsar-package

    154 |

    The 'atsar' package.

    159 |

    fit_stan()

    160 |

    fit_stan is the primary function which calls pre-written stan scripts for time series data.

    165 |
    166 | 167 | 172 |
    173 | 174 | 175 |
    176 | 179 | 180 |
    181 |

    Site built with pkgdown 1.6.1.

    182 |
    183 | 184 |
    185 |
    186 | 187 | 188 | 189 | 190 | 191 | 192 | 193 | 194 | -------------------------------------------------------------------------------- /inst/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/atsa-es/atsar/a423d23978dac21fd50a51339b60600aecc4b1d4/inst/.DS_Store -------------------------------------------------------------------------------- /inst/include/stan_meta_header.hpp: -------------------------------------------------------------------------------- 1 | // Insert all #include statements here 2 | -------------------------------------------------------------------------------- /inst/marss_example.R: -------------------------------------------------------------------------------- 1 | y = matrix(0, 4, 30) 2 | for(i in 1:nrow(y)) y[i,] = cumsum(rnorm(ncol(y))) 3 | 4 | 5 | mcmc_list = list(n_mcmc = 100, n_burn = 50, n_chain = 3, n_thin = 1) 6 | 7 | marss = list(states = c(1,2,3,4), obsVariances = c(1,2,2,1), 8 | proVariances = c(1,2,3,3), trends = c(1,2,3,4), 9 | est_trend = FALSE, est_B = TRUE) 10 | 11 | fit_stan(y = y, model_name = "marss", marss = marss, 12 | mcmc_list = mcmc_list) 13 | 14 | 15 | # Or if you want to run the code yourself you could run this part below 16 | marss = list(states = c(1,2,3,3), obsVariances = c(1,2,2,1), 17 | proVariances = c(1,2,3), trends = c(1,2,3), 18 | est_trend = TRUE, est_B = TRUE) 19 | 20 | # Don't change anything below here 21 | if (is.null(marss$states)) marss$states <- rep(1, nrow(y)) 22 | if(length(marss$states) != nrow(y)) stop("Error: state vector must be same length as number of time series in y") 23 | if (is.null(marss$obsVariances)) marss$obsVariances <- rep(1, nrow(y)) 24 | if(length(marss$obsVariances) != nrow(y)) stop("Error: vector of observation error variances must be same length as number of time series in y") 25 | if (is.null(marss$proVariances)) marss$proVariances <- rep(1, max(marss$states)) 26 | if(length(marss$proVariances) < max(marss$states)) stop("Error: vector of process error variances is fewer than the number of states") 27 | if(length(marss$proVariances) > max(marss$states)) stop("Error: vector of process error variances is larger than the number of states") 28 | if (is.null(marss$trends)) marss$trends <- rep(1, max(marss$states)) 29 | if(length(marss$trends) < max(marss$states)) stop("Error: vector of trends is fewer than the number of states") 30 | if(length(marss$trends) > max(marss$states)) stop("Error: vector of trends is larger than the number of states") 31 | if (marss$est_trend == FALSE) est_trend = FALSE 32 | if (marss$est_B == FALSE) est_B = FALSE 33 | proVariances <- c(marss$proVariances, 0) # to keep types in stan constant 34 | trends <- c(marss$trends, 0) # to keep types in stan constant 35 | N <- ncol(y) 36 | M <- nrow(y) 37 | row_indx_pos <- matrix((rep(1:M, N)), M, N)[which(!is.na(y))] 38 | col_indx_pos <- matrix(sort(rep(1:N, M)), M, N)[which(!is.na(y))] 39 | n_pos <- length(row_indx_pos) 40 | y <- y[which(!is.na(y))] 41 | 42 | data_list = list("N"=N,"M"=M, "y"=y, 43 | "states"=states, "S" = max(marss$states), "obsVariances"=marss$obsVariances, 44 | "n_obsvar" = max(marss$obsVariances), "proVariances" = proVariances, 45 | "n_provar" = max(proVariances), 46 | "trends"=trends, "n_trends" = max(trends), 47 | "n_pos" = n_pos, 48 | "col_indx_pos" = col_indx_pos, 49 | "row_indx_pos" = row_indx_pos, 50 | "y_int"=round(y), 51 | "family"=1, 52 | "est_trend" = as.numeric(est_trend), 53 | "est_B" = as.numeric(est_B)) 54 | 55 | mod <- rstan::stan(paste0("inst/stan/marss.stan"), 56 | data = data_list, chains = mcmc_list$n_chain, 57 | iter = mcmc_list$n_mcmc, thin = mcmc_list$n_thin) 58 | 59 | pars = rstan::extract(mod) -------------------------------------------------------------------------------- /inst/stan/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/atsa-es/atsar/a423d23978dac21fd50a51339b60600aecc4b1d4/inst/stan/.DS_Store -------------------------------------------------------------------------------- /inst/stan/ar.stan: -------------------------------------------------------------------------------- 1 | data { 2 | int N; 3 | real y[N]; 4 | int P; 5 | int est_drift; 6 | int est_nu; 7 | } 8 | parameters { 9 | real sigma; // outcome noise 10 | real phi[P]; 11 | real mu[est_drift]; 12 | real nu[est_nu]; 13 | } 14 | transformed parameters { 15 | real pred[N]; 16 | for(i in 1:P) { 17 | pred[i] = 0; 18 | } 19 | for(i in (P+1):N) { 20 | if(est_drift==1) { 21 | pred[i] = mu[1]; 22 | } else { 23 | pred[i] = 0; 24 | } 25 | for(j in 1:P) { 26 | pred[i] = pred[i] + phi[j]*y[i-j]; 27 | } 28 | } 29 | } 30 | model { 31 | if(est_drift==1) { 32 | mu ~ normal(0,1); 33 | } 34 | if(est_nu == 0) { 35 | y[P:N] ~ normal(pred[P:N], sigma); 36 | } else { 37 | y[P:N] ~ student_t(nu, pred[P:N], sigma); 38 | } 39 | sigma ~ student_t(3,0,2); 40 | phi ~ normal(0,1); 41 | if(est_nu==1) { 42 | nu ~ student_t(3,2,2); 43 | } 44 | } 45 | 46 | -------------------------------------------------------------------------------- /inst/stan/dlm.stan: -------------------------------------------------------------------------------- 1 | data { 2 | int N; 3 | int n_pos; 4 | vector[n_pos] y; 5 | int pos_indx[n_pos+2]; 6 | int K; // number of covariates 7 | matrix[N, K] x; // matrix of covariates 8 | int y_int[n_pos]; 9 | int family; // 1 = normal, 2 = binomial, 3 = poisson, 4 = gamma, 5 = lognormal 10 | int est_nu; 11 | } 12 | parameters { 13 | //real x0; 14 | vector[K] beta0; 15 | vector[K] pro_dev[N-1]; 16 | real sigma_process[K]; 17 | real sigma_obs; 18 | real nu[est_nu]; 19 | } 20 | transformed parameters { 21 | vector[N] pred; 22 | vector[K] beta[N]; // elements accessed [N,K] 23 | 24 | for(k in 1:K) { 25 | beta[1,k] = beta0[k]; 26 | for(i in 2:N) { 27 | beta[i,k] = beta[i-1,k] + sigma_process[k]*pro_dev[i-1,k]; 28 | } 29 | } 30 | for(i in 1:N) { 31 | pred[i] = x[i] * beta[i]; 32 | } 33 | 34 | } 35 | model { 36 | sigma_obs ~ student_t(3,0,2); 37 | if(est_nu==1) { 38 | nu ~ student_t(3,2,2); 39 | } 40 | for(k in 1:K) { 41 | beta0[k] ~ normal(0,10); 42 | sigma_process[k] ~ student_t(3,0,2); 43 | //pro_dev[k] ~ normal(0, sigma_process[k]); 44 | if(est_nu == 0) { 45 | pro_dev[k] ~ std_normal(); 46 | } else { 47 | pro_dev[k] ~ student_t(nu, 0, 1); 48 | } 49 | } 50 | if(family==1) { 51 | for(i in 1:(n_pos)) { 52 | y[i] ~ normal(pred[pos_indx[i]], sigma_obs); 53 | } 54 | } 55 | if(family==2) { 56 | for(i in 1:(n_pos)) { 57 | y_int[i] ~ bernoulli_logit(pred[pos_indx[i]]); 58 | } 59 | } 60 | if(family==3) { 61 | for(i in 1:(n_pos)) { 62 | y_int[i] ~ poisson_log(pred[pos_indx[i]]); 63 | } 64 | } 65 | if(family==4) { 66 | for(i in 1:(n_pos)) { 67 | y[i] ~ gamma(sigma_obs, sigma_obs ./ exp(pred[pos_indx[i]])); 68 | } 69 | } 70 | if(family==5) { 71 | for(i in 1:(n_pos)) { 72 | y[i] ~ lognormal(pred[pos_indx[i]], sigma_obs); 73 | } 74 | } 75 | } 76 | generated quantities { 77 | vector[n_pos] log_lik; 78 | // regression example in loo() package 79 | if(family==1) for (n in 1:n_pos) log_lik[n] = normal_lpdf(y[n] | pred[pos_indx[n]], sigma_obs); 80 | if(family==2) for (n in 1:n_pos) log_lik[n] = bernoulli_lpmf(y_int[n] | inv_logit(pred[pos_indx[n]])); 81 | if(family==3) for (n in 1:n_pos) log_lik[n] = poisson_lpmf(y_int[n] | exp(pred[pos_indx[n]])); 82 | if(family==4) for (n in 1:n_pos) log_lik[n] = gamma_lpdf(y[n] | sigma_obs, sigma_obs ./ exp(pred[pos_indx[n]])); 83 | if(family==5) for (n in 1:n_pos) log_lik[n] = lognormal_lpdf(y[n] | pred[pos_indx[n]], sigma_obs); 84 | } 85 | -------------------------------------------------------------------------------- /inst/stan/dlm_int.stan: -------------------------------------------------------------------------------- 1 | data { 2 | int N; 3 | int n_pos; 4 | vector[n_pos] y; 5 | int pos_indx[n_pos+2]; 6 | int K; // number of covariates 7 | matrix[N, K] x; // matrix of covariates 8 | int y_int[n_pos]; 9 | int family; // 1 = normal, 2 = binomial, 3 = poisson, 4 = gamma, 5 = lognormal 10 | int est_nu; 11 | } 12 | parameters { 13 | real x0; 14 | vector[K] beta; 15 | vector[N-1] pro_dev; 16 | real sigma_process; 17 | real sigma_obs; 18 | real nu[est_nu]; 19 | } 20 | transformed parameters { 21 | vector[N] pred; 22 | vector[N] intercept; 23 | intercept[1] = x0; 24 | for(i in 2:N) { 25 | intercept[i] = intercept[i-1] + sigma_process*pro_dev[i-1]; 26 | } 27 | pred = x * beta + intercept; 28 | } 29 | model { 30 | x0 ~ normal(0,10); 31 | sigma_process ~ student_t(3,0,2); 32 | sigma_obs ~ student_t(3,0,2); 33 | if(est_nu==1) { 34 | nu ~ student_t(3,2,2); 35 | } 36 | if(est_nu==0) { 37 | pro_dev ~ std_normal();//normal(0, sigma_process); 38 | } else { 39 | pro_dev ~ student_t(nu, 0, 1); 40 | } 41 | if(family==1) { 42 | for(i in 1:(n_pos)) { 43 | y[i] ~ normal(pred[pos_indx[i]], sigma_obs); 44 | } 45 | } 46 | if(family==2) { 47 | for(i in 1:(n_pos)) { 48 | y_int[i] ~ bernoulli_logit(pred[pos_indx[i]]); 49 | } 50 | } 51 | if(family==3) { 52 | for(i in 1:(n_pos)) { 53 | y_int[i] ~ poisson_log(pred[pos_indx[i]]); 54 | } 55 | } 56 | if(family==4) { 57 | for(i in 1:(n_pos)) { 58 | y[i] ~ gamma(sigma_obs, sigma_obs ./ exp(pred[pos_indx[i]])); 59 | } 60 | } 61 | if(family==5) { 62 | for(i in 1:(n_pos)) { 63 | y[i] ~ lognormal(pred[pos_indx[i]], sigma_obs); 64 | } 65 | } 66 | } 67 | generated quantities { 68 | vector[n_pos] log_lik; 69 | // regression example in loo() package 70 | if(family==1) for (n in 1:n_pos) log_lik[n] = normal_lpdf(y[n] | pred[pos_indx[n]], sigma_obs); 71 | if(family==2) for (n in 1:n_pos) log_lik[n] = bernoulli_lpmf(y_int[n] | inv_logit(pred[pos_indx[n]])); 72 | if(family==3) for (n in 1:n_pos) log_lik[n] = poisson_lpmf(y_int[n] | exp(pred[pos_indx[n]])); 73 | if(family==4) for (n in 1:n_pos) log_lik[n] = gamma_lpdf(y[n] | sigma_obs, sigma_obs ./ exp(pred[pos_indx[n]])); 74 | if(family==5) for (n in 1:n_pos) log_lik[n] = lognormal_lpdf(y[n] | pred[pos_indx[n]], sigma_obs); 75 | } 76 | -------------------------------------------------------------------------------- /inst/stan/dlm_slope.stan: -------------------------------------------------------------------------------- 1 | data { 2 | int N; 3 | int n_pos; 4 | vector[n_pos] y; 5 | int K; // number of covariates 6 | matrix[N, K] x; // matrix of covariates 7 | int y_int[n_pos]; 8 | int pos_indx[n_pos+2]; 9 | int family; // 1 = normal, 2 = binomial, 3 = poisson, 4 = gamma, 5 = lognormal 10 | int est_nu; 11 | } 12 | parameters { 13 | real x0; 14 | vector[K] beta0; 15 | vector[K] pro_dev[N-1]; 16 | real sigma_process[K]; 17 | real sigma_obs; 18 | real nu[est_nu]; 19 | } 20 | transformed parameters { 21 | vector[N] pred; 22 | vector[K] beta[N]; // elements accessed [N,K] 23 | 24 | for(k in 1:K) { 25 | beta[1,k] = beta0[k]; 26 | for(i in 2:N) { 27 | beta[i,k] = beta[i-1,k] + sigma_process[k]*pro_dev[i-1,k]; 28 | } 29 | } 30 | for(i in 1:N) { 31 | pred[i] = x[i] * beta[i] + x0; 32 | } 33 | 34 | } 35 | model { 36 | x0 ~ normal(0,10); 37 | sigma_obs ~ student_t(3,0,2); 38 | if(est_nu==1) { 39 | nu ~ student_t(3,2,2); 40 | } 41 | 42 | for(k in 1:K) { 43 | beta0[k] ~ normal(0,1); 44 | sigma_process[k] ~ student_t(3,0,2); 45 | if(est_nu == 0) { 46 | pro_dev[k] ~ std_normal();//normal(0, sigma_process[k]); 47 | } else { 48 | pro_dev[k] ~ student_t(nu, 0, 1); 49 | } 50 | } 51 | if(family==1) { 52 | for(i in 1:(n_pos)) { 53 | //y ~ normal(pred, sigma_obs); 54 | y[i] ~ normal(pred[pos_indx[i]], sigma_obs); 55 | } 56 | } 57 | if(family==2) { 58 | for(i in 1:(n_pos)) { 59 | y_int[i] ~ bernoulli_logit(pred[pos_indx[i]]); 60 | } 61 | } 62 | if(family==3) { 63 | for(i in 1:(n_pos)) { 64 | y_int[i] ~ poisson_log(pred[pos_indx[i]]); 65 | } 66 | } 67 | if(family==4) { 68 | for(i in 1:(n_pos)) { 69 | y[i] ~ gamma(sigma_obs, sigma_obs ./ exp(pred[pos_indx[i]])); 70 | } 71 | } 72 | if(family==5) { 73 | for(i in 1:(n_pos)) { 74 | y[i] ~ lognormal(pred[pos_indx[i]], sigma_obs); 75 | } 76 | } 77 | } 78 | generated quantities { 79 | vector[n_pos] log_lik; 80 | // regression example in loo() package 81 | if(family==1) for (n in 1:n_pos) log_lik[n] = normal_lpdf(y[n] | pred[pos_indx[n]], sigma_obs); 82 | if(family==2) for (n in 1:n_pos) log_lik[n] = bernoulli_lpmf(y_int[n] | inv_logit(pred[pos_indx[n]])); 83 | if(family==3) for (n in 1:n_pos) log_lik[n] = poisson_lpmf(y_int[n] | exp(pred[pos_indx[n]])); 84 | if(family==4) for (n in 1:n_pos) log_lik[n] = gamma_lpdf(y[n] | sigma_obs, sigma_obs ./ exp(pred[pos_indx[n]])); 85 | if(family==5) for (n in 1:n_pos) log_lik[n] = lognormal_lpdf(y[n] | pred[pos_indx[n]], sigma_obs); 86 | } 87 | -------------------------------------------------------------------------------- /inst/stan/include/license.stan: -------------------------------------------------------------------------------- 1 | /* 2 | atsarpackage is free software: you can redistribute it and/or modify 3 | it under the terms of the GNU General Public License as published by 4 | the Free Software Foundation, either version 3 of the License, or 5 | (at your option) any later version. 6 | 7 | atsarpackage is distributed in the hope that it will be useful, 8 | but WITHOUT ANY WARRANTY; without even the implied warranty of 9 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 10 | GNU General Public License for more details. 11 | 12 | You should have received a copy of the GNU General Public License 13 | along with atsarpackage. If not, see . 14 | */ 15 | -------------------------------------------------------------------------------- /inst/stan/ma.stan: -------------------------------------------------------------------------------- 1 | data { 2 | int Q; // num previous noise terms 3 | int N; // num observations 4 | vector[N] y; // observation at time t 5 | int est_nu; 6 | } 7 | parameters { 8 | real mu; // mean 9 | real sigma; // error scale 10 | vector[Q] theta; // error coeff, lag -t 11 | real nu[est_nu]; 12 | } 13 | transformed parameters { 14 | vector[N] epsilon; // error term at time t 15 | vector[N] pred; 16 | for (t in 1:N) { 17 | epsilon[t] = y[t] - mu; 18 | for (q in 1:min(t - 1, Q)) 19 | epsilon[t] = epsilon[t] - theta[q] * epsilon[t - q]; 20 | } 21 | for (t in 1:N) { 22 | pred[t] = mu; 23 | for (q in 1:min(t - 1, Q)) 24 | pred[t] = pred[t] + theta[q] * epsilon[t - q]; 25 | } 26 | } 27 | model { 28 | if(est_nu==1) { 29 | nu ~ student_t(3,2,2); 30 | } 31 | mu ~ student_t(3,0,2); 32 | theta ~ student_t(3,0,2); 33 | sigma ~ student_t(3,0,2); 34 | if(est_nu==0) { 35 | y ~ normal(pred, sigma); 36 | } else { 37 | y ~ student_t(nu, pred, sigma); 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /inst/stan/ma1.stan: -------------------------------------------------------------------------------- 1 | data { 2 | int N; // number of observations 3 | vector[N] y; // observation at time T 4 | int est_nu; 5 | } 6 | parameters { 7 | real mu; // mean 8 | real sigma; // error scale 9 | real theta; // lag coefficients 10 | real nu[est_nu]; 11 | } 12 | transformed parameters { 13 | vector[N] epsilon; // error terms 14 | vector[N] pred; // predictions 15 | epsilon[1] = y[1] - mu; 16 | pred[1] = y[1]; 17 | for (t in 2:N) { 18 | epsilon[t] = (y[t] - mu - theta * epsilon[t - 1]); 19 | pred[t] = mu + theta * epsilon[t - 1]; 20 | } 21 | } 22 | model { 23 | if(est_nu==1) { 24 | nu ~ student_t(3,2,2); 25 | } 26 | mu ~ student_t(3,0,2); 27 | theta ~ student_t(3,0,2); 28 | sigma ~ student_t(3,0,2); 29 | if(est_nu==0) { 30 | for (t in 2:N) { 31 | y[t] ~ normal(pred[t],sigma); 32 | } 33 | } else { 34 | for (t in 2:N) { 35 | y[t] ~ student_t(nu, pred[t],sigma); 36 | } 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /inst/stan/marss.stan: -------------------------------------------------------------------------------- 1 | data { 2 | int N; 3 | int M; 4 | int states[M]; // vector assigning time series to states 5 | int S; // number of states 6 | int obsVariances[M]; 7 | int n_obsvar; 8 | int proVariances[S+1]; 9 | int n_provar; 10 | int trends[S+1]; 11 | int n_trends; 12 | int n_pos; // number of non-NA values 13 | int col_indx_pos[n_pos]; 14 | int row_indx_pos[n_pos]; 15 | int est_trend; 16 | int est_B; 17 | int n_A; 18 | int est_A[n_A+1]; 19 | vector[n_pos] y; // data 20 | int y_int[n_pos]; 21 | int family; // 1 = normal, 2 = binomial, 3 = poisson, 4 = gamma, 5 = lognormal 22 | } 23 | parameters { 24 | vector[S] x0; // initial states 25 | vector[S] pro_dev[N-1]; 26 | vector[n_trends * est_trend] U; 27 | matrix[S*est_B,S*est_B] B; 28 | vector[n_A] A; // offsets 29 | real sigma_process[S]; 30 | real sigma_obs[n_obsvar]; 31 | } 32 | transformed parameters { 33 | vector[M] pred[N]; 34 | vector[S] x[N]; // elements accessed [N,K] 35 | //matrix[N, S] x; 36 | matrix[S,S] Bmat; 37 | vector[S] Uvec; 38 | vector[M] Avec; 39 | 40 | for(i in 1:M) Avec[i] = 0; 41 | for(i in 1:n_A) Avec[est_A[i]] = A[i]; 42 | 43 | for(i in 1:S) { 44 | if(est_trend) { 45 | Uvec[i] = U[trends[i]]; // map shared trends 46 | } else { 47 | Uvec[i] = 0; 48 | } 49 | } 50 | for(i in 1:S) { 51 | for(j in 1:S) { 52 | if(i==j) { 53 | Bmat[i,j] = 1; 54 | } else { 55 | Bmat[i,j] = 0; 56 | } 57 | } 58 | } 59 | if(est_B) Bmat = B; 60 | 61 | x[1,] = x0; 62 | for(t in 2:N) { 63 | x[t,] = Bmat * x[t-1,] + pro_dev[t-1,]; 64 | if(est_trend == 1) { 65 | x[t,] = x[t,] + Uvec; 66 | } 67 | } 68 | 69 | // map predicted states to time series 70 | for(m in 1:M) { 71 | for(t in 1:N) { 72 | pred[t,m] = x[t,states[m]] + Avec[m]; 73 | } 74 | } 75 | } 76 | model { 77 | x0 ~ normal(0, 3); // initial states 78 | A ~ normal(0, 3); // A offsets 79 | 80 | for(i in 1:n_obsvar) { 81 | sigma_obs[i] ~ student_t(3,0,1); // observation var sigma 82 | } 83 | for(s in 1:n_provar) { 84 | sigma_process[s] ~ student_t(3,0,1); // process var sigma 85 | } 86 | if(est_trend==1){ 87 | for(i in 1:n_trends) { 88 | U[i] ~ normal(0,1); // optional trends 89 | } 90 | } 91 | for(s in 1:S) { 92 | pro_dev[s] ~ normal(0, sigma_process[proVariances[s]]); // process deviations 93 | } 94 | if(est_B ==1) { 95 | for(i in 1:S) { 96 | for(j in 1:S) { 97 | if(i==j) { 98 | B[i,j] ~ uniform(0,1); 99 | } else { 100 | B[i,j] ~ normal(0,1); 101 | } 102 | } 103 | } 104 | } 105 | 106 | // likelihood 107 | for(i in 1:n_pos) { 108 | if(family==1) y[i] ~ normal(pred[col_indx_pos[i], row_indx_pos[i]], sigma_obs[obsVariances[row_indx_pos[i]]]); 109 | if(family==2) y_int[i] ~ bernoulli_logit(pred[col_indx_pos[i], row_indx_pos[i]]); 110 | if(family==3) y_int[i] ~ poisson_log(pred[col_indx_pos[i], row_indx_pos[i]]); 111 | if(family==4) y[i] ~ gamma(sigma_obs[obsVariances[row_indx_pos[i]]], sigma_obs[obsVariances[row_indx_pos[i]]] ./ pred[col_indx_pos[i], row_indx_pos[i]]); 112 | if(family==5) y[i] ~ lognormal(pred[col_indx_pos[i], row_indx_pos[i]], sigma_obs[obsVariances[row_indx_pos[i]]]); 113 | } 114 | } 115 | generated quantities { 116 | vector[n_pos] log_lik; 117 | // regresssion example in loo() package 118 | if(family==1) for (n in 1:n_pos) log_lik[n] = normal_lpdf(y[n] | pred[col_indx_pos[n], row_indx_pos[n]], sigma_obs[obsVariances[row_indx_pos[n]]]); 119 | if(family==2) for (n in 1:n_pos) log_lik[n] = bernoulli_lpmf(y_int[n] | inv_logit(pred[col_indx_pos[n], row_indx_pos[n]])); 120 | if(family==3) for (n in 1:n_pos) log_lik[n] = poisson_lpmf(y_int[n] | exp(pred[col_indx_pos[n], row_indx_pos[n]])); 121 | if(family==4) for (n in 1:n_pos) log_lik[n] = gamma_lpdf(y[n] | sigma_obs[obsVariances[row_indx_pos[n]]], sigma_obs[obsVariances[row_indx_pos[n]]] ./ exp(pred[col_indx_pos[n], row_indx_pos[n]])); 122 | if(family==5) for (n in 1:n_pos) log_lik[n] = lognormal_lpdf(y[n] | pred[col_indx_pos[n], row_indx_pos[n]], sigma_obs[obsVariances[row_indx_pos[n]]]); 123 | } 124 | -------------------------------------------------------------------------------- /inst/stan/regression.stan: -------------------------------------------------------------------------------- 1 | data { 2 | int N; 3 | int K; 4 | matrix[N, K] x; 5 | vector[N] y; 6 | int y_int[N]; 7 | int family; // 1 = normal, 2 = binomial, 3 = poisson, 4 = gamma, 5 = lognormal 8 | } 9 | parameters { 10 | vector[K] beta; 11 | real sigma; 12 | } 13 | transformed parameters { 14 | vector[N] pred; 15 | pred = x * beta; 16 | } 17 | model { 18 | beta ~ normal(0,2); 19 | sigma ~ student_t(3,0,2); 20 | if(family==1) y ~ normal(pred, sigma); 21 | if(family==2) y_int ~ bernoulli_logit(pred); 22 | if(family==3) y_int ~ poisson_log(pred); 23 | if(family==4) y ~ gamma(sigma, sigma ./ exp(pred)); 24 | if(family==5) y ~ lognormal(pred, sigma); 25 | } 26 | generated quantities { 27 | vector[N] log_lik; 28 | // regresssion example in loo() package 29 | if(family==1) for (n in 1:N) log_lik[n] = normal_lpdf(y[n] | pred[n], sigma); 30 | if(family==2) for (n in 1:N) log_lik[n] = bernoulli_lpmf(y_int[n] | inv_logit(pred[n])); 31 | if(family==3) for (n in 1:N) log_lik[n] = poisson_lpmf(y_int[n] | exp(pred[n])); 32 | if(family==4) for (n in 1:N) log_lik[n] = gamma_lpdf(y[n] | sigma, sigma ./ exp(pred[n])); 33 | if(family==5) for (n in 1:N) log_lik[n] = lognormal_lpdf(y[n] | pred[n], sigma); 34 | } 35 | -------------------------------------------------------------------------------- /inst/stan/regression_cor.stan: -------------------------------------------------------------------------------- 1 | data { 2 | int N; 3 | int K; 4 | matrix[N, K] x; 5 | vector[N] y; 6 | int y_int[N]; 7 | int family; // 1 = normal, 2 = binomial, 3 = poisson, 4 = gamma, 5 = lognormal 8 | } 9 | parameters { 10 | vector[K] beta; 11 | real sigma; 12 | real phi; 13 | } 14 | transformed parameters { 15 | vector[N] pred; 16 | vector[N] epsilon; 17 | real sigma_cor; 18 | pred[1] = x[1] * beta; 19 | epsilon[1] = y[1]-pred[1]; 20 | for(i in 2:N) { 21 | pred[i] = x[i] * beta; 22 | epsilon[i] = (y[i] - pred[i]) - phi*epsilon[i-1]; 23 | } 24 | sigma_cor = sqrt(sigma*sigma * (1-phi*phi)); // Var = sigma2 * (1-rho^2) 25 | } 26 | model { 27 | phi ~ normal(0,1); 28 | beta ~ normal(0,2); 29 | sigma ~ student_t(3,0,2); 30 | if(family==1) y ~ normal(pred, sigma_cor); 31 | if(family==2) y_int ~ bernoulli_logit(pred); 32 | if(family==3) y_int ~ poisson_log(pred); 33 | if(family==4) y ~ gamma(sigma_cor, sigma_cor ./ exp(pred)); 34 | if(family==5) y ~ lognormal(pred, sigma_cor); 35 | } 36 | generated quantities { 37 | vector[N] log_lik; 38 | // regresssion example in loo() package 39 | if(family==1) for (n in 1:N) log_lik[n] = normal_lpdf(y[n] | pred[n], sigma_cor); 40 | if(family==2) for (n in 1:N) log_lik[n] = bernoulli_lpmf(y_int[n] | inv_logit(pred[n])); 41 | if(family==3) for (n in 1:N) log_lik[n] = poisson_lpmf(y_int[n] | exp(pred[n])); 42 | if(family==4) for (n in 1:N) log_lik[n] = gamma_lpdf(y[n] | sigma_cor, sigma_cor ./ exp(pred[n])); 43 | if(family==5) for (n in 1:N) log_lik[n] = lognormal_lpdf(y[n] | pred[n], sigma_cor); 44 | } 45 | -------------------------------------------------------------------------------- /inst/stan/rw.stan: -------------------------------------------------------------------------------- 1 | data { 2 | int N; 3 | real y[N]; 4 | int est_drift; 5 | int est_nu; 6 | } 7 | parameters { 8 | real sigma; // outcome noise 9 | real mu[est_drift]; 10 | real nu[est_nu]; 11 | } 12 | transformed parameters { 13 | real pred[N]; 14 | real temp; 15 | pred[1] = 0; 16 | temp = 0; 17 | if(est_drift == 1) { 18 | temp = mu[1]; 19 | } 20 | for(i in 2:N) { 21 | pred[i] = y[i-1] + temp; 22 | } 23 | } 24 | model { 25 | if(est_nu==1) { 26 | nu ~ student_t(3,2,2); 27 | } 28 | if(est_nu==0) { 29 | y[2:N] ~ normal(pred[2:N], sigma); 30 | } else { 31 | y[2:N] ~ student_t(nu, pred[2:N], sigma); 32 | } 33 | sigma ~ student_t(3,0,2); 34 | if(est_drift==1) { 35 | mu ~ normal(0,1); 36 | } 37 | } 38 | generated quantities { 39 | vector[N-1] log_lik; 40 | // regresssion example in loo() package 41 | for (n in 2:N) log_lik[n-1] = normal_lpdf(y[n] | pred[n], sigma); 42 | } 43 | -------------------------------------------------------------------------------- /inst/stan/ss_ar.stan: -------------------------------------------------------------------------------- 1 | data { 2 | int N; 3 | int n_pos; 4 | vector[n_pos] y; 5 | int y_int[n_pos]; 6 | int pos_indx[n_pos+2]; 7 | int est_drift; 8 | int est_nu; 9 | int family; // 1 = normal, 2 = binomial, 3 = poisson, 4 = gamma, 5 = lognormal 10 | } 11 | parameters { 12 | real x0; 13 | real phi; 14 | real mu[est_drift]; 15 | vector[N-1] pro_dev; 16 | real sigma_process; 17 | real sigma_obs; 18 | real nu[est_nu]; 19 | } 20 | transformed parameters { 21 | vector[N] pred; 22 | real temp; 23 | pred[1] = x0; 24 | temp = 0; 25 | if(est_drift==1) { 26 | temp = mu[1]; 27 | } 28 | for(i in 2:N) { 29 | pred[i] = temp + phi*(pred[i-1] - temp) + sigma_process*pro_dev[i-1]; 30 | } 31 | } 32 | model { 33 | x0 ~ normal(0,10); 34 | phi ~ uniform(-0.999,0.999); 35 | if(est_drift==1) { 36 | mu ~ normal(0,10); 37 | } 38 | if(est_nu==1) { 39 | nu ~ student_t(3,2,2); 40 | } 41 | sigma_process ~ student_t(3,0,2); 42 | sigma_obs ~ student_t(3,0,2); 43 | if(est_nu==0) { 44 | pro_dev ~ std_normal();//normal(0, sigma_process); 45 | } else { 46 | pro_dev ~ student_t(nu,0,1); 47 | } 48 | 49 | if(family==1) { 50 | for(i in 1:(n_pos)) { 51 | //y ~ normal(pred, sigma_obs); 52 | y[i] ~ normal(pred[pos_indx[i]], sigma_obs); 53 | } 54 | } 55 | if(family==2) { 56 | for(i in 1:(n_pos)) { 57 | y_int[i] ~ bernoulli_logit(pred[pos_indx[i]]); 58 | } 59 | } 60 | if(family==3) { 61 | for(i in 1:(n_pos)) { 62 | y_int[i] ~ poisson_log(pred[pos_indx[i]]); 63 | } 64 | } 65 | if(family==4) { 66 | for(i in 1:(n_pos)) { 67 | y[i] ~ gamma(sigma_obs, sigma_obs ./ exp(pred[pos_indx[i]])); 68 | } 69 | } 70 | if(family==5) { 71 | for(i in 1:(n_pos)) { 72 | y[i] ~ lognormal(pred[pos_indx[i]], sigma_obs); 73 | } 74 | } 75 | } 76 | generated quantities { 77 | vector[n_pos] log_lik; 78 | // regresssion example in loo() package 79 | if(family==1) for (n in 1:n_pos) log_lik[n] = normal_lpdf(y[n] | pred[pos_indx[n]], sigma_obs); 80 | if(family==2) for (n in 1:n_pos) log_lik[n] = bernoulli_lpmf(y_int[n] | inv_logit(pred[pos_indx[n]])); 81 | if(family==3) for (n in 1:n_pos) log_lik[n] = poisson_lpmf(y_int[n] | exp(pred[pos_indx[n]])); 82 | if(family==4) for (n in 1:n_pos) log_lik[n] = gamma_lpdf(y[n] | sigma_obs, sigma_obs ./ exp(pred[pos_indx[n]])); 83 | if(family==5) for (n in 1:n_pos) log_lik[n] = lognormal_lpdf(y[n] | pred[pos_indx[n]], sigma_obs); 84 | } 85 | -------------------------------------------------------------------------------- /inst/stan/ss_ar_mean.stan: -------------------------------------------------------------------------------- 1 | data { 2 | int N; 3 | int n_pos; 4 | vector[n_pos] y; 5 | int y_int[n_pos]; 6 | int pos_indx[n_pos+2]; 7 | int est_nu; 8 | int family; // 1 = normal, 2 = binomial, 3 = poisson, 4 = gamma, 5 = lognormal 9 | } 10 | parameters { 11 | real x0; 12 | real phi; 13 | real mu; 14 | vector[N-1] pro_dev; 15 | real sigma_process; 16 | real sigma_obs; 17 | real nu[est_nu]; 18 | } 19 | transformed parameters { 20 | vector[N] pred; 21 | pred[1] = x0; 22 | for(i in 2:N) { 23 | pred[i] = mu + phi*(pred[i-1] - mu) + sigma_process*pro_dev[i-1]; 24 | } 25 | } 26 | model { 27 | x0 ~ normal(0,10); 28 | phi ~ normal(0,10); 29 | mu ~ normal(0,10); 30 | if(est_nu==1) { 31 | nu ~ student_t(3,2,2); 32 | } 33 | sigma_process ~ student_t(3,0,2); 34 | sigma_obs ~ student_t(3,0,2); 35 | if(est_nu==0) { 36 | pro_dev ~ std_normal();//normal(0, sigma_process); 37 | } else { 38 | pro_dev ~ student_t(nu,0,1); 39 | } 40 | 41 | if(family==1) { 42 | for(i in 1:(n_pos)) { 43 | //y ~ normal(pred, sigma_obs); 44 | y[i] ~ normal(pred[pos_indx[i]], sigma_obs); 45 | } 46 | } 47 | if(family==2) { 48 | for(i in 1:(n_pos)) { 49 | y_int[i] ~ bernoulli_logit(pred[pos_indx[i]]); 50 | } 51 | } 52 | if(family==3) { 53 | for(i in 1:(n_pos)) { 54 | y_int[i] ~ poisson_log(pred[pos_indx[i]]); 55 | } 56 | } 57 | if(family==4) { 58 | for(i in 1:(n_pos)) { 59 | y[i] ~ gamma(sigma_obs, sigma_obs ./ exp(pred[pos_indx[i]])); 60 | } 61 | } 62 | if(family==5) { 63 | for(i in 1:(n_pos)) { 64 | y[i] ~ lognormal(pred[pos_indx[i]], sigma_obs); 65 | } 66 | } 67 | } 68 | generated quantities { 69 | vector[n_pos] log_lik; 70 | // regresssion example in loo() package 71 | if(family==1) for (n in 1:n_pos) log_lik[n] = normal_lpdf(y[n] | pred[pos_indx[n]], sigma_obs); 72 | if(family==2) for (n in 1:n_pos) log_lik[n] = bernoulli_lpmf(y_int[n] | inv_logit(pred[pos_indx[n]])); 73 | if(family==3) for (n in 1:n_pos) log_lik[n] = poisson_lpmf(y_int[n] | exp(pred[pos_indx[n]])); 74 | if(family==4) for (n in 1:n_pos) log_lik[n] = gamma_lpdf(y[n] | sigma_obs, sigma_obs ./ exp(pred[pos_indx[n]])); 75 | if(family==5) for (n in 1:n_pos) log_lik[n] = lognormal_lpdf(y[n] | pred[pos_indx[n]], sigma_obs); 76 | } 77 | -------------------------------------------------------------------------------- /inst/stan/ss_rw.stan: -------------------------------------------------------------------------------- 1 | data { 2 | int N; 3 | int n_pos; 4 | vector[n_pos] y; 5 | int y_int[n_pos]; 6 | int pos_indx[n_pos+2]; 7 | int est_drift; 8 | int est_nu; 9 | int family; // 1 = normal, 2 = binomial, 3 = poisson, 4 = gamma, 5 = lognormal 10 | } 11 | parameters { 12 | real x0; 13 | real mu[est_drift]; 14 | vector[N-1] pro_dev; 15 | real sigma_process; 16 | real sigma_obs; 17 | real nu[est_nu]; 18 | } 19 | transformed parameters { 20 | vector[N] pred; 21 | real temp; 22 | pred[1] = x0; 23 | temp = 0; 24 | if(est_drift==1) { 25 | temp = mu[1]; 26 | } 27 | for(i in 2:N) { 28 | pred[i] = pred[i-1] + temp + sigma_process*pro_dev[i-1]; 29 | } 30 | } 31 | model { 32 | x0 ~ normal(0,10); 33 | if(est_drift==1) { 34 | mu ~ normal(0,2); 35 | } 36 | if(est_nu==1) { 37 | nu ~ student_t(3,2,2); 38 | } 39 | sigma_process ~ student_t(3,0,2); 40 | sigma_obs ~ student_t(3,0,2); 41 | if(est_nu==0) { 42 | pro_dev ~ std_normal();//normal(0, sigma_process); 43 | } else { 44 | pro_dev ~ student_t(nu,0,1); 45 | } 46 | 47 | if(family==1) { 48 | for(i in 1:(n_pos)) { 49 | //y ~ normal(pred, sigma_obs); 50 | y[i] ~ normal(pred[pos_indx[i]], sigma_obs); 51 | } 52 | } 53 | if(family==2) { 54 | for(i in 1:(n_pos)) { 55 | y_int[i] ~ bernoulli_logit(pred[pos_indx[i]]); 56 | } 57 | } 58 | if(family==3) { 59 | for(i in 1:(n_pos)) { 60 | y_int[i] ~ poisson_log(pred[pos_indx[i]]); 61 | } 62 | } 63 | if(family==4) { 64 | for(i in 1:(n_pos)) { 65 | y[i] ~ gamma(sigma_obs, sigma_obs ./ exp(pred[pos_indx[i]])); 66 | } 67 | } 68 | if(family==5) { 69 | for(i in 1:(n_pos)) { 70 | y[i] ~ lognormal(pred[pos_indx[i]], sigma_obs); 71 | } 72 | } 73 | } 74 | generated quantities { 75 | vector[n_pos] log_lik; 76 | // regresssion example in loo() package 77 | if(family==1) for (n in 1:n_pos) log_lik[n] = normal_lpdf(y[n] | pred[pos_indx[n]], sigma_obs); 78 | if(family==2) for (n in 1:n_pos) log_lik[n] = bernoulli_lpmf(y_int[n] | inv_logit(pred[pos_indx[n]])); 79 | if(family==3) for (n in 1:n_pos) log_lik[n] = poisson_lpmf(y_int[n] | exp(pred[pos_indx[n]])); 80 | if(family==4) for (n in 1:n_pos) log_lik[n] = gamma_lpdf(y[n] | sigma_obs, sigma_obs ./ exp(pred[pos_indx[n]])); 81 | if(family==5) for (n in 1:n_pos) log_lik[n] = lognormal_lpdf(y[n] | pred[pos_indx[n]], sigma_obs); 82 | } 83 | -------------------------------------------------------------------------------- /man/atsar-package.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/atsar-package.R 3 | \docType{package} 4 | \name{atsar-package} 5 | \alias{atsar-package} 6 | \alias{atsar} 7 | \title{The 'atsar' package.} 8 | \description{ 9 | A DESCRIPTION OF THE PACKAGE 10 | } 11 | \references{ 12 | Stan Development Team (2020). RStan: the R interface to Stan. R package version 2.21.2. https://mc-stan.org 13 | } 14 | -------------------------------------------------------------------------------- /man/fit_stan.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/fit_stan.R 3 | \name{fit_stan} 4 | \alias{fit_stan} 5 | \title{fit_stan is the primary function which calls pre-written stan scripts for time series data.} 6 | \usage{ 7 | fit_stan( 8 | y, 9 | x = NA, 10 | model_name = NA, 11 | est_drift = FALSE, 12 | est_mean = FALSE, 13 | P = 1, 14 | Q = 1, 15 | mcmc_list = list(n_mcmc = 1000, n_burn = 500, n_chain = 3, n_thin = 1), 16 | family = "gaussian", 17 | est_nu = FALSE, 18 | marss = list(states = NULL, obsVariances = NULL, proVariances = NULL, trends = NULL), 19 | map_estimation = FALSE, 20 | hessian = FALSE, 21 | ... 22 | ) 23 | } 24 | \arguments{ 25 | \item{y}{The response variable (numeric)} 26 | 27 | \item{x}{The predictors, either a vector or matrix} 28 | 29 | \item{model_name}{The specific name of the model to be fitted. Currently supported are 'regression', 'ar', 'rw', 'ma', 'ss_ar' (state space univariate AR), or 'ss_rw' (state space univariate random walk).} 30 | 31 | \item{est_drift}{Whether or not to estimate a drift parameter (default = FALSE). Only applicable to the rw and ar models.} 32 | 33 | \item{est_mean}{Whether to estimate a mean or not (for state space autoregressive model only)} 34 | 35 | \item{P}{The order of the ar model, with minimum value = 1 (default).} 36 | 37 | \item{Q}{The order of the ma model, with minimum value = 1 (default).} 38 | 39 | \item{mcmc_list}{A list of MCMC control parameters. These include the number of 'iterations' (default = 1000), burn in or warmup (default = 500), chains (default = 3), and thinning (default = 1)} 40 | 41 | \item{family}{A named distribution for the observation model, defaults to gaussian} 42 | 43 | \item{est_nu}{Boolean, whether to model process deviations as Student-t or not (default).} 44 | 45 | \item{marss}{A named list containing the following elements for specifying marss models: (states=NULL, obsVariances=NULL, proVariances=NULL, trends=NULL} 46 | 47 | \item{map_estimation}{Whether to do maximum a posteriori estimation via [rstan::optimizing()] (defualts to FALSE)} 48 | 49 | \item{hessian}{Whether to return hessian if map_estimation is TRUE via [rstan::optimizing()]} 50 | 51 | \item{...}{Any other arguments passed to [rstan::sampling()].} 52 | } 53 | \value{ 54 | an object of class 'rstan' 55 | } 56 | \description{ 57 | fit_stan is the primary function which calls pre-written stan scripts for time series data. 58 | } 59 | -------------------------------------------------------------------------------- /pkgdown/extra.css: -------------------------------------------------------------------------------- 1 | @import url("https://nmfs-general-modeling-tools.github.io/nmfspalette/extra.css"); 2 | -------------------------------------------------------------------------------- /src/Makevars: -------------------------------------------------------------------------------- 1 | # Generated by rstantools. Do not edit by hand. 2 | 3 | STANHEADERS_SRC = $(shell "$(R_HOME)/bin$(R_ARCH_BIN)/Rscript" -e "message()" -e "cat(system.file('include', 'src', package = 'StanHeaders', mustWork = TRUE))" -e "message()" | grep "StanHeaders") 4 | 5 | STANC_FLAGS = $(shell "$(R_HOME)/bin$(R_ARCH_BIN)/Rscript" -e "cat(ifelse(utils::packageVersion('rstan') >= '2.26', '-DUSE_STANC3',''))") 6 | PKG_CPPFLAGS = -I"../inst/include" -I"$(STANHEADERS_SRC)" -DBOOST_DISABLE_ASSERTS -DEIGEN_NO_DEBUG -DBOOST_MATH_OVERFLOW_ERROR_POLICY=errno_on_error $(STANC_FLAGS) -D_HAS_AUTO_PTR_ETC=0 7 | PKG_CXXFLAGS = $(shell "$(R_HOME)/bin$(R_ARCH_BIN)/Rscript" -e "RcppParallel::CxxFlags()") $(shell "$(R_HOME)/bin$(R_ARCH_BIN)/Rscript" -e "StanHeaders:::CxxFlags()") 8 | PKG_LIBS = $(shell "$(R_HOME)/bin$(R_ARCH_BIN)/Rscript" -e "RcppParallel::RcppParallelLibs()") $(shell "$(R_HOME)/bin$(R_ARCH_BIN)/Rscript" -e "StanHeaders:::LdFlags()") 9 | 10 | CXX_STD = CXX17 11 | -------------------------------------------------------------------------------- /src/Makevars.win: -------------------------------------------------------------------------------- 1 | # Generated by rstantools. Do not edit by hand. 2 | 3 | STANHEADERS_SRC = $(shell "$(R_HOME)/bin$(R_ARCH_BIN)/Rscript" -e "message()" -e "cat(system.file('include', 'src', package = 'StanHeaders', mustWork = TRUE))" -e "message()" | grep "StanHeaders") 4 | 5 | STANC_FLAGS = $(shell "$(R_HOME)/bin$(R_ARCH_BIN)/Rscript" -e "cat(ifelse(utils::packageVersion('rstan') >= 2.26, '-DUSE_STANC3',''))") 6 | PKG_CPPFLAGS = -I"../inst/include" -I"$(STANHEADERS_SRC)" -DBOOST_DISABLE_ASSERTS -DEIGEN_NO_DEBUG -DRCPP_PARALLEL_USE_TBB=1 $(STANC_FLAGS) 7 | PKG_CXXFLAGS = $(shell "$(R_HOME)/bin$(R_ARCH_BIN)/Rscript" -e "RcppParallel::CxxFlags()") $(shell "$(R_HOME)/bin$(R_ARCH_BIN)/Rscript" -e "StanHeaders:::CxxFlags()") 8 | PKG_LIBS = $(shell "$(R_HOME)/bin$(R_ARCH_BIN)/Rscript" -e "RcppParallel::RcppParallelLibs()") $(shell "$(R_HOME)/bin$(R_ARCH_BIN)/Rscript" -e "StanHeaders:::LdFlags()") 9 | 10 | CXX_STD = CXX14 11 | -------------------------------------------------------------------------------- /src/RcppExports.cpp: -------------------------------------------------------------------------------- 1 | // Generated by using Rcpp::compileAttributes() -> do not edit by hand 2 | // Generator token: 10BE3573-1514-4C36-9D1C-5A225CD40393 3 | 4 | #include 5 | #include 6 | 7 | using namespace Rcpp; 8 | 9 | #ifdef RCPP_USE_GLOBAL_ROSTREAM 10 | Rcpp::Rostream& Rcpp::Rcout = Rcpp::Rcpp_cout_get(); 11 | Rcpp::Rostream& Rcpp::Rcerr = Rcpp::Rcpp_cerr_get(); 12 | #endif 13 | 14 | 15 | RcppExport SEXP _rcpp_module_boot_stan_fit4ar_mod(); 16 | RcppExport SEXP _rcpp_module_boot_stan_fit4dlm_mod(); 17 | RcppExport SEXP _rcpp_module_boot_stan_fit4dlm_int_mod(); 18 | RcppExport SEXP _rcpp_module_boot_stan_fit4dlm_slope_mod(); 19 | RcppExport SEXP _rcpp_module_boot_stan_fit4ma_mod(); 20 | RcppExport SEXP _rcpp_module_boot_stan_fit4ma1_mod(); 21 | RcppExport SEXP _rcpp_module_boot_stan_fit4marss_mod(); 22 | RcppExport SEXP _rcpp_module_boot_stan_fit4regression_mod(); 23 | RcppExport SEXP _rcpp_module_boot_stan_fit4regression_cor_mod(); 24 | RcppExport SEXP _rcpp_module_boot_stan_fit4rw_mod(); 25 | RcppExport SEXP _rcpp_module_boot_stan_fit4ss_ar_mod(); 26 | RcppExport SEXP _rcpp_module_boot_stan_fit4ss_ar_mean_mod(); 27 | RcppExport SEXP _rcpp_module_boot_stan_fit4ss_rw_mod(); 28 | 29 | static const R_CallMethodDef CallEntries[] = { 30 | {"_rcpp_module_boot_stan_fit4ar_mod", (DL_FUNC) &_rcpp_module_boot_stan_fit4ar_mod, 0}, 31 | {"_rcpp_module_boot_stan_fit4dlm_mod", (DL_FUNC) &_rcpp_module_boot_stan_fit4dlm_mod, 0}, 32 | {"_rcpp_module_boot_stan_fit4dlm_int_mod", (DL_FUNC) &_rcpp_module_boot_stan_fit4dlm_int_mod, 0}, 33 | {"_rcpp_module_boot_stan_fit4dlm_slope_mod", (DL_FUNC) &_rcpp_module_boot_stan_fit4dlm_slope_mod, 0}, 34 | {"_rcpp_module_boot_stan_fit4ma_mod", (DL_FUNC) &_rcpp_module_boot_stan_fit4ma_mod, 0}, 35 | {"_rcpp_module_boot_stan_fit4ma1_mod", (DL_FUNC) &_rcpp_module_boot_stan_fit4ma1_mod, 0}, 36 | {"_rcpp_module_boot_stan_fit4marss_mod", (DL_FUNC) &_rcpp_module_boot_stan_fit4marss_mod, 0}, 37 | {"_rcpp_module_boot_stan_fit4regression_mod", (DL_FUNC) &_rcpp_module_boot_stan_fit4regression_mod, 0}, 38 | {"_rcpp_module_boot_stan_fit4regression_cor_mod", (DL_FUNC) &_rcpp_module_boot_stan_fit4regression_cor_mod, 0}, 39 | {"_rcpp_module_boot_stan_fit4rw_mod", (DL_FUNC) &_rcpp_module_boot_stan_fit4rw_mod, 0}, 40 | {"_rcpp_module_boot_stan_fit4ss_ar_mod", (DL_FUNC) &_rcpp_module_boot_stan_fit4ss_ar_mod, 0}, 41 | {"_rcpp_module_boot_stan_fit4ss_ar_mean_mod", (DL_FUNC) &_rcpp_module_boot_stan_fit4ss_ar_mean_mod, 0}, 42 | {"_rcpp_module_boot_stan_fit4ss_rw_mod", (DL_FUNC) &_rcpp_module_boot_stan_fit4ss_rw_mod, 0}, 43 | {NULL, NULL, 0} 44 | }; 45 | 46 | RcppExport void R_init_atsar(DllInfo *dll) { 47 | R_registerRoutines(dll, NULL, CallEntries, NULL, NULL); 48 | R_useDynamicSymbols(dll, FALSE); 49 | } 50 | -------------------------------------------------------------------------------- /src/stanExports_ar.cc: -------------------------------------------------------------------------------- 1 | // Generated by rstantools. Do not edit by hand. 2 | 3 | #include 4 | using namespace Rcpp ; 5 | #include "stanExports_ar.h" 6 | 7 | RCPP_MODULE(stan_fit4ar_mod) { 8 | 9 | 10 | class_ >("rstantools_model_ar") 11 | 12 | .constructor() 13 | 14 | 15 | .method("call_sampler", &rstan::stan_fit ::call_sampler) 16 | .method("param_names", &rstan::stan_fit ::param_names) 17 | .method("param_names_oi", &rstan::stan_fit ::param_names_oi) 18 | .method("param_fnames_oi", &rstan::stan_fit ::param_fnames_oi) 19 | .method("param_dims", &rstan::stan_fit ::param_dims) 20 | .method("param_dims_oi", &rstan::stan_fit ::param_dims_oi) 21 | .method("update_param_oi", &rstan::stan_fit ::update_param_oi) 22 | .method("param_oi_tidx", &rstan::stan_fit ::param_oi_tidx) 23 | .method("grad_log_prob", &rstan::stan_fit ::grad_log_prob) 24 | .method("log_prob", &rstan::stan_fit ::log_prob) 25 | .method("unconstrain_pars", &rstan::stan_fit ::unconstrain_pars) 26 | .method("constrain_pars", &rstan::stan_fit ::constrain_pars) 27 | .method("num_pars_unconstrained", &rstan::stan_fit ::num_pars_unconstrained) 28 | .method("unconstrained_param_names", &rstan::stan_fit ::unconstrained_param_names) 29 | .method("constrained_param_names", &rstan::stan_fit ::constrained_param_names) 30 | .method("standalone_gqs", &rstan::stan_fit ::standalone_gqs) 31 | ; 32 | } 33 | -------------------------------------------------------------------------------- /src/stanExports_dlm.cc: -------------------------------------------------------------------------------- 1 | // Generated by rstantools. Do not edit by hand. 2 | 3 | #include 4 | using namespace Rcpp ; 5 | #include "stanExports_dlm.h" 6 | 7 | RCPP_MODULE(stan_fit4dlm_mod) { 8 | 9 | 10 | class_ >("rstantools_model_dlm") 11 | 12 | .constructor() 13 | 14 | 15 | .method("call_sampler", &rstan::stan_fit ::call_sampler) 16 | .method("param_names", &rstan::stan_fit ::param_names) 17 | .method("param_names_oi", &rstan::stan_fit ::param_names_oi) 18 | .method("param_fnames_oi", &rstan::stan_fit ::param_fnames_oi) 19 | .method("param_dims", &rstan::stan_fit ::param_dims) 20 | .method("param_dims_oi", &rstan::stan_fit ::param_dims_oi) 21 | .method("update_param_oi", &rstan::stan_fit ::update_param_oi) 22 | .method("param_oi_tidx", &rstan::stan_fit ::param_oi_tidx) 23 | .method("grad_log_prob", &rstan::stan_fit ::grad_log_prob) 24 | .method("log_prob", &rstan::stan_fit ::log_prob) 25 | .method("unconstrain_pars", &rstan::stan_fit ::unconstrain_pars) 26 | .method("constrain_pars", &rstan::stan_fit ::constrain_pars) 27 | .method("num_pars_unconstrained", &rstan::stan_fit ::num_pars_unconstrained) 28 | .method("unconstrained_param_names", &rstan::stan_fit ::unconstrained_param_names) 29 | .method("constrained_param_names", &rstan::stan_fit ::constrained_param_names) 30 | .method("standalone_gqs", &rstan::stan_fit ::standalone_gqs) 31 | ; 32 | } 33 | -------------------------------------------------------------------------------- /src/stanExports_dlm_int.cc: -------------------------------------------------------------------------------- 1 | // Generated by rstantools. Do not edit by hand. 2 | 3 | #include 4 | using namespace Rcpp ; 5 | #include "stanExports_dlm_int.h" 6 | 7 | RCPP_MODULE(stan_fit4dlm_int_mod) { 8 | 9 | 10 | class_ >("rstantools_model_dlm_int") 11 | 12 | .constructor() 13 | 14 | 15 | .method("call_sampler", &rstan::stan_fit ::call_sampler) 16 | .method("param_names", &rstan::stan_fit ::param_names) 17 | .method("param_names_oi", &rstan::stan_fit ::param_names_oi) 18 | .method("param_fnames_oi", &rstan::stan_fit ::param_fnames_oi) 19 | .method("param_dims", &rstan::stan_fit ::param_dims) 20 | .method("param_dims_oi", &rstan::stan_fit ::param_dims_oi) 21 | .method("update_param_oi", &rstan::stan_fit ::update_param_oi) 22 | .method("param_oi_tidx", &rstan::stan_fit ::param_oi_tidx) 23 | .method("grad_log_prob", &rstan::stan_fit ::grad_log_prob) 24 | .method("log_prob", &rstan::stan_fit ::log_prob) 25 | .method("unconstrain_pars", &rstan::stan_fit ::unconstrain_pars) 26 | .method("constrain_pars", &rstan::stan_fit ::constrain_pars) 27 | .method("num_pars_unconstrained", &rstan::stan_fit ::num_pars_unconstrained) 28 | .method("unconstrained_param_names", &rstan::stan_fit ::unconstrained_param_names) 29 | .method("constrained_param_names", &rstan::stan_fit ::constrained_param_names) 30 | .method("standalone_gqs", &rstan::stan_fit ::standalone_gqs) 31 | ; 32 | } 33 | -------------------------------------------------------------------------------- /src/stanExports_dlm_slope.cc: -------------------------------------------------------------------------------- 1 | // Generated by rstantools. Do not edit by hand. 2 | 3 | #include 4 | using namespace Rcpp ; 5 | #include "stanExports_dlm_slope.h" 6 | 7 | RCPP_MODULE(stan_fit4dlm_slope_mod) { 8 | 9 | 10 | class_ >("rstantools_model_dlm_slope") 11 | 12 | .constructor() 13 | 14 | 15 | .method("call_sampler", &rstan::stan_fit ::call_sampler) 16 | .method("param_names", &rstan::stan_fit ::param_names) 17 | .method("param_names_oi", &rstan::stan_fit ::param_names_oi) 18 | .method("param_fnames_oi", &rstan::stan_fit ::param_fnames_oi) 19 | .method("param_dims", &rstan::stan_fit ::param_dims) 20 | .method("param_dims_oi", &rstan::stan_fit ::param_dims_oi) 21 | .method("update_param_oi", &rstan::stan_fit ::update_param_oi) 22 | .method("param_oi_tidx", &rstan::stan_fit ::param_oi_tidx) 23 | .method("grad_log_prob", &rstan::stan_fit ::grad_log_prob) 24 | .method("log_prob", &rstan::stan_fit ::log_prob) 25 | .method("unconstrain_pars", &rstan::stan_fit ::unconstrain_pars) 26 | .method("constrain_pars", &rstan::stan_fit ::constrain_pars) 27 | .method("num_pars_unconstrained", &rstan::stan_fit ::num_pars_unconstrained) 28 | .method("unconstrained_param_names", &rstan::stan_fit ::unconstrained_param_names) 29 | .method("constrained_param_names", &rstan::stan_fit ::constrained_param_names) 30 | .method("standalone_gqs", &rstan::stan_fit ::standalone_gqs) 31 | ; 32 | } 33 | -------------------------------------------------------------------------------- /src/stanExports_ma.cc: -------------------------------------------------------------------------------- 1 | // Generated by rstantools. Do not edit by hand. 2 | 3 | #include 4 | using namespace Rcpp ; 5 | #include "stanExports_ma.h" 6 | 7 | RCPP_MODULE(stan_fit4ma_mod) { 8 | 9 | 10 | class_ >("rstantools_model_ma") 11 | 12 | .constructor() 13 | 14 | 15 | .method("call_sampler", &rstan::stan_fit ::call_sampler) 16 | .method("param_names", &rstan::stan_fit ::param_names) 17 | .method("param_names_oi", &rstan::stan_fit ::param_names_oi) 18 | .method("param_fnames_oi", &rstan::stan_fit ::param_fnames_oi) 19 | .method("param_dims", &rstan::stan_fit ::param_dims) 20 | .method("param_dims_oi", &rstan::stan_fit ::param_dims_oi) 21 | .method("update_param_oi", &rstan::stan_fit ::update_param_oi) 22 | .method("param_oi_tidx", &rstan::stan_fit ::param_oi_tidx) 23 | .method("grad_log_prob", &rstan::stan_fit ::grad_log_prob) 24 | .method("log_prob", &rstan::stan_fit ::log_prob) 25 | .method("unconstrain_pars", &rstan::stan_fit ::unconstrain_pars) 26 | .method("constrain_pars", &rstan::stan_fit ::constrain_pars) 27 | .method("num_pars_unconstrained", &rstan::stan_fit ::num_pars_unconstrained) 28 | .method("unconstrained_param_names", &rstan::stan_fit ::unconstrained_param_names) 29 | .method("constrained_param_names", &rstan::stan_fit ::constrained_param_names) 30 | .method("standalone_gqs", &rstan::stan_fit ::standalone_gqs) 31 | ; 32 | } 33 | -------------------------------------------------------------------------------- /src/stanExports_ma1.cc: -------------------------------------------------------------------------------- 1 | // Generated by rstantools. Do not edit by hand. 2 | 3 | #include 4 | using namespace Rcpp ; 5 | #include "stanExports_ma1.h" 6 | 7 | RCPP_MODULE(stan_fit4ma1_mod) { 8 | 9 | 10 | class_ >("rstantools_model_ma1") 11 | 12 | .constructor() 13 | 14 | 15 | .method("call_sampler", &rstan::stan_fit ::call_sampler) 16 | .method("param_names", &rstan::stan_fit ::param_names) 17 | .method("param_names_oi", &rstan::stan_fit ::param_names_oi) 18 | .method("param_fnames_oi", &rstan::stan_fit ::param_fnames_oi) 19 | .method("param_dims", &rstan::stan_fit ::param_dims) 20 | .method("param_dims_oi", &rstan::stan_fit ::param_dims_oi) 21 | .method("update_param_oi", &rstan::stan_fit ::update_param_oi) 22 | .method("param_oi_tidx", &rstan::stan_fit ::param_oi_tidx) 23 | .method("grad_log_prob", &rstan::stan_fit ::grad_log_prob) 24 | .method("log_prob", &rstan::stan_fit ::log_prob) 25 | .method("unconstrain_pars", &rstan::stan_fit ::unconstrain_pars) 26 | .method("constrain_pars", &rstan::stan_fit ::constrain_pars) 27 | .method("num_pars_unconstrained", &rstan::stan_fit ::num_pars_unconstrained) 28 | .method("unconstrained_param_names", &rstan::stan_fit ::unconstrained_param_names) 29 | .method("constrained_param_names", &rstan::stan_fit ::constrained_param_names) 30 | .method("standalone_gqs", &rstan::stan_fit ::standalone_gqs) 31 | ; 32 | } 33 | -------------------------------------------------------------------------------- /src/stanExports_marss.cc: -------------------------------------------------------------------------------- 1 | // Generated by rstantools. Do not edit by hand. 2 | 3 | #include 4 | using namespace Rcpp ; 5 | #include "stanExports_marss.h" 6 | 7 | RCPP_MODULE(stan_fit4marss_mod) { 8 | 9 | 10 | class_ >("rstantools_model_marss") 11 | 12 | .constructor() 13 | 14 | 15 | .method("call_sampler", &rstan::stan_fit ::call_sampler) 16 | .method("param_names", &rstan::stan_fit ::param_names) 17 | .method("param_names_oi", &rstan::stan_fit ::param_names_oi) 18 | .method("param_fnames_oi", &rstan::stan_fit ::param_fnames_oi) 19 | .method("param_dims", &rstan::stan_fit ::param_dims) 20 | .method("param_dims_oi", &rstan::stan_fit ::param_dims_oi) 21 | .method("update_param_oi", &rstan::stan_fit ::update_param_oi) 22 | .method("param_oi_tidx", &rstan::stan_fit ::param_oi_tidx) 23 | .method("grad_log_prob", &rstan::stan_fit ::grad_log_prob) 24 | .method("log_prob", &rstan::stan_fit ::log_prob) 25 | .method("unconstrain_pars", &rstan::stan_fit ::unconstrain_pars) 26 | .method("constrain_pars", &rstan::stan_fit ::constrain_pars) 27 | .method("num_pars_unconstrained", &rstan::stan_fit ::num_pars_unconstrained) 28 | .method("unconstrained_param_names", &rstan::stan_fit ::unconstrained_param_names) 29 | .method("constrained_param_names", &rstan::stan_fit ::constrained_param_names) 30 | .method("standalone_gqs", &rstan::stan_fit ::standalone_gqs) 31 | ; 32 | } 33 | -------------------------------------------------------------------------------- /src/stanExports_regression.cc: -------------------------------------------------------------------------------- 1 | // Generated by rstantools. Do not edit by hand. 2 | 3 | #include 4 | using namespace Rcpp ; 5 | #include "stanExports_regression.h" 6 | 7 | RCPP_MODULE(stan_fit4regression_mod) { 8 | 9 | 10 | class_ >("rstantools_model_regression") 11 | 12 | .constructor() 13 | 14 | 15 | .method("call_sampler", &rstan::stan_fit ::call_sampler) 16 | .method("param_names", &rstan::stan_fit ::param_names) 17 | .method("param_names_oi", &rstan::stan_fit ::param_names_oi) 18 | .method("param_fnames_oi", &rstan::stan_fit ::param_fnames_oi) 19 | .method("param_dims", &rstan::stan_fit ::param_dims) 20 | .method("param_dims_oi", &rstan::stan_fit ::param_dims_oi) 21 | .method("update_param_oi", &rstan::stan_fit ::update_param_oi) 22 | .method("param_oi_tidx", &rstan::stan_fit ::param_oi_tidx) 23 | .method("grad_log_prob", &rstan::stan_fit ::grad_log_prob) 24 | .method("log_prob", &rstan::stan_fit ::log_prob) 25 | .method("unconstrain_pars", &rstan::stan_fit ::unconstrain_pars) 26 | .method("constrain_pars", &rstan::stan_fit ::constrain_pars) 27 | .method("num_pars_unconstrained", &rstan::stan_fit ::num_pars_unconstrained) 28 | .method("unconstrained_param_names", &rstan::stan_fit ::unconstrained_param_names) 29 | .method("constrained_param_names", &rstan::stan_fit ::constrained_param_names) 30 | .method("standalone_gqs", &rstan::stan_fit ::standalone_gqs) 31 | ; 32 | } 33 | -------------------------------------------------------------------------------- /src/stanExports_regression_cor.cc: -------------------------------------------------------------------------------- 1 | // Generated by rstantools. Do not edit by hand. 2 | 3 | #include 4 | using namespace Rcpp ; 5 | #include "stanExports_regression_cor.h" 6 | 7 | RCPP_MODULE(stan_fit4regression_cor_mod) { 8 | 9 | 10 | class_ >("rstantools_model_regression_cor") 11 | 12 | .constructor() 13 | 14 | 15 | .method("call_sampler", &rstan::stan_fit ::call_sampler) 16 | .method("param_names", &rstan::stan_fit ::param_names) 17 | .method("param_names_oi", &rstan::stan_fit ::param_names_oi) 18 | .method("param_fnames_oi", &rstan::stan_fit ::param_fnames_oi) 19 | .method("param_dims", &rstan::stan_fit ::param_dims) 20 | .method("param_dims_oi", &rstan::stan_fit ::param_dims_oi) 21 | .method("update_param_oi", &rstan::stan_fit ::update_param_oi) 22 | .method("param_oi_tidx", &rstan::stan_fit ::param_oi_tidx) 23 | .method("grad_log_prob", &rstan::stan_fit ::grad_log_prob) 24 | .method("log_prob", &rstan::stan_fit ::log_prob) 25 | .method("unconstrain_pars", &rstan::stan_fit ::unconstrain_pars) 26 | .method("constrain_pars", &rstan::stan_fit ::constrain_pars) 27 | .method("num_pars_unconstrained", &rstan::stan_fit ::num_pars_unconstrained) 28 | .method("unconstrained_param_names", &rstan::stan_fit ::unconstrained_param_names) 29 | .method("constrained_param_names", &rstan::stan_fit ::constrained_param_names) 30 | .method("standalone_gqs", &rstan::stan_fit ::standalone_gqs) 31 | ; 32 | } 33 | -------------------------------------------------------------------------------- /src/stanExports_rw.cc: -------------------------------------------------------------------------------- 1 | // Generated by rstantools. Do not edit by hand. 2 | 3 | #include 4 | using namespace Rcpp ; 5 | #include "stanExports_rw.h" 6 | 7 | RCPP_MODULE(stan_fit4rw_mod) { 8 | 9 | 10 | class_ >("rstantools_model_rw") 11 | 12 | .constructor() 13 | 14 | 15 | .method("call_sampler", &rstan::stan_fit ::call_sampler) 16 | .method("param_names", &rstan::stan_fit ::param_names) 17 | .method("param_names_oi", &rstan::stan_fit ::param_names_oi) 18 | .method("param_fnames_oi", &rstan::stan_fit ::param_fnames_oi) 19 | .method("param_dims", &rstan::stan_fit ::param_dims) 20 | .method("param_dims_oi", &rstan::stan_fit ::param_dims_oi) 21 | .method("update_param_oi", &rstan::stan_fit ::update_param_oi) 22 | .method("param_oi_tidx", &rstan::stan_fit ::param_oi_tidx) 23 | .method("grad_log_prob", &rstan::stan_fit ::grad_log_prob) 24 | .method("log_prob", &rstan::stan_fit ::log_prob) 25 | .method("unconstrain_pars", &rstan::stan_fit ::unconstrain_pars) 26 | .method("constrain_pars", &rstan::stan_fit ::constrain_pars) 27 | .method("num_pars_unconstrained", &rstan::stan_fit ::num_pars_unconstrained) 28 | .method("unconstrained_param_names", &rstan::stan_fit ::unconstrained_param_names) 29 | .method("constrained_param_names", &rstan::stan_fit ::constrained_param_names) 30 | .method("standalone_gqs", &rstan::stan_fit ::standalone_gqs) 31 | ; 32 | } 33 | -------------------------------------------------------------------------------- /src/stanExports_ss_ar.cc: -------------------------------------------------------------------------------- 1 | // Generated by rstantools. Do not edit by hand. 2 | 3 | #include 4 | using namespace Rcpp ; 5 | #include "stanExports_ss_ar.h" 6 | 7 | RCPP_MODULE(stan_fit4ss_ar_mod) { 8 | 9 | 10 | class_ >("rstantools_model_ss_ar") 11 | 12 | .constructor() 13 | 14 | 15 | .method("call_sampler", &rstan::stan_fit ::call_sampler) 16 | .method("param_names", &rstan::stan_fit ::param_names) 17 | .method("param_names_oi", &rstan::stan_fit ::param_names_oi) 18 | .method("param_fnames_oi", &rstan::stan_fit ::param_fnames_oi) 19 | .method("param_dims", &rstan::stan_fit ::param_dims) 20 | .method("param_dims_oi", &rstan::stan_fit ::param_dims_oi) 21 | .method("update_param_oi", &rstan::stan_fit ::update_param_oi) 22 | .method("param_oi_tidx", &rstan::stan_fit ::param_oi_tidx) 23 | .method("grad_log_prob", &rstan::stan_fit ::grad_log_prob) 24 | .method("log_prob", &rstan::stan_fit ::log_prob) 25 | .method("unconstrain_pars", &rstan::stan_fit ::unconstrain_pars) 26 | .method("constrain_pars", &rstan::stan_fit ::constrain_pars) 27 | .method("num_pars_unconstrained", &rstan::stan_fit ::num_pars_unconstrained) 28 | .method("unconstrained_param_names", &rstan::stan_fit ::unconstrained_param_names) 29 | .method("constrained_param_names", &rstan::stan_fit ::constrained_param_names) 30 | .method("standalone_gqs", &rstan::stan_fit ::standalone_gqs) 31 | ; 32 | } 33 | -------------------------------------------------------------------------------- /src/stanExports_ss_ar_mean.cc: -------------------------------------------------------------------------------- 1 | // Generated by rstantools. Do not edit by hand. 2 | 3 | #include 4 | using namespace Rcpp ; 5 | #include "stanExports_ss_ar_mean.h" 6 | 7 | RCPP_MODULE(stan_fit4ss_ar_mean_mod) { 8 | 9 | 10 | class_ >("rstantools_model_ss_ar_mean") 11 | 12 | .constructor() 13 | 14 | 15 | .method("call_sampler", &rstan::stan_fit ::call_sampler) 16 | .method("param_names", &rstan::stan_fit ::param_names) 17 | .method("param_names_oi", &rstan::stan_fit ::param_names_oi) 18 | .method("param_fnames_oi", &rstan::stan_fit ::param_fnames_oi) 19 | .method("param_dims", &rstan::stan_fit ::param_dims) 20 | .method("param_dims_oi", &rstan::stan_fit ::param_dims_oi) 21 | .method("update_param_oi", &rstan::stan_fit ::update_param_oi) 22 | .method("param_oi_tidx", &rstan::stan_fit ::param_oi_tidx) 23 | .method("grad_log_prob", &rstan::stan_fit ::grad_log_prob) 24 | .method("log_prob", &rstan::stan_fit ::log_prob) 25 | .method("unconstrain_pars", &rstan::stan_fit ::unconstrain_pars) 26 | .method("constrain_pars", &rstan::stan_fit ::constrain_pars) 27 | .method("num_pars_unconstrained", &rstan::stan_fit ::num_pars_unconstrained) 28 | .method("unconstrained_param_names", &rstan::stan_fit ::unconstrained_param_names) 29 | .method("constrained_param_names", &rstan::stan_fit ::constrained_param_names) 30 | .method("standalone_gqs", &rstan::stan_fit ::standalone_gqs) 31 | ; 32 | } 33 | -------------------------------------------------------------------------------- /src/stanExports_ss_rw.cc: -------------------------------------------------------------------------------- 1 | // Generated by rstantools. Do not edit by hand. 2 | 3 | #include 4 | using namespace Rcpp ; 5 | #include "stanExports_ss_rw.h" 6 | 7 | RCPP_MODULE(stan_fit4ss_rw_mod) { 8 | 9 | 10 | class_ >("rstantools_model_ss_rw") 11 | 12 | .constructor() 13 | 14 | 15 | .method("call_sampler", &rstan::stan_fit ::call_sampler) 16 | .method("param_names", &rstan::stan_fit ::param_names) 17 | .method("param_names_oi", &rstan::stan_fit ::param_names_oi) 18 | .method("param_fnames_oi", &rstan::stan_fit ::param_fnames_oi) 19 | .method("param_dims", &rstan::stan_fit ::param_dims) 20 | .method("param_dims_oi", &rstan::stan_fit ::param_dims_oi) 21 | .method("update_param_oi", &rstan::stan_fit ::update_param_oi) 22 | .method("param_oi_tidx", &rstan::stan_fit ::param_oi_tidx) 23 | .method("grad_log_prob", &rstan::stan_fit ::grad_log_prob) 24 | .method("log_prob", &rstan::stan_fit ::log_prob) 25 | .method("unconstrain_pars", &rstan::stan_fit ::unconstrain_pars) 26 | .method("constrain_pars", &rstan::stan_fit ::constrain_pars) 27 | .method("num_pars_unconstrained", &rstan::stan_fit ::num_pars_unconstrained) 28 | .method("unconstrained_param_names", &rstan::stan_fit ::unconstrained_param_names) 29 | .method("constrained_param_names", &rstan::stan_fit ::constrained_param_names) 30 | .method("standalone_gqs", &rstan::stan_fit ::standalone_gqs) 31 | ; 32 | } 33 | -------------------------------------------------------------------------------- /tests/tests.R: -------------------------------------------------------------------------------- 1 | library(testthat) 2 | library(atsar) 3 | 4 | test_check("atsar") 5 | -------------------------------------------------------------------------------- /tests/testthat/testfits.R: -------------------------------------------------------------------------------- 1 | test_that("fitmodels", { 2 | 3 | set.seed(123) 4 | y <- cumsum(rnorm(30)) 5 | 6 | set.seed(123) 7 | mod <- fit_stan(y, model_name = "ar", est_drift = TRUE, mcmc_list=list(n_chain = 1, n_mcmc=300, n_burn=100, n_thin=1) ) 8 | pars <- rstan::extract(mod) 9 | expect_equal(mean(pars$sigma), 1.028974, tolerance = 0.01) 10 | 11 | set.seed(123) 12 | mod <- fit_stan(y, model_name = "ar", est_drift = FALSE, mcmc_list=list(n_chain = 1, n_mcmc=300, n_burn=100, n_thin=1) ) 13 | pars <- rstan::extract(mod) 14 | expect_equal(mean(pars$sigma), 1.011565, tolerance = 0.01) 15 | 16 | set.seed(123) 17 | mod <- fit_stan(y, model_name = "rw", est_drift = TRUE, mcmc_list=list(n_chain = 1, n_mcmc=300, n_burn=100, n_thin=1) ) 18 | pars <- rstan::extract(mod) 19 | expect_equal(mean(pars$sigma), 1.032227, tolerance = 0.01) 20 | 21 | set.seed(123) 22 | mod <- fit_stan(y, model_name = "rw", est_drift = FALSE, mcmc_list=list(n_chain = 1, n_mcmc=300, n_burn=100, n_thin=1) ) 23 | pars <- rstan::extract(mod) 24 | expect_equal(mean(pars$sigma), 1.03083, tolerance = 0.01) 25 | 26 | set.seed(123) 27 | mod <- fit_stan(y, x = 1:30, model_name = "regression", est_drift = FALSE, mcmc_list=list(n_chain = 1, n_mcmc=300, n_burn=100, n_thin=1) ) 28 | pars <- rstan::extract(mod) 29 | expect_equal(mean(pars$sigma), 2.18601, tolerance = 0.01) 30 | 31 | set.seed(123) 32 | mod <- fit_stan(y, model_name = "ss_ar", est_drift = TRUE, mcmc_list=list(n_chain = 1, n_mcmc=300, n_burn=100, n_thin=1) ) 33 | pars <- rstan::extract(mod) 34 | expect_equal(mean(pars$sigma_obs), 0.2898811, tolerance = 0.01) 35 | 36 | set.seed(123) 37 | mod <- fit_stan(y, model_name = "ss_ar", est_drift = FALSE, mcmc_list=list(n_chain = 1, n_mcmc=300, n_burn=100, n_thin=1) ) 38 | pars <- rstan::extract(mod) 39 | expect_equal(mean(pars$sigma_obs), 0.2503624, tolerance = 0.01) 40 | 41 | set.seed(123) 42 | mod <- fit_stan(y, model_name = "ss_rw", est_drift = TRUE, mcmc_list=list(n_chain = 1, n_mcmc=300, n_burn=100, n_thin=1) ) 43 | pars <- rstan::extract(mod) 44 | expect_equal(mean(pars$sigma_obs), 0.3714019, tolerance = 0.01) 45 | 46 | set.seed(123) 47 | mod <- fit_stan(y, model_name = "ss_rw", est_drift = FALSE, mcmc_list=list(n_chain = 1, n_mcmc=300, n_burn=100, n_thin=1) ) 48 | pars <- rstan::extract(mod) 49 | expect_equal(mean(pars$sigma_obs), 0.4040785, tolerance = 0.01) 50 | 51 | }) 52 | -------------------------------------------------------------------------------- /vignettes/dlm.Rmd: -------------------------------------------------------------------------------- 1 | --- 2 | title: "Dynamic linear models in package atsar" 3 | author: "Eric Ward" 4 | date: "`r Sys.Date()`" 5 | output: rmarkdown::html_vignette 6 | vignette: > 7 | %\VignetteIndexEntry{Dynamic linear models in package atsar} 8 | %\VignetteEngine{knitr::rmarkdown} 9 | \usepackage[utf8]{inputenc} 10 | --- 11 | 12 | ```{r setup, include=FALSE} 13 | knitr::opts_chunk$set(echo = TRUE) 14 | ``` 15 | 16 | ## Installation 17 | 18 | ```{r install, eval=TRUE, warning=FALSE, message=FALSE, results='hide'} 19 | library(rstan) 20 | library(atsar) 21 | 22 | # for optimizing stan on your machine, 23 | #rstan_options(auto_write = TRUE) 24 | #options(mc.cores = parallel::detectCores()) 25 | mcmc_list = list(n_mcmc = 1000, n_burn = 500, n_chain = 1, n_thin = 1) 26 | ``` 27 | 28 | ## Data 29 | 30 | We'll use the same data in the MARSS manual, from Mark's example in the Columbia River. The data are accessed with 31 | 32 | ```{r,eval=FALSE} 33 | library(MARSS) 34 | data(SalmonSurvCUI) 35 | ``` 36 | 37 | ### Fitting a univariate DLM 38 | 39 | We can start with fitting a DLM that includes no covariates, but a random walk in the intercept (mean). 40 | 41 | ```{r, message=FALSE, warning=FALSE, results='hide',eval=FALSE} 42 | mod = fit_stan(y = SalmonSurvCUI$logit.s, model_name="dlm-intercept",mcmc_list=mcmc_list) 43 | ``` 44 | 45 | Next, we can fit a model with constant intercept, but time-varying slope. 46 | 47 | ```{r, message=FALSE, warning=FALSE, results='hide',eval=FALSE} 48 | mod2 = fit_stan(y = SalmonSurvCUI$logit.s, x = SalmonSurvCUI$CUI.apr, 49 | model_name="dlm-slope",mcmc_list=mcmc_list) 50 | ``` 51 | 52 | Finally, we can fit a model with both a time varying intercept and a time varying slope. 53 | 54 | ```{r, message=FALSE, warning=FALSE, results='hide',eval=FALSE} 55 | mod = fit_stan(y = SalmonSurvCUI$logit.s, 56 | x = model.matrix(lm(SalmonSurvCUI$logit.s ~ SalmonSurvCUI$CUI.apr)), 57 | model_name="dlm", 58 | mcmc_list=mcmc_list) 59 | ``` 60 | 61 | ## Fitting non-normal errors 62 | 63 | We've implemented several non-normal observation model distributions in `stan_fit`, including "binomial", "poisson", "gamma", etc. As an example of how to use these in a DLM setting, we'll fit a DLM with time-varying mean and Poisson response to a time series of ecoli data, collected weekly. The data are in the `tscount` package. 64 | 65 | ```{r eval=FALSE} 66 | y = tscount::ecoli 67 | ``` 68 | 69 | We could fit a Poisson GLM in `fit_stan` with the following, 70 | 71 | ```{r, message=FALSE, warning=FALSE, results='hide',eval=FALSE} 72 | mod = fit_stan(y=y$cases, 73 | x = model.matrix(lm(y$cases~1)), 74 | model="regression", 75 | family="poisson", 76 | mcmc_list=mcmc_list) 77 | ``` 78 | 79 | But the regression model assumes independent observations between time steps. To include the autocorrelation between time points, we can fit a DLM, 80 | 81 | ```{r, message=FALSE, warning=FALSE, results='hide'} 82 | y = data.frame(cases = rpois(20,2)) 83 | mod = fit_stan(y$cases, 84 | model="dlm-intercept", 85 | family="poisson", 86 | mcmc_list=mcmc_list) 87 | ``` 88 | 89 | This more flexible model captures the data much better. Note: the credible intervals are on the mean, not new data. 90 | 91 | \break 92 | 93 | ```{r, fig.cap="Estimated fit of the DLM with Poisson observation model applied to E. coli count data."} 94 | pars = extract(mod) 95 | plot(apply(exp(pars$intercept), 2, mean), type="l", lwd=3, ylim=c(0,100), ylab="E coli", xlab="") 96 | lines(apply(exp(pars$intercept), 2, quantile,0.025)) 97 | lines(apply(exp(pars$intercept), 2, quantile,0.975)) 98 | points(y$cases, col="red", cex=0.3) 99 | ``` 100 | 101 | 102 | -------------------------------------------------------------------------------- /vignettes/fit_stan.Rmd: -------------------------------------------------------------------------------- 1 | --- 2 | title: "Fitting time series models in package atsar" 3 | author: "Eric Ward" 4 | date: "`r Sys.Date()`" 5 | output: rmarkdown::html_vignette 6 | vignette: > 7 | %\VignetteIndexEntry{Fitting time series models in package atsar} 8 | %\VignetteEngine{knitr::rmarkdown} 9 | \usepackage[utf8]{inputenc} 10 | --- 11 | 12 | ```{r setup, include=FALSE} 13 | knitr::opts_chunk$set(echo = TRUE) 14 | ``` 15 | 16 | # Fitting time series models 17 | 18 | ## Installing packages 19 | 20 | ```{r load, warning=FALSE, message=FALSE, results='hide'} 21 | library(rstan) 22 | library(atsar) 23 | # for optimizing stan on your machine, 24 | #rstan_options(auto_write = TRUE) 25 | #options(mc.cores = parallel::detectCores()) 26 | mcmc_list = list(n_mcmc = 1000, n_burn = 500, n_chain = 1, n_thin = 1) 27 | ``` 28 | 29 | ## Data 30 | 31 | For data for this lab, we'll include a dataset on airquality in New York. We'll load the data and create a couple new variables for future use. For the majority of our models, we're going to treat 'Wind' as the response variable for our time series models. 32 | 33 | ```{r} 34 | data(airquality) 35 | Wind = airquality$Wind # wind speed 36 | Temp = airquality$Temp # air temperature 37 | ``` 38 | 39 | ## 1. Linear regression 40 | 41 | \subsection*{1. Linear regression} 42 | We'll start with the simplest time series model possible: linear regression with only an intercept, so that the predicted values of all observations are the same. There are several ways we can write this equation. First, the predicted values can be written as $E[{Y}_{t}] = u$. Assuming that the residuals are normally distributed, the model linking our predictions to observed data is written as 43 | $$Y = u + e_{t}, e_{t} \sim Normal(0,\sigma)$$ 44 | 45 | An equivalent way to think about this model is that instead of the residuals as normally distributed with mean zero, we can think of the data $Y$ as being normally distributed with a mean of the intercept, and the same residual standard deviation: 46 | $$Y \sim Normal(E[Y_{t}],\sigma)$$ 47 | Remember that in linear regression models, the residual error is interpreted as independent and identically distributed observation error. 48 | 49 | To run this model using our package, we'll need to specify the response and predictor variables. The covariate matrix with an intercept only is a matrix of 1s. To double check, you could always look at 50 | 51 | ```{r} 52 | x = model.matrix(lm(Temp~1)) 53 | ``` 54 | 55 | Fitting the model using our function is done with this code, 56 | 57 | ```{r, warning=FALSE, message=FALSE, results='hide'} 58 | x = model.matrix(lm(Nile~1)) 59 | lm_intercept = fit_stan(y = as.numeric(Nile), x = rep(1, length(Nile)), 60 | model_name = "regression",mcmc_list=mcmc_list) 61 | ``` 62 | 63 | Coarse summaries of *stanfit* objects can be examined by typing one of the following 64 | 65 | ```{r, eval=FALSE} 66 | lm_intercept 67 | summary(lm_intercept) 68 | ``` 69 | 70 | But to get more detailed output for each parameter, you have to use the *extract()* function, 71 | ```{r} 72 | pars = extract(lm_intercept) 73 | names(pars) 74 | ``` 75 | 76 | **On your own, try to re-fit a regression model that includes the intercept and a slope, modeling the effect of Wind. What's the mean wind effect you estimate?** 77 | 78 | We can then make basic plots or summaries of each of these parameters, 79 | 80 | ```{r} 81 | hist(pars$beta, 40, col="grey", xlab="Intercept", main="") 82 | quantile(pars$beta, c(0.025,0.5,0.975)) 83 | ``` 84 | 85 | One of the other useful things we can do is look at the predicted values of our model and overlay the data. The predicted values are *pars$pred*. 86 | 87 | ```{r} 88 | plot(apply(pars$pred, 2, mean), main="Predicted values", lwd=2, 89 | ylab="Wind", ylim= c(min(pars$pred), max(pars$pred)), type="l") 90 | lines(apply(pars$pred, 2, quantile,0.025)) 91 | lines(apply(pars$pred, 2, quantile,0.975)) 92 | points(Wind, col="red") 93 | ``` 94 | 95 | ### Burn-in and thinning 96 | 97 | To illustrate the effects of the burn-in / warmup period, and thinning, we'll have you re-run the above model, but for just 1 MCMC chain (the default is 3). 98 | 99 | **Please make a plot of the time series of beta. Based on visual inspection, when does the chain converge? Second, calculate the ACF using acf() - would thinning more be appropriate?** 100 | 101 | ```{r eval = FALSE} 102 | lm_intercept = fit_stan(y = Temp, x = rep(1, length(Temp)), 103 | model_name = "regression", 104 | mcmc_list = list(n_mcmc = 1000, n_burn = 1, n_chain = 1, n_thin = 1)) 105 | ``` 106 | 107 | ## 2. Linear regression with correlated errors 108 | 109 | In our first model, the errors were independent in time. We're going to modify this to model autocorrelated errors. Autocorrelated errors are widely used in ecology and other fields -- for a greater discussion, see Morris and Doak (2002) Quantitative Conservation Biology. To make the deviations autocorrelated, we start by defining the deviation in the first time step, ${e}_{1} = {Y}_{1} - {u}$. The expectation of ${Y_t}$ in each time step is then written as 110 | $$E[{Y_t}] = u + \phi * e_{t-1}$$ 111 | 112 | In addition to affecting the expectation, the correlation parameter $\phi$ also affects the variance of the errors, so that 113 | $${ \sigma }^{ 2 }={ \psi }^{ 2 }\left( 1-{ \phi }^{ 2 } \right)$$ 114 | Like in our first model, we assume that the data follows a normal likelihood (or equivalently that the residuals are normally distributed), ${Y_t} = E[{Y_t}] + {e}_{t}$, or ${Y_t} \sim Normal(E[{Y_t}], \sigma)$. Thus, it is possible to express the subsequent deviations as ${e}_{t} = {Y}_{t} - E[{Y_t}]$, or equivalently as ${e}_{t} = {Y}_{t} - {u} -\phi * {e}_{t-1}$. 115 | 116 | We can fit this regression with autocorrelated errors by changing the model name to 'regression_cor' 117 | 118 | ```{r eval = FALSE} 119 | lm_intercept_cor = fit_stan(y = Temp, x = rep(1, length(Temp)), 120 | model_name = "regression_cor", 121 | mcmc_list = list(n_mcmc = 1000, n_burn = 1, n_chain = 1, n_thin = 1)) 122 | ``` 123 | 124 | ## 3. Random walk model 125 | 126 | All of the previous three models can be interpreted as observation error models. Switching gears, we can alternatively model error in the state of nature, creating process error models. A simple process error model that many of you may have seen before is the random walk model. In this model, the assumption is that the true state of nature (or latent states) are measured perfectly. Thus, all uncertainty is originating from process variation (for ecological problems, this is often interpreted as environmental variation). For this simple model, we'll assume that our process of interest (in this case, daily wind speed) exhibits no daily trend, but behaves as a random walk. 127 | 128 | $$E[{Y_t}] = Y_{t-1} + e_{t-1}$$ 129 | 130 | And the ${e}_{t} \sim Normal(0, \sigma)$. Remember back to the autocorrelated model (or MA(1) models) that we assumed that the errors $e_t$ followed a random walk. In contrast, the AR(1) model assumes that the errors are independent, but that the state of nature follows a random walk. Note also that this model as written doesn't include a drift term (this can be turned on / off using the *est_drift* argument). 131 | 132 | **Please fit the random walk model to the temperature data. Our function can do this by using model_name = 'rw'. Once you've fitted the model, plot the predicted values and 95% CIs, as we did above in the regression model.** 133 | 134 | ```{r, eval = FALSE} 135 | rw = fit_stan(y = Temp, est_drift = FALSE, model_name = "rw",mcmc_list=mcmc_list) 136 | ``` 137 | 138 | ## 4. Autoregressive models 139 | A variation of the random walk model described previously is the autoregressive time series model of order 1, AR(P=1). This model is essentially the same as the random walk model but it introduces an estimated coefficient, which we'll call $\phi$. The parameter $\phi$ controlls the degree to which the random walk reverts to the mean -- when $\phi$ = 1, the model is identical to the random walk, but at smaller values, the model will revert back to the mean (which in this case is zero). Also, $\phi$ can take on negative values, which we'll discuss more in future lectures. The math to describe the AR(P=1) time series model is: $$E[{Y_t}] = \phi * Y_{t-1} + e_{t-1}$$. 140 | 141 | **Our function can fit higher order AR models, but for now we just want you to fit an AR model and make a histogram of phi. ** 142 | 143 | ```{r eval = FALSE} 144 | ar1 = fit_stan(y = Temp, x = matrix(1, nrow = length(Temp), ncol = 1), 145 | model_name = "ar", est_drift=FALSE, P = 1,mcmc_list=mcmc_list) 146 | ``` 147 | 148 | **To see the effect of this increased flexibility in estimating the autocorrelation, make a plot of the predictions from the AR(P=1) model and the RW model** 149 | 150 | ## 5. State-space models 151 | 152 | At this point, we've fit models with observation or process error, but we haven't tried to estimate both simultaneously. We will do so here, and introduce some new notation to describe the process model and observation model. We use the notation ${x_t}$ to denote the latent state or state of nature (which is unobserved) at time $t$ and ${y_t}$ to denote the observed data. For introductory purposes, we'll make the process model autoregressive (similar to our AR(1) model), 153 | 154 | $$x_{t} = \phi * x_{t-1} + e_{t-1}; e_{t-1} \sim Normal(0,q)$$ 155 | 156 | For the process model, there are a number of ways to parameterize the first 'state', and we'll talk about this more in the class, but for the sake of this model, we'll place a vague weakly informative prior on $x_1$, $x_1 \sim Normal(0, 0.01)$.Second, we need to construct an observation model linking the estimate unseen states of nature $x_t$ to the data $Y_t$. For simplicitly, we'll assume that the observation errors are indepdendent and identically distributed, with no observation component. Mathematically, this model is 157 | $$Y_t \sim Normal(x_t, r)$$ 158 | In the two above models, we'll refer to $q$ as the standard deviation of the process variance and $r$ as the standard deviation of the observation error variance 159 | 160 | **For this model, fit the above model with and without the autoregressive parameter $\phi$ and compare the estimated process and observation error variances. Code examples are given below** 161 | 162 | ```{r eval = FALSE} 163 | ss_ar = fit_stan(y = Temp, est_drift=FALSE, model_name = "ss_ar",mcmc_list=mcmc_list) 164 | ss_rw = fit_stan(y = Temp, est_drift=FALSE, model_name = "ss_rw",mcmc_list=mcmc_list) 165 | ``` 166 | --------------------------------------------------------------------------------