diff --git a/R/checks.R b/R/checks.R index 446e3a0..83bc27f 100644 --- a/R/checks.R +++ b/R/checks.R @@ -308,14 +308,16 @@ check_regions <- function(regions, stratify_by, stratify_type, msg <- "Stratification does not match desired regions:\n" if(stratify_by %in% c("bcr", "latlong") & - any(regions %in% c("country", "prov_state"))) { + any(regions %in% c("country", "prov_state")) + & stratify_type != "custom" & is.null(regions_index)) { stop(msg, "BCRs and lat-long degree block stratifications cannot be divided ", "into regions with political boundaries ('country', 'prov_state').", call. = FALSE) } - if(stratify_by == "prov_state" & "bcr" %in% regions){ + if(stratify_by == "prov_state" & "bcr" %in% regions + & stratify_type != "custom" & is.null(regions_index)){ stop(msg, "The States and Provinces stratification", "cannot be divided into BCR regions.", diff --git a/R/generate-trends.R b/R/generate-trends.R index e8cb345..d14805d 100644 --- a/R/generate-trends.R +++ b/R/generate-trends.R @@ -139,13 +139,14 @@ generate_trends <- function(indices, max_year = NULL, quantiles = c(0.025, 0.05, 0.25, 0.75, 0.95, 0.975), slope = FALSE, + gam = FALSE, prob_decrease = NULL, prob_increase = NULL, hpdi = FALSE) { # Checks check_data(indices) - check_logical(slope, hpdi) + check_logical(slope, hpdi, gam) check_numeric(quantiles) check_numeric(min_year, max_year, quantiles, prob_decrease, prob_increase, allow_null = TRUE) @@ -263,6 +264,26 @@ generate_trends <- function(indices, .data[[paste0("slope_trend_q_", q1)]]) } + + # Optional gam based trends + if(gam) { + trends <- trends %>% + dplyr::mutate( + sl_t = purrr::map(.data$n, calc_gam, + .env$min_year_num, .env$max_year_num), + gam_trend = purrr::map_dbl(.data$sl_t, stats::median), + gam_trend_q = purrr::map_df( + .data$sl_t, ~stats::setNames( + calc_quantiles(.x, quantiles, names = FALSE), + paste0("gam_trend_q_", quantiles)))) %>% + tidyr::unnest("gam_trend_q") %>% + dplyr::mutate( + "width_of_{q}_percent_credible_interval_gam" := + .data[[paste0("gam_trend_q_", q2)]] - + .data[[paste0("gam_trend_q_", q1)]]) + } + + # Model conditional probabilities of population change during trends period if(!is.null(prob_decrease)) { trends <- trends %>% @@ -292,6 +313,7 @@ generate_trends <- function(indices, dplyr::starts_with("trend"), dplyr::starts_with("percent_change"), dplyr::starts_with("slope"), + dplyr::starts_with("gam"), dplyr::starts_with("width"), dplyr::starts_with("prob"), "rel_abundance", "obs_rel_abundance", @@ -325,6 +347,25 @@ calc_slope <- function(n, min_year_num, max_year_num) { as.vector((exp(m) - 1) * 100) } +gam_sl <- function(i, wy) { + df <- data.frame(i = i, + y = 1:length(i)) + sm <- mgcv::gam(data = df, + formula = i~s(y)) + smf <- sm$fitted.values[wy] + ny <- wy[2]-wy[1] + smt <- (smf[2]-smf[1])*(1/ny) +} + +calc_gam <- function(n, min_year_num, max_year_num) { + wy <- c(min_year_num,max_year_num) + + ne <- log(n) + m <- t(apply(ne, 1, FUN = gam_sl, wy)) + + as.vector((exp(m) - 1) * 100) +} + calc_prob_crease <- function(x, p, type = "decrease") { if(type == "decrease") f <- function(p) length(x[x < (-1 * p)]) / length(x) if(type == "increase") f <- function(p) length(x[x > p]) / length(x) diff --git a/R/prepare-data.R b/R/prepare-data.R index e20e5b4..4aa535b 100644 --- a/R/prepare-data.R +++ b/R/prepare-data.R @@ -56,7 +56,7 @@ prepare_data <- function(strata_data, check_numeric(min_n_routes, min_max_route_years, min_mean_route_years) check_logical(quiet) #warning if stratification == latlong and min_n_routes > 1 - if(strata_data$meta_data$stratify_by == "latlong" & min_n_routes == 3){ + if(strata_data$meta_data$stratify_by == "latlong" & min_n_routes > 1){ warning("Many strata with data may have been excluded ", "With latlong stratification, most strata have ", "only 1 route. You may wish to set min_n_routes = 1", @@ -71,7 +71,7 @@ prepare_data <- function(strata_data, # Add in routes obs <- strata_data$routes_strata %>% dplyr::select("country_num", "state_num", "state", "rpid", "bcr", "year", - "strata_name", "route", "obs_n") %>% + "strata_name", "route", "obs_n","latitude","longitude") %>% dplyr::left_join(obs, by = c("route", "rpid", "year")) %>% dplyr::mutate(count = tidyr::replace_na(.data$count, 0)) diff --git a/R/run-model.R b/R/run-model.R index 532819f..8733d06 100644 --- a/R/run-model.R +++ b/R/run-model.R @@ -104,9 +104,17 @@ run_model <- function(model_data, meta_data <- model_data[["meta_data"]] raw_data <- model_data[["raw_data"]] meta_strata <- model_data[["meta_strata"]] + init_values <- model_data[["init_values"]] folds <- model_data[["folds"]] model_data <- model_data[["model_data"]] + + if(model_data$n_strata < 2){ + stop("The data have only 1 stratum. bbsBayes2 models require multiple strata. + If there are sufficient routes with data, you can try an alternate stratification + (e.g., latlong) where the routes may be redistributed among > 1 strata.") + } + species <- stringr::str_remove_all(meta_data[["species"]], "[^[[:alpha:]]]") diff --git a/data-raw/data_exported.R b/data-raw/data_exported.R index a1df371..ad364a0 100644 --- a/data-raw/data_exported.R +++ b/data-raw/data_exported.R @@ -16,7 +16,7 @@ usethis::use_data(species_forms, overwrite = TRUE) species_notes <- readr::read_csv("data-raw/species_notes.csv", - col_types = "ncc", locale = readr::locale(encoding = "latin1"), + col_types = "ccnnc", locale = readr::locale(encoding = "latin1"), progress = FALSE) %>% as.data.frame() diff --git a/data-raw/example_model_fits.R b/data-raw/example_model_fits.R new file mode 100644 index 0000000..be4e1cc --- /dev/null +++ b/data-raw/example_model_fits.R @@ -0,0 +1,75 @@ + +library(bbsBayes2) +library(tidyverse) + +species <- "Scissor-tailed Flycatcher" +species <- "Arctic Warbler" + +# extract the unique numerical identifier for this species in the BBS database +species_number <- search_species(species) %>% + select(aou) %>% + unlist() + +s <- stratify("bbs_usgs", + species = species) %>% + prepare_data() + +for(j in 1:nrow(bbs_models)){ + + mod <- as.character(bbs_models[j,"model"]) + var <- as.character(bbs_models[j,"variant"]) + + if(var == "spatial"){ + p <- prepare_spatial(s, strata_map = load_map("bbs_usgs")) %>% + prepare_model(model = mod, model_variant = var) + }else{ + p <- prepare_model(s,model = mod, + model_variant = var) +} + + m <- paste0("output/", + species_number, + "_", + mod, + "_", + var) + m2 <- run_model(p, + output_basename = m, + output_dir = "vignettes/articles") + +} + + +# latlong fits ------------------------------------------------------------ + + + +s <- stratify("latlong", + species = species) %>% + prepare_data(min_n_routes = 1) + +for(j in 3){ + + mod <- as.character(bbs_models[j,"model"]) + var <- as.character(bbs_models[j,"variant"]) + + if(var == "spatial"){ + p <- prepare_spatial(s, strata_map = load_map("latlong")) %>% + prepare_model(model = mod, model_variant = var) + }else{ + p <- prepare_model(s,model = mod, + model_variant = var) + } + + m <- paste0("output/", + species_number, + "_latlong_", + mod, + "_", + var) + m2 <- run_model(p, + output_basename = m, + output_dir = "vignettes/articles") + +} + diff --git a/data-raw/flow_diagram.R b/data-raw/flow_diagram.R new file mode 100644 index 0000000..c1adb68 --- /dev/null +++ b/data-raw/flow_diagram.R @@ -0,0 +1,79 @@ +library(DiagrammeR) +gri <- grViz("digraph functions { + + # a 'graph' statement + graph [overlap = true, fontsize = 10 compound = true, ranksep = 0.5] + + # several 'node' statements + node [shape = rectangle, fontname = 'Courier New', + fixedsize = false, style=filled, fillcolor=white] + + fetch [label = 'fetch_bbs_data()', fillcolor=lightblue] + remove [label = 'remove_cache()', fillcolor=orange] + loadbbs [label = 'load_bbs_data()', fillcolor=lightblue] + + search [label = 'search_species()', fillcolor=orange] + strat [label = 'stratify()', fillcolor=lightpink] + prepdata [label = 'prepare_data()', fillcolor=lightpink] + prepspatial [label = 'prepare_spatial()', fillcolor=lightpink] + prepmodel [label = 'prepare_model()', fillcolor=darkolivegreen3] + loadmap [label = 'load_map()', fillcolor=orange] + assign_ps [label = 'assign_prov_state()', fillcolor=orange] + + runmodel [label = 'run_model()', fillcolor=darkolivegreen3] + modelfile [label = 'copy_model_file()', fillcolor=darkolivegreen3] + + conv[label = 'save_model_run()\nget_convergence()\nget_model_vars()\nget_summary()', fillcolor=darkolivegreen3] + + genind [label = 'generate_indices()', fillcolor=thistle] + gentre [label = 'generate_trends()', fillcolor=thistle] + geo [label = 'plot_geofacet()', fillcolor=thistle] + plotind [label = 'plot_indices()', fillcolor=thistle] + genmap [label = 'plot_map()', fillcolor=thistle] + + + # several 'edge' statements + edge [] + fetch->remove [style=dashed] + fetch->loadbbs [style=dashed] + fetch->strat [style=dashed] + + runmodel->remove [style=dashed] + + modelfile->prepmodel [style=dashed] + + search->strat [style=dashed] + strat->prepdata + prepdata->prepspatial + prepdata->prepmodel [color=grey50] + prepspatial->prepmodel [color=grey50] + prepmodel->runmodel + + + runmodel->conv + runmodel->genind + genind->gentre + + loadmap->assign_ps [style=dashed] + loadmap->genind [style=dashed] + loadmap->prepspatial [style=dashed] + loadmap->strat [style=dashed] + + genind->plotind + genind->geo + gentre->geo [color=grey50] + gentre->genmap + + # Invisible edges for arranging + prepspatial->conv [style=invis] +}") + + +export_graph(file_name = "flow_diagram.png", + graph = gri, + file_type = "png", + width = 1200,height = 1400) +print(gri) +dev.off() + + diff --git a/data-raw/species_notes.csv b/data-raw/species_notes.csv index 3f659e1..38e7a6a 100644 --- a/data-raw/species_notes.csv +++ b/data-raw/species_notes.csv @@ -1,7 +1,7 @@ -aou,minimum_year,warning -4661,1978,Alder and Willow Flycatcher were considered a single species until 1973. It is likely that they are not accurately separated by BBS observers until at least some years after that split. -4660,1978,Alder and Willow Flycatcher were considered a single species until 1973. It is likely that they are not accurately separated by BBS observers until at least some years after that split. -10,1990,Clark's and Western Grebe were considered a single species until 1985. It is likely that they are not accurately separated by BBS observers until at least some years after that split. -10,1990,Clark's and Western Grebe were considered a single species until 1985. It is likely that they are not accurately separated by BBS observers until at least some years after that split. -22860,1990,Eurasian Collared Dove was introduced into North America in the 1980s. 1990 is the first year that the species was observed on at least 3 BBS routes. -6121,1985,Cave Swallows were relatively rare in the areas surveyed by BBS before 1980. There are only two observations during BBS before 1980. +english,french,aou,minimum_year,warning +Alder Flycatcher,Moucherolle des aulnes,4661,1978,Alder and Willow Flycatcher were considered a single species until 1973. It is likely that they are not accurately separated by BBS observers until at least some years after that split. +Willow Flycatcher,Moucherolle des saules,4660,1978,Alder and Willow Flycatcher were considered a single species until 1973. It is likely that they are not accurately separated by BBS observers until at least some years after that split. +Clark's Grebe,Grèbe à face blanche,11,1990,Clark's and Western Grebe were considered a single species until 1985. It is likely that they are not accurately separated by BBS observers until at least some years after that split. +Western Grebe,Grèbe élégant,10,1990,Clark's and Western Grebe were considered a single species until 1985. It is likely that they are not accurately separated by BBS observers until at least some years after that split. +Eurasian Collared-Dove,Tourterelle turque,22860,1990,Eurasian Collared Dove was introduced into North America in the 1980s. 1990 is the first year that the species was observed on at least 3 BBS routes. +Cave Swallow,Hirondelle à front brun,6121,1985,Cave Swallows were relatively rare in the areas surveyed by BBS before 1980. There are only two observations during BBS before 1980. diff --git a/data/species_notes.rda b/data/species_notes.rda index 9e5a0bb..42c9c25 100644 Binary files a/data/species_notes.rda and b/data/species_notes.rda differ diff --git a/vignettes/articles/bbsBayes2.Rmd.orig b/vignettes/articles/bbsBayes2.Rmd.orig index 645592e..d339d57 100644 --- a/vignettes/articles/bbsBayes2.Rmd.orig +++ b/vignettes/articles/bbsBayes2.Rmd.orig @@ -88,10 +88,10 @@ Now we should be able to use cmdstanr to install cmdstan cmdstanr::install_cmdstan() ``` -Let's check that everything went as planned +Let's check that everything went as planned, and tell cmdstanr to fix any issues. ```{r, eval = TRUE} -cmdstanr::check_cmdstan_toolchain() +cmdstanr::check_cmdstan_toolchain(fix = TRUE) ``` > Problems? Check out cmdstanr's vignette on [Getting @@ -130,15 +130,15 @@ This will save the data to a package-specific directory on your computer. You mu > section). -There are (as of August 2023) two types of BBS data that can be -downloaded, and three release-versions: +There are two types of BBS data that can be +downloaded, and annual release-versions: - Two levels `state` and `stop` (only `state` works with bbsBayes2 models, the `stop` option is provided to facilitate custom projects and models) -- Two releases `2020`, `2022` and `2023` (more options will be added as annual releases occur). +- Annual releases `2020`, `2022`, `2023`, and '2024' more options will be added as annual releases occur). -The defaults (level `state` and the most recent release - `2023`) is almost certainly what you are looking for, Unless you have a specific reason to need a different version. The most recent release will include all of the data included in earlier releases. -However you can download all data sets and specify which one you wish to +The defaults (level `state` and the most recent release - `2024`) is almost certainly what you are looking for, Unless you have a specific reason to need a different version. The most recent release will include all of the data included in earlier releases. +However you can download all releases and specify which one you wish to use in the `stratify()` step. ### A note about BBS release names: @@ -311,7 +311,7 @@ search_species("Corvidae") ##### Species groupings There are some taxonomic groupings of species-units in the BBS database -that bbsBayes2 by default also combines into combined species forms. These +that bbsBayes2 by default also groups into combined species forms. These represent groupings that make sense based on changes in taxonomy or potentially inconsistent distinctions among observers, routes, regions, or time. @@ -321,11 +321,17 @@ potentially inconsistent distinctions among observers, routes, regions, or time. Flicker observations exist in the BBS database separately as Red-shafted Flicker (4130), Yellow-shafted Flicker (4120), unidentified Red/Yellow-shafted Flicker (4123) or hybrid Red x Yellow-shafted Flicker (4125). To provide an appropriate dataset to represent population trends of Northern Flicker, bbsBayes2 by default sums all of these observations into a new *species* called Northern Flicker (all forms), which replaces the (4123) unidentified category in the species database. The remaining original separate forms (Red, Yellow, and hybrid) are retained. - Similar combined *species* are created for taxonomic splits that have occurred since the start of the BBS, such as Clark's and Western Grebe, which are retained as their own separate species, but are also combined into Western Grebe (Clark's/Western) (12). - You can access a complete list of these combined *species* groups and the sub groups that make them up. ```{r} -species_forms +bbsBayes2::species_forms +``` + +- These splits that have occurred since the start of the BBS require some extra +care when considering what years to include in any model fit. For example, if fitting a trend model to the data for Clark's Grebe, it would not make sense to include all years back to 1966. Prior to 1985, Clark's Grebe was not a distinct species and so observers would not have recorded observations for this *species* in the same was as they would have after 1985. The `prepare_data()` function will generate warnings if the user selects a species and time-period where these species identification-issues may be important. Related concerns with time-span may apply to species that have expanded their range into the surveyed area of the BBS since the beginning of surveys. A list of the species where these time-span concerns may be most relevant can be found by calling the built-in data table. + +```{r} +bbsBayes2::species_notes ``` If you're looking for a complete list of all species in the BBS database. @@ -401,7 +407,7 @@ m <- run_model(mod) # Optionally, save the model output as an .rds file saveRDS(m, "output/4430_gamye_spatial.rds") ``` -The spatial aspects of the spatial model variants use an intrinsic Conditional Autoregressive structure (iCAR) to share information among neighbouring strata on the population abundance and trend parameter ([Besag et al. 1991](https://doi.org/10.1007/BF00116466), [ver Hoef et al. 2018](http://doi.wiley.com/10.1002/ecm.1283), [Morris et al. 2019](https://doi.org/10.1016/j.sste.2019.100301)). For more information about the bbsBayes2 models and the spatial models see the [models vignette](./models.html) and [Smith et al., 2023 pre-print](https://doi.org/10.32942/X2088D). +The spatial aspects of the spatial model variants use an intrinsic Conditional Autoregressive structure (iCAR) to share information among neighbouring strata on the population abundance and trend parameter ([Besag et al. 1991](https://doi.org/10.1007/BF00116466), [ver Hoef et al. 2018](http://doi.wiley.com/10.1002/ecm.1283), [Morris et al. 2019](https://doi.org/10.1016/j.sste.2019.100301)). For more information about the bbsBayes2 models and the spatial models see the [models vignette](./models.html) and [Smith et al., 2024](https://doi.org/10.1093/ornithapp/duad056). The prepared spatial data object includes a map of the spatial neighbourhood relationships for a given species and stratification. @@ -558,6 +564,18 @@ p1_mod <- p[["continent"]]+ print(p1_mod) ``` +#### Spaghetti plots to show uncertainty in population trajectories + +The most common inference to draw from one of these BBS models relates to the estimates of the population trajectory. One particularly useful way to visualise the uncertainty of those population trajectories is to plot many posterior draws of the full trajectory. The default population trajectories plots `plot_indices()` show a line representing the path of the annual posterior medians of the annual indices and an uncertainty band spanning the outer limits of a credible interval on the annual indices. These are reasonable summaries of the uncertainty in the collection of annual indices. However, the uncertainty of each annual index of abundance includes information about the uncertainty in the estimate of the change in abundance through time (e.g., trend) and uncertainty in the estimate of the mean abundance (e.g., the mean count in any given route or observer). Those two sources of uncertainty can be correlated in the posterior distribution, so that the uncertainty of the annual indices may over-estimate the uncertainty in the trend. +To plot a sample of estimated trajectories, set the `spaghetti = TRUE` argument in the `plot_indices()` function. +```{r} +# generates a list of ggplot graphs, one for each region +p <- plot_indices(indices = i, + add_observed_means = TRUE) +print(p[["continent"]]) +``` +There are arguments that also allow the user to control the transparency of each plotted line, as well as the number of lines to plot (the default is to draw 100 random samples). + ### Trends - predictions of mean rates of change over time Next we can calculate the long-term trends based on these indices. Note diff --git a/vignettes/articles/models.Rmd.orig b/vignettes/articles/models.Rmd.orig index b01e961..5cf0802 100644 --- a/vignettes/articles/models.Rmd.orig +++ b/vignettes/articles/models.Rmd.orig @@ -39,14 +39,14 @@ The four models differ in the way they estimate the time-series components. ### 1. First Difference Models -A first-difference model considers the time-series as a random-walk forward and backwards in time from the mid-year of the time-series, so that the first-differences of the sequence of year-effects are random effects with mean = 0 and an estimated variance. The non-hierarchical variant of this model model has been described in [Link et al., 2017](https://doi.org/10.1650/CONDOR-17-1.1) the hierarchical and spatial variants are described in [Smith et al., 2023 pre-print](https://doi.org/10.32942/X2088D). +A first-difference model considers the time-series as a random-walk forward and backwards in time from the mid-year of the time-series, so that the first-differences of the sequence of year-effects are random effects with mean = 0 and an estimated variance. The non-hierarchical variant of this model model has been described in [Link et al., 2017](https://doi.org/10.1650/CONDOR-17-1.1) the hierarchical and spatial variants are described in [Smith et al., 2024](https://doi.org/10.1093/ornithapp/duad056). ### 2. Generalized Additive Models -The GAM models the time series as a semiparametric smooth using a Generalized Additive Model (GAM) structure. This model is unique among the bbsBayes2 models in that it does not model annual fluctuations, only smoothed changes in population size through time. As a result, it makes some very strong assumptions about population change. See [Smith & Edwards, 2021](https://doi.org/10.1093/ornithapp/duaa065) for the original formulation. The updated hierarchical and spatial variants of this model are described in this [Smith et al., 2023 pre-print](https://doi.org/10.32942/X2088D). +The GAM models the time series as a semiparametric smooth using a Generalized Additive Model (GAM) structure. This model is unique among the bbsBayes2 models in that it does not model annual fluctuations, only smoothed changes in population size through time. As a result, it makes some very strong assumptions about population change. See [Smith & Edwards, 2021](https://doi.org/10.1093/ornithapp/duaa065) for the original formulation. The updated hierarchical and spatial variants of this model are described in this [Smith et al., 2024](https://doi.org/10.1093/ornithapp/duad056). ### 3. Generalized Additive Models with Year Effect -The GAMYE includes the semiparametric smooth used in the gam option, but also includes random year-effect terms that track annual fluctuations around the smooth. This is the model that the Canadian Wildlife Service is now using for the annual status and trend estimates. See this [Smith et al., 2023 pre-print](https://doi.org/10.32942/X2088D) for details on the Stan version of this model and see [Smith & Edwards, 2021](https://doi.org/10.1093/ornithapp/duaa065) for the original formulation. +The GAMYE includes the semiparametric smooth used in the gam option, but also includes random year-effect terms that track annual fluctuations around the smooth. This is the model that the Canadian Wildlife Service is now using for the annual status and trend estimates. See this [Smith et al., 2024](https://doi.org/10.1093/ornithapp/duad056) for details on the Stan version of this model and see [Smith & Edwards, 2021](https://doi.org/10.1093/ornithapp/duaa065) for the original formulation. ### 4. Slope The slope model estimates the time series as a log-linear regression with random year-effect terms that allow the trajectory to depart from the smooth log-linear regression line. It is the model used by the USGS and CWS to estimate BBS trends between 2011 and 2018. The basic model was first described in 2002 [Link and Sauer 2002](https://doi.org/10.1890/0012-9658(2002)083[2832:AHAOPC]2.0.CO;2) and its application to the annual status and trend estimates is documented in [Sauer and Link, 2011](https://doi.org/10.1525/auk.2010.09220) and [Smith et al., 2014](https://doi.org/10.22621/cfn.v128i2.1565). @@ -66,17 +66,63 @@ The non-hierarchical variant of the first-difference model `model = "first_diff" ## More background reading -The models in bbsBayes2 are best described and contrasted here [Smith et al., 2023 pre-print](https://doi.org/10.32942/X2088D). +The models in bbsBayes2 are best described and contrasted here [Smith et al., 2024](https://doi.org/10.1093/ornithapp/duad056). The models and variants differ in the way they estimate the parameters that are most important for understanding the status and trends of bird populations. That is, they vary in the way they estimate the relative abundance and the temporal-changes in relative abundance (population trends), within and among strata. -Otherwise, they are identical in that they all share the same set of parameters designed to adjust estimates for variations among observers, routes, and first-year observer start-up effects. For more details on the development of these Bayesian hierarchical models for the BBS and the observer-effects, see [Link and Sauer 2002](https://doi.org/10.1890/0012-9658(2002)083[2832:AHAOPC]2.0.CO;2), [Sauer and Link, 2011](https://doi.org/10.1525/auk.2010.09220), [Smith et al., 2014](https://doi.org/10.22621/cfn.v128i2.1565), [Link et al., 2017](https://doi.org/10.1650/CONDOR-17-1.1), [Link et al. 2020](https://doi.org/10.1002/eap.2137), [Smith & Edwards, 2021](https://doi.org/10.1093/ornithapp/duaa065). +Otherwise, they are identical in that they all share the same set of parameters and priors designed to adjust estimates for variations among observers, routes, and first-year observer start-up effects. For more details on the development of these Bayesian hierarchical models for the BBS and the observer-effects, see [Link and Sauer 2002](https://doi.org/10.1890/0012-9658(2002)083[2832:AHAOPC]2.0.CO;2), [Sauer and Link, 2011](https://doi.org/10.1525/auk.2010.09220), [Smith et al., 2014](https://doi.org/10.22621/cfn.v128i2.1565), [Link et al., 2017](https://doi.org/10.1650/CONDOR-17-1.1), [Link et al. 2020](https://doi.org/10.1002/eap.2137), [Smith & Edwards, 2021](https://doi.org/10.1093/ornithapp/duaa065). ## One species, nine-models Here is an example application of all nine models and variants applied to the same data set. In this example, we've used data for the Scissor-tailed Flycatcher. You can download the fitted model results for all nine models in a zipped file [here](https://drive.google.com/file/d/1zF8xOIn_ZuORmjNDHAu5YCJjIx4j-MHC/view?usp=sharing). Unzip the file and save the *.rds* files in a sub-directory of your working directory called *output* to replicate our code below. -The following code chunk loads each of the fitted model objects, calculates the annual indices and trends, then saves the continent population trajectories and the long-term (1966-2021) trend maps. +The following code chunk loads each of the fitted model objects, calculates the annual indices and trends, then saves the continent population trajectories and the long-term (1966-2023) trend maps. + +This code was used to generate these fitted model results. + + +```{r, eval=FALSE} +library(bbsBayes2) +library(tidyverse) + +species <- "Scissor-tailed Flycatcher" + +# extract the unique numerical identifier for this species in the BBS database +species_number <- search_species(species) %>% + select(aou) %>% + unlist() + +s <- stratify("bbs_usgs", + species = species) %>% + prepare_data() + +for(j in 1:nrow(bbs_models)){ + + mod <- as.character(bbs_models[j,"model"]) + var <- as.character(bbs_models[j,"variant"]) + + if(var == "spatial"){ + p <- prepare_spatial(s, strata_map = load_map("bbs_usgs")) %>% + prepare_model(model = mod, model_variant = var) + }else{ + p <- prepare_model(s,model = mod, + model_variant = var) +} + + m <- paste0("output/", + species_number, + "_", + mod, + "_", + var) + m2 <- run_model(p, + output_basename = m, + output_dir = getwd()) + +} + + +``` ```{r, message=FALSE} saved_trajectories <- NULL diff --git a/vignettes/articles/stratification.Rmd.orig b/vignettes/articles/stratification.Rmd.orig index 8318469..0f0533b 100644 --- a/vignettes/articles/stratification.Rmd.orig +++ b/vignettes/articles/stratification.Rmd.orig @@ -93,7 +93,7 @@ z <- "output/WBPHS_Stratum_Boundaries_2019.zip" # download.file(url = "https://ecos.fws.gov/ServCat/DownloadFile/213149", destfile = z, - cacheOK = FALSE) + cacheOK = TRUE) unzip(z) # Unzip - if you get a file is corrupt message, download it manually unlink(z) # Remove the zipped file ```