From a911351f17cc946842f708b6b196e80b9a13f8f3 Mon Sep 17 00:00:00 2001 From: Schiano-NOAA <125507018+Schiano-NOAA@users.noreply.github.com> Date: Fri, 13 Nov 2026 22:10:01 +0000 Subject: [PATCH] style and docs: run devtools::document() and style with styler or air --- DESCRIPTION | 4 +- R/add_caption_alt_text.R | 24 +- R/conout_bam.R | 40 +-- R/conout_rceattle.R | 68 ++-- R/conout_ss3.R | 96 ++--- R/convert_output.R | 9 +- R/data.R | 12 +- R/extract_sis_data.R | 352 ++++++++++--------- R/plot_abundance_at_age.R | 10 +- R/plot_biomass.R | 27 +- R/plot_biomass_at_age.R | 16 +- R/plot_catch_at_age.R | 10 +- R/plot_discard.R | 10 +- R/plot_fishing_mortality.R | 12 +- R/plot_landings.R | 14 +- R/plot_natural_mortality.R | 8 +- R/plot_recruitment.R | 8 +- R/plot_recruitment_deviations.R | 4 +- R/plot_selectivity.R | 10 +- R/plot_spawning_biomass.R | 28 +- R/plot_spr.R | 38 +- R/plot_stock_recruitment.R | 12 +- R/save_all_plots.R | 101 +++--- R/table_biomass_abundance_catch.R | 24 +- R/table_index.R | 22 +- R/table_landings.R | 19 +- R/table_projections.R | 32 +- R/table_total_catch.R | 20 +- R/utils_plot.R | 47 ++- R/utils_rda.R | 25 +- data-raw/DATASET_RCEATTLE.R | 5 +- man/save_all_plots.Rd | 2 +- man/table_landings.Rd | 3 +- man/table_projections.Rd | 12 +- tests/testthat/helper-test_functions.R | 42 +-- tests/testthat/test-check_data.R | 12 +- tests/testthat/test-convert_output.R | 4 +- tests/testthat/test-export_rda.R | 84 ++--- tests/testthat/test-extract_sis_data.R | 40 ++- tests/testthat/test-plot_natural_mortality.R | 2 +- tests/testthat/test-plot_recruitment.R | 1 - tests/testthat/test-plot_spr.R | 4 +- tests/testthat/test-save_all_plots.R | 188 +++++----- tests/testthat/test-table_landings.R | 2 +- vignettes/extract-sis-data.Rmd | 2 +- 45 files changed, 770 insertions(+), 735 deletions(-) diff --git a/DESCRIPTION b/DESCRIPTION index ce341c63..b24a373e 100644 --- a/DESCRIPTION +++ b/DESCRIPTION @@ -61,10 +61,10 @@ Suggests: r4ss, rmarkdown, testthat (>= 3.0.0) -Remotes: - r4ss/r4ss VignetteBuilder: knitr +Remotes: + r4ss/r4ss Config/roxygen2/version: 8.1.1 Config/testthat/edition: 3 Config/testthat/parallel: true diff --git a/R/add_caption_alt_text.R b/R/add_caption_alt_text.R index 87def075..a2c1584d 100644 --- a/R/add_caption_alt_text.R +++ b/R/add_caption_alt_text.R @@ -4,25 +4,25 @@ #' caption, and alt_text for a figure or table not present in stockplotr. #' #' @inheritParams create_rda -#' -#' @param topic_label String. Figure/table label. For automated matching in +#' +#' @param topic_label String. Figure/table label. For automated matching in #' asar-based report, it must match the label in your plot's chunk options, MINUS -#' the "fig-" or "tab-". For example, the label "custom_table1" would match up +#' the "fig-" or "tab-". For example, the label "custom_table1" would match up #' properly with the "tbl-custom_table1" code chunk label. -#' +#' #' @param caption String. Figure/table caption. -#' +#' #' @param alt_text String. Figure alternative text. Unnecessary for text-based tables. -#' +#' #' Default: "" -#' +#' #' @param dir Path. Path to the existing captions_alt_text.csv file that will be #' updated with the new caption and alt text. #' #' Default: file.path(getwd(), "captions_alt_text.csv") #' #' @export -#' +#' #' @examples \dontrun{ #' add_caption_alt_text( #' topic_label = "my_topic", @@ -38,22 +38,22 @@ add_caption_alt_text <- function(topic_label, alt_text = "", dir = file.path(getwd(), "captions_alt_text.csv")) { captions_alt_text <- utils::read.csv(dir) - + if (fig_or_table == tolower("figure") & alt_text == "") { cli::cli_alert_warning("No alt text provided for figure {topic_label}.") cli::cli_alert_warning("Figure alt text is necessary to pass asar report accessibility checks.") cli::cli_alert_info("Learn how to write descriptive alt text with the asar 'Increasing Report Accessibility' vignette: {.url https://nmfs-ost.github.io/asar/articles/accessibility_guide.html#alternative-text}.") } - + new_row <- data.frame( label = topic_label, type = fig_or_table, caption = caption, alt_text = alt_text ) - + captions_alt_text <- rbind(captions_alt_text, new_row) - + utils::write.csv( captions_alt_text, file = dir, diff --git a/R/conout_bam.R b/R/conout_bam.R index 83215146..ed198d0d 100644 --- a/R/conout_bam.R +++ b/R/conout_bam.R @@ -1,5 +1,5 @@ #' Code to convert BAM output to standard framework. -#' +#' #' Does not change naming conventions. #' #' @inheritParams convert_output @@ -8,13 +8,13 @@ #' #' @returns Reshaped data frame. conout_bam <- function( - file, - out_new, - fleet_names = NULL + file, + out_new, + fleet_names = NULL ) { # Extract values from BAM output - model file after following ADMB2R dat <- dget(file) - + # Find fleet names if (is.null(fleet_names)) { # Extract names from indices @@ -24,13 +24,13 @@ conout_bam <- function( # Extract names from landings landings <- dat$t.series |> dplyr::select(dplyr::contains("L.") & dplyr::contains(".ob") | - dplyr::contains("D.") & dplyr::contains(".ob")) + dplyr::contains("D.") & dplyr::contains(".ob")) fleets_land <- stringr::str_extract(as.vector(colnames(landings)), "(?<=L\\.)\\w+(?=\\.ob)") fleets_disc <- stringr::str_extract(as.vector(colnames(landings)), "(?<=D\\.)\\w+(?=\\.ob)") # Extract names from lof F dev parm <- dat$parm.tvec |> dplyr::select(dplyr::contains("log.F.dev.") | - dplyr::contains("log.F.dev.") & dplyr::contains(".D")) + dplyr::contains("log.F.dev.") & dplyr::contains(".D")) # fleets_parm_D <- stringr::str_extract(as.vector(colnames(parm)), "(?<=log\\.F\\.dev\\.)\\w+(?=\\.D)") fleets_parm <- stringr::str_extract(as.vector(colnames(parm)), "(?<=log\\.F\\.dev\\.)\\w+") fleets <- unique(tolower(c(fleets_ind, fleets_land, fleets_disc, fleets_parm))) @@ -48,13 +48,13 @@ conout_bam <- function( cli::cli_alert_info("{fleet_names}") # Create list for morphed dfs to go into (for rbind later) out_list <- list() - + factors <- c("year", "fleet", "fleet_name", "age", "sex", "area", "seas", "season", "time", "era", "subseas", "subseason", "platoon", "platoo", "growth_pattern", "gp", "nsim", "age_a") errors <- c("StdDev", "sd", "se", "SE", "cv", "CV", "stddev") units <- c("mt", "lbs", "eggs") # argument for function when model == BAM # fleet_names <- c("cl", "cL","cp","mrip","ct", "hb", "HB", "comm","Mbft","CVID") - + ##### BAM loop ---- # Extract data from list fit to output df # Loop over all items to output each object/transform @@ -97,7 +97,7 @@ conout_bam <- function( df <- df |> dplyr::rename_with( ~ ifelse(max(as.numeric(df$year)) < 50, - c("age_a"), c("year") + c("age_a"), c("year") ), year ) @@ -127,7 +127,7 @@ conout_bam <- function( TRUE ~ names(extract[[1]][i]) ) # label_init = names(extract[[1]][i]), - + # label = dplyr::case_when( # is.na(fleet) ~ names(extract[[1]][i]), # TRUE ~ stringr::str_replace(tolower(label), paste(".", fleet_names, sep = "", collapse = "|"), "") @@ -505,7 +505,7 @@ conout_bam <- function( cli::cli_alert_warning(paste(names(extract), " not compatible.", sep = "")) } # close if statement } # close loop over objects listed in dat file - + # Place out_list into a single data frame # VIRG, INIT, TIME, FORE out_new <- Reduce(rbind, out_list) |> @@ -515,15 +515,15 @@ conout_bam <- function( label = tolower(label) ) # if (model == "bam") { - out_new <- dplyr::mutate( - out_new, - era = dplyr::case_when( - year < dat$parms$styr ~ "init", - year >= dat$parms$styr & year <= dat$parms$endyr ~ "time", - year > dat$parms$endyr ~ "fore", - TRUE ~ NA - ) + out_new <- dplyr::mutate( + out_new, + era = dplyr::case_when( + year < dat$parms$styr ~ "init", + year >= dat$parms$styr & year <= dat$parms$endyr ~ "time", + year > dat$parms$endyr ~ "fore", + TRUE ~ NA ) + ) # } return(out_new) } diff --git a/R/conout_rceattle.R b/R/conout_rceattle.R index 117fdae4..4289faa5 100644 --- a/R/conout_rceattle.R +++ b/R/conout_rceattle.R @@ -1,5 +1,5 @@ #' Code to convert Rceattle output to standard framework. -#' +#' #' Does not change naming conventions. #' #' @inheritParams convert_output @@ -8,9 +8,9 @@ #' #' @returns Reshaped data frame. conout_rceattle <- function( - file, - out_new, - fleet_names = NULL + file, + out_new, + fleet_names = NULL ) { # Want to extract and set values from: # quantities, sdrep, and estimated_params @@ -28,7 +28,7 @@ conout_rceattle <- function( } else { dat <- file } - + # The standardized output describes one stock and has no species dimension, # but CEATTLE is a multispecies model. A multispecies fit's `sdrep` holds # nspp * nyrs values per label, which fails the `n == length(styr:projyr)` @@ -57,22 +57,22 @@ conout_rceattle <- function( i = "Subset the fit to a single species before converting." )) } - + # Extract or use fleet names if (is.null(fleet_names)) { fleet_names <- names(dat$estimated_params$index_log_q) } - + # Output fleet names in console cli::cli_alert_info("Identified fleet names:") cli::cli_alert_info("{fleet_names}") # Create list for morphed dfs to go into (for rbind later) out_list <- list() - + factors <- c("year", "fleet", "fleet_name", "age", "sex", "area", "seas", "season", "time", "era", "subseas", "subseason", "platoon", "platoo", "growth_pattern", "gp", "nsim", "age_a") errors <- c("StdDev", "sd", "se", "SE", "cv", "CV", "stddev") # units <- c("mt", "lbs", "eggs") - + ##### Loop #### # Select the modules by name rather than by position. An Rceattle fit's # element list depends on how it was fitted -- `phase = TRUE` adds @@ -125,18 +125,18 @@ conout_rceattle <- function( dplyr::pull(label) )) ) - + df2 <- values |> dplyr::filter(n == length(dat[["data_list"]]$styr:dat[["data_list"]]$projyr)) |> dplyr::mutate(year = year_col) - + df2 <- values |> dplyr::filter( n != length(dat[["data_list"]]$styr:dat[["data_list"]]$projyr) ) |> dplyr::mutate(year = NA) |> rbind(df2) - + # Extract parameter values ts # The standard errors of the fixed effects are the square root of the # diagonal of cov.fixed, in the same order as par.fixed. @@ -170,7 +170,7 @@ conout_rceattle <- function( par_fixes_count, by = "label" ) - + year_col_par_fix <- rep( dat[["data_list"]]$styr:dat[["data_list"]]$endyr, length(unique( @@ -178,7 +178,7 @@ conout_rceattle <- function( dplyr::pull(label) )) ) - + df3 <- par_fixes |> dplyr::filter(n == length(dat[["data_list"]]$styr:dat[["data_list"]]$endyr)) |> dplyr::mutate(year = year_col_par_fix) @@ -191,13 +191,13 @@ conout_rceattle <- function( # not sure how pop_scalar is indexed # not sure how log_index_hat is indexes # Did not use r_sd for the error in rec bc used it from the other element in the list - + df4 <- rbind(df2, df3) |> dplyr::select(-n) |> dplyr::mutate( module_name = module_name ) - + df4[setdiff(tolower(names(out_new)), tolower(names(df4)))] <- NA out_list[[names(extract)]] <- df4 } else if (module_name == "data_list") { @@ -205,7 +205,7 @@ conout_rceattle <- function( # Only extract specific quantity needs # comp_data?, index_data, catch_data, weight, Ftarget, Flimit data_list_list <- list() - + ####### Indices #### # Extract index_data df_index <- extract[[1]]$index_data |> @@ -227,7 +227,7 @@ conout_rceattle <- function( # still needing to be dropped from an older one. dplyr::select(-dplyr::any_of(c("fleet_code", "q_block"))) cli::cli_alert_info("'Selectivity_block' values located in 'block' columns.") - + # check if species > 1 if (length(unique(df_index$species)) > 1) { cli::cli_abort("Not currently compatible for multispecies.") @@ -235,7 +235,7 @@ conout_rceattle <- function( df_index <- df_index |> dplyr::select(-species) } - + # expand df long to have obs and pred in same column with label df_index_long <- df_index |> tidyr::pivot_longer( @@ -252,10 +252,10 @@ conout_rceattle <- function( # ) label = stringr::str_replace_all(label, "indices", "index") ) - + df_index_long[setdiff(tolower(names(out_new)), tolower(names(df_index_long)))] <- NA data_list_list[["index_data"]] <- df_index_long - + ####### Catch indexing #### # Extract catch_data and align with log_index_hat and catch_h # Modify sdrep in outlist to include index @@ -289,28 +289,28 @@ conout_rceattle <- function( values_to = "estimate" ) |> dplyr::select(-c(fleet_code, species)) - + # Remove fleet names if do not match object # if (unique(df_catch$fleet) %notin% fleet_names) { # df_catch <- df_catch |> # dplyr::mutate(fleet = NA) # } - + if (length(unique(df_catch$month)) == 1) { df_catch$month <- NA } df_catch[setdiff(tolower(names(out_new)), tolower(names(df_catch)))] <- NA data_list_list[["catch_data"]] <- df_catch - + ####### Comp indexing #### df_comp_obs <- dat$data_list$comp_data |> dplyr::rename_with(tolower) |> dplyr::mutate( label = "index_observed" ) - + indexing_vars_cols <- colnames(df_comp_obs)[!grepl("comp", colnames(df_comp_obs))] - + # `age_hat` holds one row per row of `comp_data`, in the same order, so # it binds column-wise. cross_join() paired every observation with the # whole prediction matrix instead, which is a Cartesian product: on the @@ -332,7 +332,7 @@ conout_rceattle <- function( # NOTE: the below age mutate slows down code age = stringr::str_replace(age, "agehat_", "") ) - + # Finish adjusting comp_obs # pivot obs data df_comp_obs <- df_comp_obs |> @@ -347,7 +347,7 @@ conout_rceattle <- function( # NOTE: the below age mutate slows down code age = stringr::str_replace(age, "comp_", "") ) - + df_comp <- rbind(df_comp_obs, df_comp_pred) |> # Match the index and catch frames: the standard names the fleet # `fleet`, carries no `fleet_name` or `species`, and every row states @@ -357,10 +357,10 @@ conout_rceattle <- function( dplyr::select(-dplyr::any_of("species")) |> # TODO: do I need to filter sample size by <3 for confidentiality or does this not apply? dplyr::select(-c(age0_length1, fleet_code, sample_size)) - + df_comp[setdiff(tolower(names(out_new)), tolower(names(df_comp)))] <- NA data_list_list[["comp_data"]] <- df_comp - + # final df for data_list module # rbind() rather than bind_rows(): every frame has already been padded # to the standard column set above, so rbind() succeeds and keeps the @@ -379,7 +379,7 @@ conout_rceattle <- function( # Rceattle stores sex 1 as females, or both sexes when nsex = 1. sex_names <- if (nsex == 1) NA_character_ else c("female", "male") quantities_list <- list() - + if ("sel_at_age" %in% names(extract[[1]])) { sel <- extract[[1]][["sel_at_age"]][, seq_len(nsex), seq_along(ages), , drop = FALSE] df_sel <- expand.grid( @@ -396,7 +396,7 @@ conout_rceattle <- function( df_sel[setdiff(tolower(names(out_new)), tolower(names(df_sel)))] <- NA quantities_list[["sel_at_age"]] <- df_sel } - + if ("M_at_age" %in% names(extract[[1]])) { m_at_age <- extract[[1]][["M_at_age"]][1, seq_len(nsex), seq_along(ages), , drop = FALSE] df_m <- expand.grid( @@ -412,7 +412,7 @@ conout_rceattle <- function( df_m[setdiff(tolower(names(out_new)), tolower(names(df_m)))] <- NA quantities_list[["m_at_age"]] <- df_m } - + if (length(quantities_list) > 0) { out_list[[names(extract)]] <- Reduce(rbind, quantities_list) |> dplyr::mutate( @@ -441,7 +441,7 @@ conout_rceattle <- function( # mod_name2 <- glue::glue("{module_name}_{names(extract[[1]][i])}") # comment out message once finished development cli::cli_alert_info("Processing {names(extract[[1]][i])}") - + df <- extract[[1]][i][[1]] |> expand_element(fleet_names = fleet_names) |> dplyr::mutate( diff --git a/R/conout_ss3.R b/R/conout_ss3.R index 6ca8ec69..95a6cd36 100644 --- a/R/conout_ss3.R +++ b/R/conout_ss3.R @@ -1,6 +1,6 @@ #' Code to convert SS3 output to standard framework. -#' -#' Does not change naming conventions. Contains code to work with SS3 Report.sso +#' +#' Does not change naming conventions. Contains code to work with SS3 Report.sso #' file or returned object from `r4ss::ss_output()`. #' #' @inheritParams convert_output @@ -9,9 +9,9 @@ #' #' @returns Reshaped data frame. conout_ss3 <- function( - file, - out_new, - fleet_names = NULL + file, + out_new, + fleet_names = NULL ) { if (is.character(file)) { # report.sso file @@ -31,7 +31,7 @@ conout_ss3 <- function( if (vers < 3.3) { cli::cli_abort("This function in its current state can not process the data.") } - + # Extract fleet names if (is.null(fleet_names)) { fleet_names <- SS3_extract_fleet(dat, vers) @@ -39,7 +39,7 @@ conout_ss3 <- function( # Output fleet names in console cli::cli_alert_info("Identified fleet names:") cli::cli_alert_info("{fleet_names}") - + # Estimated and focal parameters to put into reformatted output df - naming conventions from SS3 # Extract keywords from ss3 file # Find row where keywords start @@ -59,7 +59,7 @@ conout_ss3 <- function( # identify first reported keyword keywords_end_row <- which(apply(dat, 1, function(row) any(grepl(keyword_1, row))))[2] - 12 # 12 rows behind is the last entry for keywords # always extract the second entry bc the first is just in the list of keywords - + keywords <- dat[keywords_start_row:keywords_end_row, ][-c(1:3), c(1:3)] |> replace_empty_with_na_all() keywords <- Filter(function(x) !all(is.na(x)), keywords) @@ -68,7 +68,7 @@ conout_ss3 <- function( dplyr::mutate(output_order = as.numeric(stringr::str_extract(output_order, "\\d+$"))) |> dplyr::filter(output == "Y") |> dplyr::pull(keyword) - + # Group parameters base on table pattern std <- c( "DERIVED_QUANTITIES", @@ -135,13 +135,13 @@ conout_ss3 <- function( # Output fleet names in console cli::cli_alert_info("Identified fleet names:") cli::cli_alert_info("{fleet_names}") - + # Extract start year and end year start_year <- file$startyr end_year <- file$endyr - + param_names <- names(dat) - + std <- c( "recruit", # STD "exploitation", # STD @@ -189,7 +189,7 @@ conout_ss3 <- function( cha <- c() info <- c() } - + # Loop for all identified parameters to extract for plotting and use # Create list of parameters that were not found in the output file # 1,4,10,17,19,20,22,32,37 @@ -204,14 +204,14 @@ conout_ss3 <- function( "settlement", "birthseas", "count", "kind" ) - + errors <- c( "StdDev", "sd", "std", "stddev", "se", "SE", "cv", "CV" # "dev" # not included bc this is dev in model, not uncertainty of the value ) - + miss_parms <- c() out_list <- list() #### SS3 loop #### @@ -225,7 +225,7 @@ conout_ss3 <- function( } else { extract <- file[[parm_sel]] } - + if (!is.data.frame(extract)) { if (is.numeric(extract)) { df <- data.frame( @@ -314,14 +314,14 @@ conout_ss3 <- function( } else if (any(colnames(df3) %in% c(factors, errors))) { # Keeping check here if case arises that there is a similar situation to the error # aka there are multiple columns containing the string and they are not selected properly - + if ("sexes" %in% colnames(df3)) { df3 <- df3 |> # add in case if sexes is present and add sex as na if so dplyr::mutate(sex = if (any(grepl("^sexes$", colnames(df3)))) sexes else NA) |> dplyr::select(-sexes) } - + # Identify which errors were identified in a column & rename err_col_id <- colnames(df3)[grepl(paste0(errors, "$", collapse = "|"), colnames(df3))] # rename error column @@ -395,7 +395,7 @@ conout_ss3 <- function( ) } ) - + df4 <- df4 |> dplyr::mutate( label = dplyr::case_when( @@ -405,7 +405,7 @@ conout_ss3 <- function( TRUE ~ stringr::str_extract(label, "^.*?(?=_\\d|_gp|_fem|_mal|_sx|:|$)") ) ) - + if (parm_sel == "DISCARD_OUTPUT") { df4 <- df4 |> dplyr::mutate(label = glue::glue("discard_{label}")) @@ -415,7 +415,7 @@ conout_ss3 <- function( cli::cli_alert_warning(glue::glue("Data frame not compatible in {parm_sel}.")) } if (any(colnames(df4) %in% c("value"))) df4 <- dplyr::rename(df4, estimate = value) - + # Check if error values are in the labels column and extract out if (any(sapply(paste0("(^|[_.])", errors, "($|[_.])"), function(x) grepl(x, unique(df4$label))))) { err_names <- unique(df4$label)[grepl(paste(paste0("(^|[_.])", errors, "($|[_.])"), collapse = "|"), unique(df4$label)) & !unique(df4$label) %in% errors] @@ -494,7 +494,7 @@ conout_ss3 <- function( } } } - + df5 <- df4 |> dplyr::select(tidyselect::any_of(c("label", "estimate", "year", factors, errors))) |> dplyr::mutate( @@ -510,7 +510,7 @@ conout_ss3 <- function( # estimate # ) ) - + if (any(colnames(df5) %in% errors)) { df5 <- df5 |> dplyr::mutate(uncertainty_label = intersect(names(df5), errors)) |> @@ -525,11 +525,11 @@ conout_ss3 <- function( colnames(df5) <- tolower(names(df5)) } if ("seas" %in% colnames(df5)) df5 <- dplyr::rename(df5, season = seas) - + if ("subseas" %in% colnames(df5)) df5 <- dplyr::rename(df5, subseason = subseas) - + if ("like" %in% colnames(df5)) df5 <- dplyr::rename(df5, likelihood = like) - + df5[setdiff(tolower(names(out_new)), tolower(names(df5)))] <- NA if (ncol(out_new) < ncol(df5)) { diff <- setdiff(names(df5), names(out_new)) @@ -629,7 +629,7 @@ conout_ss3 <- function( # Add to new dataframe df5 <- Reduce(rbind, comps_list) out_list[[parm_sel]] <- df5 - + ##### cha #### } else if (parm_sel %in% cha) { # Only one keyword characterized as this @@ -673,7 +673,7 @@ conout_ss3 <- function( # "SPAWN_RECR_CURVE" # "Biology_at_age_in_endyr" # "PARAMETERS" - + if (parm_sel %in% c("SPAWN_RECR_CURVE", "SPAWN_RECRUIT_CURVE")) { # 32 # TODO: add this to converter @@ -749,7 +749,7 @@ conout_ss3 <- function( # label = paste("estimate_", label, sep = ""), morph = NA ) - + sub_df2 <- df3[, c(1:2, (actual_col + 1):(moref_col - 1))] |> tidyr::pivot_longer( cols = -c(yr, era), @@ -1049,7 +1049,7 @@ conout_ss3 <- function( row <- row[row != "XX"] df1 <- df1[, -loc_xx] } - + # TODO: apply this next if statement to a general process so it's part of the standard cleaning # check if the headers make sense # this is a temporary fix to a specific bug @@ -1063,10 +1063,10 @@ conout_ss3 <- function( df2 <- df1[stats::complete.cases(df1), ] row <- df2[1, ] } - + # make row the header names for first df colnames(df1) <- row - + # find row number that matches 'row' rownum <- row_match(row, df1) # Subset data frame @@ -1098,20 +1098,20 @@ conout_ss3 <- function( ( # add conditions for naming label from aa.al label <- switch(parm_sel, - # "sizeselex" = "selectivity_length", - "ageselex" = "selectivity_age", - "Natural_Mortality" = "natural_mortality_age", - "fatage" = "fishing_mortality_age", - "natage" = "abundance_age", - "batage" = "biomass_age", - "natlen" = "abundance_length", - "batlen" = "biomass_length", - "discard_at_age" = "discard_age", - "catage" = "catch_age", - "Z_at_age" = "total_mortality_age", - "M_at_age" = "natural_mortality_age", - "Z_by_area" = "total_mortality", - "M_by_area" = "natural_mortality" + # "sizeselex" = "selectivity_length", + "ageselex" = "selectivity_age", + "Natural_Mortality" = "natural_mortality_age", + "fatage" = "fishing_mortality_age", + "natage" = "abundance_age", + "batage" = "biomass_age", + "natlen" = "abundance_length", + "batlen" = "biomass_length", + "discard_at_age" = "discard_age", + "catage" = "catch_age", + "Z_at_age" = "total_mortality_age", + "M_at_age" = "natural_mortality_age", + "Z_by_area" = "total_mortality", + "M_by_area" = "natural_mortality" ) ) } @@ -1124,10 +1124,10 @@ conout_ss3 <- function( } else { fac <- "age" } - + # remove fac from label if (grepl(glue::glue("_{fac}"), label)) label <- stringr::str_remove(label, glue::glue("_{fac}")) - + # Reformat dataframe if (any(colnames(df3) %in% c("Yr", "yr"))) { df3 <- df3 |> diff --git a/R/convert_output.R b/R/convert_output.R index d3b2ac99..111c63fd 100644 --- a/R/convert_output.R +++ b/R/convert_output.R @@ -63,18 +63,17 @@ convert_output <- function( save_dir = NULL, start_year = NULL ) { - if (is.character(file) && grepl("Report.sso", file)) { lifecycle::deprecate_warn( - when = "2.8.0", - what = I("convert_output(file = 'Report.sso')"), + when = "2.8.0", + what = I("convert_output(file = 'Report.sso')"), details = c( i = "Please use the returned object from `r4ss::ss_output()`", i = "File will be compatible until Oct. 1, 2027" ) ) } - + # check if entered save_dir exists so doesn't waste user time finding this out at the end if (!is.null(save_dir)) { if (!grepl(".rda", save_dir)) { @@ -232,7 +231,7 @@ convert_output <- function( out_new <- conout_fims(file = file, out_new = out_new, start_year = start_year) #### Rceattle #### } else if (model == "rceattle") { - out_new <- conout_rceattle(file = file, out_new = out_new, fleet_names = fleet_names) + out_new <- conout_rceattle(file = file, out_new = out_new, fleet_names = fleet_names) } else { cli::cli_abort(c( message = "Output file not compatible.", diff --git a/R/data.R b/R/data.R index ec214e56..95263d2d 100644 --- a/R/data.R +++ b/R/data.R @@ -44,7 +44,7 @@ #' 2018 Gulf of Alaska Pollock stock assessment output #' -#' Output of the 2018 Gulf of Alaska Pollock stock assessment produced from Rceattle, standardized +#' Output of the 2018 Gulf of Alaska Pollock stock assessment produced from Rceattle, standardized #' using `stockplotr::convert_output()`. The example can be found and run from the Rceattle repository. #' #' @docType data @@ -103,7 +103,7 @@ #' SEDAR 55 South Atlantic Vermilion Snapper #' -#' Standardized output of the 2018 South Atlantic Vermilion Snapper stock assessment +#' Standardized output of the 2018 South Atlantic Vermilion Snapper stock assessment #' produced from the Beaufort Assessment Model (BAM). #' #' @docType data @@ -148,7 +148,7 @@ #' } #' #' @keywords datasets -#' +#' #' @references SEDAR (2018) #' (\url{https://sedarweb.org/documents/sedar-55-stock-assessment-report-south-atlantic-vermilion-snapper/}) #' @@ -160,9 +160,9 @@ #' SS3 Simple stock assessment output #' -#' Standardized output of a generic simple example of SS3 found from the `r4ss` -#' repository examples. The raw output is converted to an R readable object -#' using `r4ss::ss_output` then standardized using `stockplotr::convert_output()`. +#' Standardized output of a generic simple example of SS3 found from the `r4ss` +#' repository examples. The raw output is converted to an R readable object +#' using `r4ss::ss_output` then standardized using `stockplotr::convert_output()`. #' #' @docType data #' diff --git a/R/extract_sis_data.R b/R/extract_sis_data.R index 0e3e3999..5c59e650 100644 --- a/R/extract_sis_data.R +++ b/R/extract_sis_data.R @@ -3,26 +3,26 @@ #' Semi-automate the extraction of key quantities from model results and time #' series data from exported figure/table `.rda` files for eventual transmittance #' to SIS via `asar::export_to_sis()`. -#' +#' #' @param sis_data_dir Path. Location to save the sis_assmt_template.csv and #' sis_ts_template.csv files or, if present, the location of the #' existing sis_assmt_template.csv file. -#' +#' #' Default: The working directory. -#' -#' @param key_quantities_dir Path. Location of the existing key_quantities.csv +#' +#' @param key_quantities_dir Path. Location of the existing key_quantities.csv #' file. -#' +#' #' Default: The working directory. -#' -#' @param figures_tables_dir Path. Location of the existing 'figures' and +#' +#' @param figures_tables_dir Path. Location of the existing 'figures' and #' 'tables' directories. -#' +#' #' Default: The working directory. -#' +#' #' @details See the "Automating data extraction for SIS" vignette for a #' detailed overview of the workflow and requirements for this function. -#' +#' #' @export #' #' @examples @@ -36,30 +36,33 @@ #' extract_sis_data <- function(sis_data_dir = getwd(), key_quantities_dir = getwd(), - figures_tables_dir = getwd() - ) { + figures_tables_dir = getwd()) { # check if existing figures and tables folders exist; if both absent, throw an error if (!dir.exists(fs::path(figures_tables_dir, "figures")) & !dir.exists(fs::path(figures_tables_dir, "tables"))) { cli::cli_abort("Neither 'figures' nor 'tables' folders were found in {figures_tables_dir}. Please check the `figures_tables_dir` path, or export figures and tables, and then try again.") - } - + } + # Check if existing data files exist; if not, start from blank templates if (!file.exists(fs::path(sis_data_dir, "sis_assmt_template.csv"))) { assmt_dat <- utils::read.csv(system.file("resources", "sis_assmt_template.csv", package = "stockplotr")) cli::cli_alert_info("No existing sis_assmt_template.csv found in {sis_data_dir}. Using blank template.") } else { assmt_dat <- utils::read.csv(fs::path(sis_data_dir, "sis_assmt_template.csv"), stringsAsFactors = FALSE) - cli::cli_alert_success("Found existing sis_assmt_template.csv in {sis_data_dir}.") + cli::cli_alert_success("Found existing sis_assmt_template.csv in {sis_data_dir}.") } - + ts_dat <- utils::read.csv(system.file("resources", "sis_ts_template.csv", package = "stockplotr")) - + # extract key quantities from csv and assign to variables kqs_path <- fs::path(key_quantities_dir, "key_quantities.csv") - if (file.exists(kqs_path)){ - kqs <- utils::read.csv(fs::path(key_quantities_dir, - "key_quantities.csv"), - stringsAsFactors = FALSE) + if (file.exists(kqs_path)) { + kqs <- utils::read.csv( + fs::path( + key_quantities_dir, + "key_quantities.csv" + ), + stringsAsFactors = FALSE + ) cli::cli_alert_success("Found existing key_quantities.csv in {key_quantities_dir}.") } else { cli::cli_alert_warning("No existing key_quantities.csv found in {key_quantities_dir}.") @@ -69,8 +72,8 @@ extract_sis_data <- function(sis_data_dir = getwd(), "*" = "plot_biomass()" )) } - - if (file.exists(kqs_path)){ + + if (file.exists(kqs_path)) { # insert values into the sis_assmt_template.csv file mapping <- tibble::tribble( ~key_quantity, ~Variable, @@ -92,20 +95,20 @@ extract_sis_data <- function(sis_data_dir = getwd(), "F.MSY.terminal.max", "AS_FMSY_MAX", "F.MSY.terminal.min", "AS_FMSY_MIN" ) - + # Extract values and format into a key-value matching table - new_vals <- kqs |> - dplyr::inner_join(mapping, by = "key_quantity") |> - dplyr::mutate(value = as.numeric(value)) |> + new_vals <- kqs |> + dplyr::inner_join(mapping, by = "key_quantity") |> + dplyr::mutate(value = as.numeric(value)) |> dplyr::select(Variable, new_value = value) - + # Update assmt_dat - assmt_dat <- assmt_dat |> - dplyr::left_join(new_vals, by = "Variable") |> - dplyr::mutate(Value = ifelse(!is.na(new_value), new_value, Value)) |> + assmt_dat <- assmt_dat |> + dplyr::left_join(new_vals, by = "Variable") |> + dplyr::mutate(Value = ifelse(!is.na(new_value), new_value, Value)) |> dplyr::select(-new_value) } - + # obtain time series data if (!dir.exists(fs::path(figures_tables_dir, "figures"))) { cli::cli_alert_info("'figures' folder not found in {sis_data_dir}.") @@ -127,76 +130,83 @@ extract_sis_data <- function(sis_data_dir = getwd(), biomass <<- NULL } ) - + # SPAWNERS (fits under "abundance" category) - tryCatch({ - load(fs::path(figures_tables_dir, "figures", "spawning_biomass_figure.rda")) |> suppressWarnings() - sb <- rda[["figure"]][["layers"]][["geom_line"]]$data - spawning_biomass <- sb |> - dplyr::group_by(year) |> - dplyr::summarise(sum = sum(estimate)) |> - dplyr::rename(Spawners = sum) - }, - error = function(e) { - cli::cli_alert_warning("Spawning biomass data was not extracted from the 'spawning_biomass_figure.rda' file.") - spawning_biomass <<- NULL - } + tryCatch( + { + load(fs::path(figures_tables_dir, "figures", "spawning_biomass_figure.rda")) |> suppressWarnings() + sb <- rda[["figure"]][["layers"]][["geom_line"]]$data + spawning_biomass <- sb |> + dplyr::group_by(year) |> + dplyr::summarise(sum = sum(estimate)) |> + dplyr::rename(Spawners = sum) + }, + error = function(e) { + cli::cli_alert_warning("Spawning biomass data was not extracted from the 'spawning_biomass_figure.rda' file.") + spawning_biomass <<- NULL + } ) - + # RECRUITMENT - tryCatch({ - load(fs::path(figures_tables_dir, "figures", "abundance_at_age_figure.rda")) |> suppressWarnings() - rec <- rda[["figure"]][["layers"]][["geom_point"]][["data"]] - recruitment <- rec |> - dplyr::filter(age == 1) |> - dplyr::group_by(year) |> - dplyr::summarise(sum = sum(estimate)) |> - dplyr::rename(Recruitment = sum) - }, - error = function(e) { - cli::cli_alert_warning("Recruitment (age 1) data was not extracted from the 'abundance_at_age_figure.rda' file.") - recruitment <<- NULL - - # this is for recruitment in mt- not age-1, which is what SIS expects - # load(fs::path(figures_tables_dir, "figures", "recruitment_figure.rda")) |> suppressWarnings() - # rec <- rda[["figure"]][["layers"]][["geom_line"]]$data - # recruitment <- rec |> - # dplyr::group_by(year) |> - # dplyr::summarise(sum = sum(predicted_recruitment)) |> - # dplyr::rename(Recruitment = sum) - # }, - # error = function(e) { - # cli::cli_alert_warning("Recruitment data was not extracted from the 'recruitment_figure.rda' file.") - # recruitment <<- NULL - }) - + tryCatch( + { + load(fs::path(figures_tables_dir, "figures", "abundance_at_age_figure.rda")) |> suppressWarnings() + rec <- rda[["figure"]][["layers"]][["geom_point"]][["data"]] + recruitment <- rec |> + dplyr::filter(age == 1) |> + dplyr::group_by(year) |> + dplyr::summarise(sum = sum(estimate)) |> + dplyr::rename(Recruitment = sum) + }, + error = function(e) { + cli::cli_alert_warning("Recruitment (age 1) data was not extracted from the 'abundance_at_age_figure.rda' file.") + recruitment <<- NULL + + # this is for recruitment in mt- not age-1, which is what SIS expects + # load(fs::path(figures_tables_dir, "figures", "recruitment_figure.rda")) |> suppressWarnings() + # rec <- rda[["figure"]][["layers"]][["geom_line"]]$data + # recruitment <- rec |> + # dplyr::group_by(year) |> + # dplyr::summarise(sum = sum(predicted_recruitment)) |> + # dplyr::rename(Recruitment = sum) + # }, + # error = function(e) { + # cli::cli_alert_warning("Recruitment data was not extracted from the 'recruitment_figure.rda' file.") + # recruitment <<- NULL + } + ) + # FISHING MORTALITY - tryCatch({ - load(fs::path(figures_tables_dir, "figures", "fishing_mortality_figure.rda")) |> suppressWarnings() - fm <- rda[["figure"]][["layers"]][["geom_line"]]$data - fishing_mortality <- fm |> - dplyr::group_by(year) |> - dplyr::summarise(mean = mean(estimate)) |> - dplyr::rename(Fmort = mean) - }, - error = function(e) { - cli::cli_alert_warning("Fishing mortality data was not extracted from the 'fishing_mortality_figure.rda' file.") - fishing_mortality <<- NULL - }) - + tryCatch( + { + load(fs::path(figures_tables_dir, "figures", "fishing_mortality_figure.rda")) |> suppressWarnings() + fm <- rda[["figure"]][["layers"]][["geom_line"]]$data + fishing_mortality <- fm |> + dplyr::group_by(year) |> + dplyr::summarise(mean = mean(estimate)) |> + dplyr::rename(Fmort = mean) + }, + error = function(e) { + cli::cli_alert_warning("Fishing mortality data was not extracted from the 'fishing_mortality_figure.rda' file.") + fishing_mortality <<- NULL + } + ) + # INDEX - tryCatch({ - load(fs::path(figures_tables_dir, "figures", "index_figure.rda")) |> suppressWarnings() - index <- rda[["figure"]][["layers"]][["geom_line"]]$data - index <- index |> - dplyr::group_by(year) |> - dplyr::summarise(mean = mean(estimate)) |> - dplyr::rename(Index = mean) - }, - error = function(e) { - cli::cli_alert_warning("Index data was not extracted from the 'index_figure.rda' file.") - index <<- NULL - }) + tryCatch( + { + load(fs::path(figures_tables_dir, "figures", "index_figure.rda")) |> suppressWarnings() + index <- rda[["figure"]][["layers"]][["geom_line"]]$data + index <- index |> + dplyr::group_by(year) |> + dplyr::summarise(mean = mean(estimate)) |> + dplyr::rename(Index = mean) + }, + error = function(e) { + cli::cli_alert_warning("Index data was not extracted from the 'index_figure.rda' file.") + index <<- NULL + } + ) } if (!dir.exists(fs::path(figures_tables_dir, "tables"))) { cli::cli_alert_info("'tables' folder not found in {sis_data_dir}.") @@ -205,38 +215,38 @@ extract_sis_data <- function(sis_data_dir = getwd(), } else { table_ts <- TRUE tryCatch( - { - load(fs::path(figures_tables_dir, "tables", "total_catch_table.rda")) |> suppressWarnings() - catch <- rda[["table"]][["_data"]] - catch_cols <- colnames(catch) - cols_without_catch <- c("Sex", "Area", "Season", "Type") - if (any(cols_without_catch %in% catch_cols)) { + { + load(fs::path(figures_tables_dir, "tables", "total_catch_table.rda")) |> suppressWarnings() + catch <- rda[["table"]][["_data"]] + catch_cols <- colnames(catch) + cols_without_catch <- c("Sex", "Area", "Season", "Type") + if (any(cols_without_catch %in% catch_cols)) { + catch <- catch |> + dplyr::select(-dplyr::any_of(cols_without_catch)) + } catch <- catch |> - dplyr::select(-dplyr::any_of(cols_without_catch)) + # remove values in parentheses, if present + dplyr::mutate(dplyr::across(!Year, ~ stringr::str_remove_all(.x, "\\s*\\(.*?\\)"))) |> + dplyr::mutate(dplyr::across(!Year, ~ stringr::str_remove_all(.x, ","))) |> + dplyr::mutate(dplyr::across(!Year, ~ as.numeric(.x))) |> + # summarize non-Year rows + dplyr::rowwise() |> + dplyr::mutate(Catch = sum(dplyr::c_across(!Year), na.rm = TRUE)) |> + dplyr::ungroup() |> + dplyr::select(Year, Catch) + }, + error = function(e) { + cli::cli_alert_warning("Catch data will not be extracted from the 'total_catch_table.rda' file.") + catch <<- NULL } - catch <- catch |> - # remove values in parentheses, if present - dplyr::mutate(dplyr::across(!Year, ~ stringr::str_remove_all(.x, "\\s*\\(.*?\\)"))) |> - dplyr::mutate(dplyr::across(!Year, ~ stringr::str_remove_all(.x, ","))) |> - dplyr::mutate(dplyr::across(!Year, ~ as.numeric(.x))) |> - # summarize non-Year rows - dplyr::rowwise() |> - dplyr::mutate(Catch = sum(dplyr::c_across(!Year), na.rm = TRUE)) |> - dplyr::ungroup() |> - dplyr::select(Year, Catch) - }, - error = function(e) { - cli::cli_alert_warning("Catch data will not be extracted from the 'total_catch_table.rda' file.") - catch <<- NULL - } ) } - - if(exists("fig_ts")){ + + if (exists("fig_ts")) { summaries <- c("biomass", "spawning_biomass", "recruitment", "fishing_mortality", "index") - - summaries <- summaries[sapply(summaries, function(x) !is.null(get(x)))] - + + summaries <- summaries[sapply(summaries, function(x) !is.null(get(x)))] + # join all summaries by year all_summaries <- c() for (i in seq_along(summaries)) { @@ -244,25 +254,27 @@ extract_sis_data <- function(sis_data_dir = getwd(), all_summaries <- get(summaries[i]) } else { all_summaries <- dplyr::full_join(all_summaries, - get(summaries[i]), - by = "year") + get(summaries[i]), + by = "year" + ) } } } - if (exists("table_ts") & !is.null(catch)){ - if (!is.null(all_summaries) & exists("fig_ts")){ + if (exists("table_ts") & !is.null(catch)) { + if (!is.null(all_summaries) & exists("fig_ts")) { catch <- catch |> dplyr::rename(year = Year) all_summaries <- dplyr::full_join(all_summaries, - catch, - by = "year") + catch, + by = "year" + ) summaries <- c(summaries, "catch") } else { all_summaries <- get("catch") summaries <- "catch" } } - + ts_options <- summaries[!is.na(summaries)] cli::cli_alert_info("The following time series summaries were extracted:") cli::cli_ul(ts_options) @@ -281,23 +293,25 @@ extract_sis_data <- function(sis_data_dir = getwd(), if (all(primary_options2 %in% ts_options)) { cli::cli_alert_info("One of the following categories can be a Primary time series:") cli::cli_ul(primary_options2) - if (interactive()) { + if (interactive()) { primary1 <- readline("Which category should be chosen? ") - if (primary1 %notin% primary_options2) { - cli::cli_abort("Invalid Primary category specified. Please choose from: {primary_options2}.") - } else { - primary <- c(primary, primary1) - } + if (primary1 %notin% primary_options2) { + cli::cli_abort("Invalid Primary category specified. Please choose from: {primary_options2}.") } else { - primary <- c(primary, primary_options2[1]) - cli::cli_alert_info("Primary categor{?y/ies} set to {primary} by default in non-interactive mode.") + primary <- c(primary, primary1) } + } else { + primary <- c(primary, primary_options2[1]) + cli::cli_alert_info("Primary categor{?y/ies} set to {primary} by default in non-interactive mode.") + } } else if (any(primary_options2 %in% ts_options)) { primary <- c(primary, ts_options[ts_options %in% primary_options2]) } - - if (length(primary) == 0) {primary <- NA} - + + if (length(primary) == 0) { + primary <- NA + } + category_pairs <- list( "fishing_mortality" = "Fmort", "recruitment" = "Recruitment", @@ -306,41 +320,41 @@ extract_sis_data <- function(sis_data_dir = getwd(), "biomass" = "Biomass", "index" = "Index" ) - + primary <- unlist(lapply(primary, function(x) category_pairs[[x]])) - + # identify sis_assmt_template AS_B_UNIT values if coded b_unit <- assmt_dat$Value[assmt_dat$Variable == "AS_B_UNIT"] if (as.numeric(b_unit) %in% 1:8) { b_unit <- switch(b_unit, - "1" = "Metric Tons", - "2" = "Thousand Metric Tons", - "3" = "Adult spawners - Natural & Hatchery - Escapement", - "4" = "Adult spawners - Hatchery - Escapement", - "5" = "Adult spawners - Natural - Escapement", - "6" = "Number of Eggs", - "7" = "kg / tow", - "8" = "Number of Fish" + "1" = "Metric Tons", + "2" = "Thousand Metric Tons", + "3" = "Adult spawners - Natural & Hatchery - Escapement", + "4" = "Adult spawners - Hatchery - Escapement", + "5" = "Adult spawners - Natural - Escapement", + "6" = "Number of Eggs", + "7" = "kg / tow", + "8" = "Number of Fish" ) } - + # identify sis_assmt_template AS_F_UNIT values if coded f_unit <- assmt_dat$Value[assmt_dat$Variable == "AS_F_UNIT"] if (as.numeric(f_unit) %in% 1:7) { f_unit <- switch(f_unit, - "1" = "Apical F", - "2" = "Fully-selected F", - "3" = "Exploitation Rate", - "4" = "Relative F", - "5" = "Metric Tons", - "6" = "1 - SPR", - "7" = "Z - M" + "1" = "Apical F", + "2" = "Fully-selected F", + "3" = "Exploitation Rate", + "4" = "Relative F", + "5" = "Metric Tons", + "6" = "1 - SPR", + "7" = "Z - M" ) } - - + + ts_dat_filled <- all_summaries |> - dplyr::rename_with(~ "Year", .cols = matches("^year$")) |> + dplyr::rename_with(~"Year", .cols = matches("^year$")) |> tidyr::pivot_longer(cols = -Year, names_to = "Category", values_to = "Value") |> dplyr::mutate(Primary = ifelse(tolower(Category) %in% tolower(primary), "Y", "")) |> dplyr::mutate(Description = dplyr::case_when( @@ -356,16 +370,16 @@ extract_sis_data <- function(sis_data_dir = getwd(), Category == "Biomass" ~ as.character(b_unit), Category == "Spawners" ~ as.character(b_unit), Category == "Fmort" ~ as.character(f_unit), - Category == "Index" ~ "", + Category == "Index" ~ "", Category == "Catch" ~ ifelse(kqs$value[kqs$key_quantity == "tot.catch.units"] == " (mt)", "Metric Tons", kqs$value[kqs$key_quantity == "tot.catch.units"]), Category == "Recruitment" ~ "Number of Fish", TRUE ~ NA )) |> dplyr::relocate(Value, .after = Unit) - + # Ensure ts_dat_filled has same cols as ts_dat if (isFALSE(any(colnames(ts_dat_filled) == colnames(ts_dat)))) { - cli::cli_abort("Time series data does not match template structure.") + cli::cli_abort("Time series data does not match template structure.") } # if assmt_dat$Value is NA and Default is 95, change it to Default @@ -374,11 +388,11 @@ extract_sis_data <- function(sis_data_dir = getwd(), assmt_dat$Value[i] <- assmt_dat$Default[i] } } - + # export files assmt_dat_path <- fs::path(sis_data_dir, "sis_assmt_template.csv") ts_dat_path <- fs::path(sis_data_dir, "sis_ts_template.csv") - + if (file.exists(assmt_dat_path) | file.exists(ts_dat_path)) { cli::cli_alert_info("Existing sis_assmt_template.csv or sis_ts_template.csv found in {sis_data_dir}.") overwrite <- readline("Do you want to overwrite the existing files? (y/n): ") @@ -394,7 +408,7 @@ extract_sis_data <- function(sis_data_dir = getwd(), utils::write.csv(ts_dat_filled, ts_dat_path, row.names = FALSE) cli::cli_alert_success("Files saved successfully in {sis_data_dir}.") } - + # remove global variables c("biomass", "spawning_biomass", "recruitment", "fishing_mortality", "index", "catch") |> purrr::walk(~ if (exists(.x, envir = .GlobalEnv)) rm(list = .x, envir = .GlobalEnv)) diff --git a/R/plot_abundance_at_age.R b/R/plot_abundance_at_age.R index 22f7e7b7..480da3a1 100644 --- a/R/plot_abundance_at_age.R +++ b/R/plot_abundance_at_age.R @@ -112,7 +112,7 @@ plot_abundance_at_age <- function( unit_label = unit_label, scale_amount = scale_amount ) - + if (!is.null(facet) && facet == "none") { data <- b |> dplyr::group_by(year, age) |> @@ -176,7 +176,7 @@ plot_abundance_at_age <- function( pop.naa.age.max, pop.naa.fish.min, pop.naa.fish.max, - dir=figures_dir + dir = figures_dir ) # Add key quantities to captions/alt text @@ -187,7 +187,7 @@ plot_abundance_at_age <- function( pop.naa.age.max, pop.naa.fish.min, pop.naa.fish.max, - dir=figures_dir + dir = figures_dir ) create_rda( @@ -199,10 +199,10 @@ plot_abundance_at_age <- function( dat ) } - + if (exists("selected_module")) { rm(selected_module, envir = .GlobalEnv) } - + plot } diff --git a/R/plot_biomass.R b/R/plot_biomass.R index ac8570bc..211056d0 100644 --- a/R/plot_biomass.R +++ b/R/plot_biomass.R @@ -87,7 +87,7 @@ plot_biomass <- function( scale_amount = scale_amount, interactive = interactive ) - + if (is.null(unit_label)) { unit_label <- unique(prepared_data$unit) if (is.na(unit_label)) { @@ -95,7 +95,7 @@ plot_biomass <- function( unit_label <- "" } } - + biomass_label <- ifelse( relative, yes = "Relative biomass", @@ -108,7 +108,7 @@ plot_biomass <- function( ) } ) - + if (relative) { if (nrow(prepared_data) == 0) { cli::cli_abort("No data found for relative biomass. Please check that your data contains a label for 'biomass_biomass_unfished'.") @@ -190,10 +190,10 @@ plot_biomass <- function( ) # calculate & export key quantities - export_kqs(rel.B.min, rel.B.max, dir=figures_dir) + export_kqs(rel.B.min, rel.B.max, dir = figures_dir) # Add key quantities to captions/alt text - insert_kqs(rel.B.min, rel.B.max, dir=figures_dir) + insert_kqs(rel.B.min, rel.B.max, dir = figures_dir) } else { B.min <- calc_kqs( returned_kq = "B.min", @@ -204,8 +204,8 @@ plot_biomass <- function( prepared_data = prepared_data ) - export_kqs(B.min, B.max, dir=figures_dir) - insert_kqs(B.min, B.max, dir=figures_dir) + export_kqs(B.min, B.max, dir = figures_dir) + insert_kqs(B.min, B.max, dir = figures_dir) } B.ref.pt <- as.character(ref_line) @@ -292,8 +292,8 @@ plot_biomass <- function( B.msy, B.terminal.est, B.terminal.min, - B.terminal.max, - dir=figures_dir + B.terminal.max, + dir = figures_dir ) insert_kqs( @@ -308,7 +308,7 @@ plot_biomass <- function( B.terminal.est, B.terminal.min, B.terminal.max, - dir=figures_dir + dir = figures_dir ) insert_kqs( @@ -323,7 +323,7 @@ plot_biomass <- function( B.terminal.est, B.terminal.min, B.terminal.max, - dir=figures_dir + dir = figures_dir ) create_rda( @@ -336,11 +336,10 @@ plot_biomass <- function( scale_amount = scale_amount ) } - + if (exists("selected_module")) { rm(selected_module, envir = .GlobalEnv) } - - final + final } diff --git a/R/plot_biomass_at_age.R b/R/plot_biomass_at_age.R index 1b9cd130..f335ed19 100644 --- a/R/plot_biomass_at_age.R +++ b/R/plot_biomass_at_age.R @@ -64,7 +64,7 @@ plot_biomass_at_age <- function( scale_amount = scale_amount, interactive = interactive ) - + if (is.null(unit_label)) { unit_label <- unique(b$unit) if (is.na(unit_label)) { @@ -72,14 +72,14 @@ plot_biomass_at_age <- function( unit_label <- "" } } - + # Create label for abundance units in legend biomass_label <- label_magnitude( label = "Biomass", unit_label = unit_label, scale_amount = scale_amount ) - + if (!is.null(facet) && facet == "none") { data <- b |> dplyr::group_by(year, age) |> @@ -142,7 +142,7 @@ plot_biomass_at_age <- function( pop.baa.age.max, pop.baa.fish.min, pop.baa.fish.max, - dir=figures_dir + dir = figures_dir ) # Add key quantities to captions/alt text @@ -153,7 +153,7 @@ plot_biomass_at_age <- function( pop.baa.age.max, pop.baa.fish.min, pop.baa.fish.max, - dir=figures_dir + dir = figures_dir ) create_rda( @@ -161,14 +161,14 @@ plot_biomass_at_age <- function( # get name of function and remove "plot_" from it topic_label = gsub("plot_", "", utils::tail(as.character(sys.call()[[1]]), n = 1)), fig_or_table = "figure", - dir=figures_dir, + dir = figures_dir, dat ) } - + if (exists("selected_module")) { rm(selected_module, envir = .GlobalEnv) } - + plot } diff --git a/R/plot_catch_at_age.R b/R/plot_catch_at_age.R index 4917c45d..78308e52 100644 --- a/R/plot_catch_at_age.R +++ b/R/plot_catch_at_age.R @@ -105,7 +105,7 @@ plot_catch_at_age <- function( scale_amount = scale_amount, legend = TRUE ) - + # Check for extracted data, if not return warning and empty plot if (nrow(catch) == 0) { cli::cli_alert_warning("No data found for catch at age. Please check the input data.") @@ -164,7 +164,7 @@ plot_catch_at_age <- function( caa.age.max, tot.catch.min, tot.catch.max, - dir=figures_dir + dir = figures_dir ) # Add key quantities to captions/alt text @@ -175,7 +175,7 @@ plot_catch_at_age <- function( caa.age.max, tot.catch.min, tot.catch.max, - dir=figures_dir + dir = figures_dir ) create_rda( @@ -187,10 +187,10 @@ plot_catch_at_age <- function( dat ) } - + if (exists("selected_module")) { rm(selected_module, envir = .GlobalEnv) } - + plot } diff --git a/R/plot_discard.R b/R/plot_discard.R index 689bd45b..a547c266 100644 --- a/R/plot_discard.R +++ b/R/plot_discard.R @@ -58,7 +58,7 @@ plot_discard <- function( scale_amount = scale_amount, interactive = interactive ) - + # extract unit if unit_label is null and set lbs to F by default lbs <- FALSE if (is.null(unit_label)) { @@ -139,7 +139,7 @@ plot_discard <- function( mod.fit.discards.end.year, fleet.or.survey.name, mod.fit.discards.units, - dir=figures_dir + dir = figures_dir ) # Add key quantities to captions/alt text @@ -150,7 +150,7 @@ plot_discard <- function( mod.fit.discards.end.year, fleet.or.survey.name, mod.fit.discards.units, - dir=figures_dir + dir = figures_dir ) create_rda( @@ -162,10 +162,10 @@ plot_discard <- function( scale_amount = scale_amount ) } - + if (exists("selected_module")) { rm(selected_module, envir = .GlobalEnv) } - + final } diff --git a/R/plot_fishing_mortality.R b/R/plot_fishing_mortality.R index dfd5b141..ccbb73d7 100644 --- a/R/plot_fishing_mortality.R +++ b/R/plot_fishing_mortality.R @@ -111,8 +111,8 @@ plot_fishing_mortality <- function( prepared_data = prepared_data ) - export_kqs(F.min, F.max, dir=figures_dir) - insert_kqs(F.min, F.max, dir=figures_dir) + export_kqs(F.min, F.max, dir = figures_dir) + insert_kqs(F.min, F.max, dir = figures_dir) F.ref.pt <- as.character(ref_line) F.start.year <- min(prepared_data$year) @@ -173,7 +173,7 @@ plot_fishing_mortality <- function( F.MSY.terminal.max, F.MSY.terminal.min, F.MSY.terminal, - dir=figures_dir + dir = figures_dir ) insert_kqs( @@ -189,7 +189,7 @@ plot_fishing_mortality <- function( F.MSY.terminal.max, F.MSY.terminal.min, F.MSY.terminal, - dir=figures_dir + dir = figures_dir ) create_rda( @@ -202,10 +202,10 @@ plot_fishing_mortality <- function( scale_amount = 1 ) } - + if (exists("selected_module")) { rm(selected_module, envir = .GlobalEnv) } - + final } diff --git a/R/plot_landings.R b/R/plot_landings.R index efd1b7bf..2021024c 100644 --- a/R/plot_landings.R +++ b/R/plot_landings.R @@ -59,7 +59,7 @@ plot_landings <- function( ) # |> # filter NA from year # dplyr::filter(!is.na(year)) - + # Process data processed_data <- process_data( dat = prepared_data, @@ -77,7 +77,7 @@ plot_landings <- function( # always select the first label if TRUE dplyr::filter(label == unique(label)[1]) } - + # extract unit if unit_label is null and set lbs to F by default lbs <- FALSE if (is.null(unit_label)) { @@ -93,7 +93,7 @@ plot_landings <- function( } else { if (grepl("lbs|pounds|lb", unit_label, ignore.case = TRUE)) lbs <- TRUE } - + # Units landings_label <- label_magnitude( label = "Landings", @@ -138,7 +138,7 @@ plot_landings <- function( landings.min, landings.max, landings.units, - dir=figures_dir + dir = figures_dir ) # Add key quantities to captions/alt text @@ -148,7 +148,7 @@ plot_landings <- function( landings.min, landings.max, landings.units, - dir=figures_dir + dir = figures_dir ) create_rda( @@ -161,10 +161,10 @@ plot_landings <- function( scale_amount = scale_amount ) } - + if (exists("selected_module")) { rm(selected_module, envir = .GlobalEnv) } - + plt } diff --git a/R/plot_natural_mortality.R b/R/plot_natural_mortality.R index e3c70b03..09d1c1e9 100644 --- a/R/plot_natural_mortality.R +++ b/R/plot_natural_mortality.R @@ -121,7 +121,7 @@ plot_natural_mortality <- function( M.age.max, M.rate.min, M.rate.max, - dir=figures_dir + dir = figures_dir ) # Add key quantities to captions/alt text @@ -130,7 +130,7 @@ plot_natural_mortality <- function( M.age.max, M.rate.min, M.rate.max, - dir=figures_dir + dir = figures_dir ) create_rda( @@ -142,10 +142,10 @@ plot_natural_mortality <- function( dir = figures_dir ) } - + if (exists("selected_module")) { rm(selected_module, envir = .GlobalEnv) } - + final } diff --git a/R/plot_recruitment.R b/R/plot_recruitment.R index 95706a1c..5dbf3c9a 100644 --- a/R/plot_recruitment.R +++ b/R/plot_recruitment.R @@ -73,14 +73,14 @@ plot_recruitment <- function( unit_label <- unique(prepared_data$unit) if (is.na(unit_label) || is.null(unit_label)) cli::cli_alert_warning("No unit label found in the data. Please provide a unit label using the 'unit_label' argument.") } - + recruitment_label <- label_magnitude( label = "Recruitment", unit_label = unit_label, scale_amount = scale_amount, legend = FALSE ) - + # Check if contains 'rec devs' and filter out if (any(grepl("recruitment_deviations", unique(recruitment$label)))) { if (length(unique(recruitment$label)) > 1) { @@ -194,10 +194,10 @@ plot_recruitment <- function( dir = figures_dir ) } - + if (exists("selected_module")) { rm(selected_module, envir = .GlobalEnv) } - + final } diff --git a/R/plot_recruitment_deviations.R b/R/plot_recruitment_deviations.R index f00ae1af..f2ad753d 100644 --- a/R/plot_recruitment_deviations.R +++ b/R/plot_recruitment_deviations.R @@ -98,7 +98,7 @@ plot_recruitment_deviations <- function( recruit.dev.end.year, recruit.dev.min, recruit.dev.max, - dir=figures_dir + dir = figures_dir ) # Add key quantities to captions/alt text @@ -107,7 +107,7 @@ plot_recruitment_deviations <- function( recruit.dev.end.year, recruit.dev.min, recruit.dev.max, - dir=figures_dir + dir = figures_dir ) create_rda( diff --git a/R/plot_selectivity.R b/R/plot_selectivity.R index 2af46ca7..d4781ad4 100644 --- a/R/plot_selectivity.R +++ b/R/plot_selectivity.R @@ -54,7 +54,7 @@ plot_selectivity <- function( interactive = interactive, module = module ) - + if (is.null(unit_label)) { if (!any(grepl("length", prepared_data$label))) { unit_label <- "years" @@ -167,7 +167,7 @@ plot_selectivity <- function( selectivity.x, selectivity.start.year, selectivity.end.year, - dir=figures_dir + dir = figures_dir ) # Add key quantities to captions/alt text @@ -179,7 +179,7 @@ plot_selectivity <- function( selectivity.x, selectivity.start.year, selectivity.end.year, - dir=figures_dir + dir = figures_dir ) @@ -192,10 +192,10 @@ plot_selectivity <- function( dir = figures_dir ) } - + if (exists("selected_module")) { rm(selected_module, envir = .GlobalEnv) } - + final } diff --git a/R/plot_spawning_biomass.R b/R/plot_spawning_biomass.R index 91b3cb80..1047b598 100644 --- a/R/plot_spawning_biomass.R +++ b/R/plot_spawning_biomass.R @@ -40,9 +40,9 @@ #' #' Options: (including, but not limited to) "target", "msy", and "unfished" #' If the reference point is not found in the data, set ref_line = c("name" = value). -#' @param unit_label String. Spawning biomass unit as indicated from the data. -#' When setting a unit of pounds please use one of the following keywords: -#' "lbs", "pounds", "lb". For example "1000s of lbs" would still be recognized +#' @param unit_label String. Spawning biomass unit as indicated from the data. +#' When setting a unit of pounds please use one of the following keywords: +#' "lbs", "pounds", "lb". For example "1000s of lbs" would still be recognized #' as pounds. Do not set unit_label to the desired order of magnitude, rather the #' unit label reflected in the data. Please refer to the argument `scale_amount`. #' @@ -60,7 +60,7 @@ #' If the interactive and >1 module_name is found, user will select the #' module_name in the console. @seealso [filter_data()] #' @param scale_amount Number. A number to scale the y-axis values. If > 1, the -#' magnitude of the scale amount will be added to the unit label +#' magnitude of the scale amount will be added to the unit label #' (e.g. scale_amount = 1000 with a unit label of "1000s of lbs" will result #' in "thousands of 1000s of lbs") #' @@ -166,7 +166,7 @@ plot_spawning_biomass <- function( } else { if (grepl("lbs|pounds|lb", unit_label, ignore.case = TRUE)) lbs <- TRUE } - + spawning_biomass_label <- ifelse( relative, yes = "Relative spawning biomass", @@ -179,7 +179,7 @@ plot_spawning_biomass <- function( ) } ) - + if (relative) { if (nrow(prepared_data) == 0) { cli::cli_abort("No data found for relative biomass. Please check that your data contains a label for 'biomass_biomass_unfished'.") @@ -259,16 +259,16 @@ plot_spawning_biomass <- function( ) # calculate & export key quantities - export_kqs(rel.ssb.min, rel.ssb.max, dir=figures_dir) + export_kqs(rel.ssb.min, rel.ssb.max, dir = figures_dir) # Add key quantities to captions/alt text - insert_kqs(rel.ssb.min, rel.ssb.max, dir=figures_dir) + insert_kqs(rel.ssb.min, rel.ssb.max, dir = figures_dir) } else { ssb.min <- min(plot_data$estimate) |> round(digits = 3) ssb.max <- max(plot_data$estimate) |> round(digits = 3) - export_kqs(ssb.min, ssb.max, dir=figures_dir) - insert_kqs(ssb.min, ssb.max, dir=figures_dir) + export_kqs(ssb.min, ssb.max, dir = figures_dir) + insert_kqs(ssb.min, ssb.max, dir = figures_dir) } # Obtain relevant key quantities for captions/alt text @@ -283,7 +283,7 @@ plot_spawning_biomass <- function( ssb.units, ssb.start.year, ssb.end.year, - dir=figures_dir + dir = figures_dir ) # Add key quantities to captions/alt text @@ -292,7 +292,7 @@ plot_spawning_biomass <- function( ssb.units, ssb.start.year, ssb.end.year, - dir=figures_dir + dir = figures_dir ) create_rda( @@ -305,11 +305,11 @@ plot_spawning_biomass <- function( scale_amount = scale_amount ) } - + if (exists("selected_module")) { rm(selected_module, envir = .GlobalEnv) } - + # Output final plot final } diff --git a/R/plot_spr.R b/R/plot_spr.R index fada854f..dc000ab2 100644 --- a/R/plot_spr.R +++ b/R/plot_spr.R @@ -1,7 +1,7 @@ #' Plot spawning potential ratio (SPR) #' #' @inheritParams plot_spawning_biomass -#' +#' #' @param ylab String. Y-axis label to show. #' #' @returns A plot showing spawning potential ratio (SPR). @@ -48,13 +48,13 @@ plot_spr <- function( ... ) { check_data(dat) - + # Filter data for spr prepared_data <- filter_data( dat = dat, label_name = "spr", geom = geom, - #TODO: change this to era once stockplotr::example_data updated + # TODO: change this to era once stockplotr::example_data updated era = NULL, group = group, facet = facet, @@ -64,19 +64,19 @@ plot_spr <- function( ) |> # filter NA from year dplyr::filter(!is.na(year)) - - if(nrow(prepared_data)==0){ + + if (nrow(prepared_data) == 0) { # We could potentially make this more informative if we know the model type # by reporting the common MODULE used by other packages (e.g., DERIVED_QUANTITIES # for SS3 models, or t.series for BAM models). cli::cli_alert(glue::glue("There is no data available to be plotted. Try selecting a different module.")) } - + # Process data processed_data <- process_data( dat = prepared_data, group = group, - facet = facet# + facet = facet # # method = "sum" ) prepared_data <- processed_data[[1]] @@ -94,7 +94,7 @@ plot_spr <- function( if (!is.null(group)) { if (group %notin% colnames(prepared_data)) group <- NULL } - + # inital base plot plt <- plot_timeseries( dat = prepared_data, @@ -105,10 +105,14 @@ plot_spr <- function( facet = facet, ... ) + - ggplot2::geom_hline(yintercept = 1, - color = "grey") + - ggplot2::geom_hline(yintercept = 0, - color = "grey") + + ggplot2::geom_hline( + yintercept = 1, + color = "grey" + ) + + ggplot2::geom_hline( + yintercept = 0, + color = "grey" + ) + add_reference_line( dat = dat, ref_line = ref_line, @@ -116,7 +120,7 @@ plot_spr <- function( scale_amount = 1 ) + theme_noaa() - + if (length(unique(prepared_data$group_var)) == 1) { plt <- plt + ggplot2::theme(legend.position = "none") @@ -126,20 +130,20 @@ plot_spr <- function( if (make_rda) { # TODO: Update caption, alt text, and quantities once plot is finalized # Obtain relevant key quantities for captions/alt text - + spr.start.year <- min(prepared_data$year) spr.end.year <- max(prepared_data$year) spr.min <- min(prepared_data$estimate) |> round(digits = 3) spr.max <- max(prepared_data$estimate) |> round(digits = 3) spr.ref.pt <- as.character(ref_line) - + # calculate & export key quantities export_kqs( spr.start.year, spr.end.year, spr.min, spr.ref.pt, - dir=figures_dir + dir = figures_dir ) # Add key quantities to captions/alt text @@ -149,7 +153,7 @@ plot_spr <- function( spr.min, spr.max, spr.ref.pt, - dir=figures_dir + dir = figures_dir ) create_rda( diff --git a/R/plot_stock_recruitment.R b/R/plot_stock_recruitment.R index 514e8d1c..e0debed2 100644 --- a/R/plot_stock_recruitment.R +++ b/R/plot_stock_recruitment.R @@ -97,7 +97,7 @@ plot_stock_recruitment <- function( # Extract spawning biomass sb <- filter_data( dat = dat |> - dplyr::filter(!is.na(year)), + dplyr::filter(!is.na(year)), label_name = "spawning biomass", geom = "point", era = era, @@ -126,7 +126,7 @@ plot_stock_recruitment <- function( if (is.null(recruitment_label)) { recruitment_label <- unique(recruitment$unit) recruitment_label <- recruitment_label[!is.na(recruitment_label)] - if (is.na(recruitment_label) || is.null(recruitment_label)) { + if (is.na(recruitment_label) || is.null(recruitment_label)) { cli::cli_alert_warning("No unit label found in the data. Please provide a unit label using the 'recruitment_label' argument.") recruitment_label <- "" } @@ -211,7 +211,7 @@ plot_stock_recruitment <- function( recruitment.min, recruitment.max, recruitment.units, - dir=figures_dir + dir = figures_dir ) # Add key quantities to captions/alt text @@ -223,7 +223,7 @@ plot_stock_recruitment <- function( recruitment.min, recruitment.max, recruitment.units, - dir=figures_dir + dir = figures_dir ) create_rda( @@ -235,11 +235,11 @@ plot_stock_recruitment <- function( dir = figures_dir ) } - + if (exists("selected_module")) { rm(selected_module, envir = .GlobalEnv) } - + final + ggplot2::scale_x_continuous( labels = scales::label_comma() diff --git a/R/save_all_plots.R b/R/save_all_plots.R index c530b094..0c7b1ac3 100644 --- a/R/save_all_plots.R +++ b/R/save_all_plots.R @@ -1,8 +1,8 @@ #' Export all figures and tables #' #' Export all figures and tables to Rda files within one function. -#' This primary purpose of this function is to quickly export all -#' available figures and tables. We recommend running individual +#' This primary purpose of this function is to quickly export all +#' available figures and tables. We recommend running individual #' plotting functions for greater customization of figures and tables. #' #' @inheritParams plot_spawning_biomass @@ -11,32 +11,32 @@ #' #' Default: the working directory (`getwd()`) #' -#' @param plot_recruitment_options List. List object of parameter values to pass +#' @param plot_recruitment_options List. List object of parameter values to pass #' directly to the `plot_recruitment` function. All default parameters for the -#' `plot_recruitment` function, except for `dat`, can be overridden with this list -#' object. -#' +#' `plot_recruitment` function, except for `dat`, can be overridden with this list +#' object. +#' #' Default: list(module = "TIME_SERIES") #' -#' @param plot_natural_mortality_options List. List object of parameter values to pass +#' @param plot_natural_mortality_options List. List object of parameter values to pass #' directly to the `plot_natural_mortality_options` function. All default parameters for the -#' `plot_natural_mortality_options` function, except for `dat`, can be overridden with this list -#' object. -#' +#' `plot_natural_mortality_options` function, except for `dat`, can be overridden with this list +#' object. +#' #' Default: list(module = "Natural_Mortality") -#' -#' @param table_total_catch_options List. List object of parameter values to pass +#' +#' @param table_total_catch_options List. List object of parameter values to pass #' directly to the `table_total_catch_options` function. All default parameters for the -#' `table_total_catch_options` function, except for `dat`, can be overridden with this list -#' object. -#' +#' `table_total_catch_options` function, except for `dat`, can be overridden with this list +#' object. +#' #' Default: list(module = "TIME_SERIES") -#' +#' #' ... Additional list objects of parameter values to pass directly to corresponding #' plot or table functions. Parameter names should follow the naming convention -#' `{function_name}_options`. All default parameters, except for `dat`, of this function +#' `{function_name}_options`. All default parameters, except for `dat`, of this function #' can be overridden with this list object. See example. -#' +#' #' @returns Rda files for each figure/table. #' #' @seealso [convert_output()], [create_rda()] @@ -73,7 +73,7 @@ #' ), #' plot_abundance_at_age_options = list( #' scale_amount = 1, # custom scale for abundance-at-age plot -#' proportional = FALSE # don't proportionalize abundance-at-age +#' proportional = FALSE # don't proportionalize abundance-at-age #' ), #' plot_spr_options = list( #' ylab = "Fishing Intensity (1-SPR)/(1-SPR_ref)" # custom Y label for SPR plot @@ -92,16 +92,16 @@ save_all_plots <- function( # no standard default modules plot_recruitment_options = list(module = "TIME_SERIES"), plot_natural_mortality_options = list(module = "Natural_Mortality"), - table_total_catch_options = list( module = "TIME_SERIES"), + table_total_catch_options = list(module = "TIME_SERIES"), # All other functions can be modified with appropriate *_options # parameter lists. ... ) { check_data(dat) - all_params <- as.list(environment(), all=TRUE) + all_params <- as.list(environment(), all = TRUE) make_rda <- TRUE - + cli::cli_h1("Starting export of figures and tables") # These arguments are used by every plot and table @@ -123,38 +123,39 @@ save_all_plots <- function( # plottab_functions <- sub("\\.[^\\.]*$", "", plottab_function_files) all_functions <- ls(getNamespace("stockplotr")) all_plottab_functions <- all_functions[grepl("plot_|table_", all_functions)] - plottab_functions <- all_plottab_functions[!(grepl(paste0(helper_functions, collapse="|"), all_plottab_functions))] + plottab_functions <- all_plottab_functions[!(grepl(paste0(helper_functions, collapse = "|"), all_plottab_functions))] - for(i in seq_along(plottab_functions)){ - func_name <- plottab_functions[i] - func_specific_args <- all_params[paste0(func_name,"_options")][[1]] + for (i in seq_along(plottab_functions)) { + func_name <- plottab_functions[i] + func_specific_args <- all_params[paste0(func_name, "_options")][[1]] - func_pars <- default_args - if(!is.null(func_specific_args)) - func_pars <- c(default_args, func_specific_args) + func_pars <- default_args + if (!is.null(func_specific_args)) { + func_pars <- c(default_args, func_specific_args) + } - # switch from "figures_dir" to "tables_dir" dynamically - if(grepl("table",func_name)){ - names(func_pars)[which(names(func_pars)=="figures_dir")] <- "tables_dir" - } + # switch from "figures_dir" to "tables_dir" dynamically + if (grepl("table", func_name)) { + names(func_pars)[which(names(func_pars) == "figures_dir")] <- "tables_dir" + } - cli::cli_alert_info("Exporting: {func_name} figure") - tryCatch( - { - suppressMessages( - do.call(func_name, func_pars) # Execute plotting/table function - ) - }, - error = function(e) { - cli::cli_alert_danger("Failed to execute: {func_name}.") - cli::cli_alert("Tip: check that your arguments are correct.") - for(a in seq_along(func_specific_args)){ - arg_name = names(func_specific_args)[a] - arg_value = as.character(func_specific_args[a]) - cli::cli_li("{arg_name} = {arg_value}") - } - print(e) + cli::cli_alert_info("Exporting: {func_name} figure") + tryCatch( + { + suppressMessages( + do.call(func_name, func_pars) # Execute plotting/table function + ) + }, + error = function(e) { + cli::cli_alert_danger("Failed to execute: {func_name}.") + cli::cli_alert("Tip: check that your arguments are correct.") + for (a in seq_along(func_specific_args)) { + arg_name <- names(func_specific_args)[a] + arg_value <- as.character(func_specific_args[a]) + cli::cli_li("{arg_name} = {arg_value}") } - ) + print(e) + } + ) } } diff --git a/R/table_biomass_abundance_catch.R b/R/table_biomass_abundance_catch.R index 1b7a9f8c..a29ddfa3 100644 --- a/R/table_biomass_abundance_catch.R +++ b/R/table_biomass_abundance_catch.R @@ -77,7 +77,7 @@ table_biomass_abundance_catch <- function( "^abundance" = "abundance", "catch$|landings_observed" = "catch" ) - + biomass_abundance_catch.biomass.units <- NA biomass_abundance_catch.abundance.units <- NA biomass_abundance_catch.catch.units <- NA @@ -97,7 +97,7 @@ table_biomass_abundance_catch <- function( module = module, scale_amount = 1, interactive = interactive - ) + ) uncertainty_label <- ifelse( is.na(unique(filtered_data$uncertainty_label)), @@ -156,14 +156,16 @@ table_biomass_abundance_catch <- function( data <- processed_data[[1]] group <- processed_data[[2]] - + # Labs # get unit label for biomass, abundance, and catch if not NULL unit_name <- named_vec[grep(x, names(named_vec), fixed = TRUE)][[1]] if (is.null(get(paste0(unit_name, "_label")))) { unit_label <- filtered_data |> - dplyr::filter(grepl(x, unit_name), - !is.na(.data$unit)) |> + dplyr::filter( + grepl(x, unit_name), + !is.na(.data$unit) + ) |> dplyr::pull("unit") |> unique() if (is.na(unit_label) || length(unit_label) == 0) { @@ -173,7 +175,7 @@ table_biomass_abundance_catch <- function( } else { unit_label <- get(paste0(unit_name, "_label")) } - + # Obtain relevant key quantities for captions/alt text idx <- match(x, names(named_vec)[1:3]) if (identical(idx, 1L)) biomass_abundance_catch.biomass.units <<- unit_label @@ -198,7 +200,7 @@ table_biomass_abundance_catch <- function( gt::gt() final <- theme_table(combine_data) - + # export figure to rda if argument = T if (make_rda == TRUE) { # calculate & export key quantities @@ -206,7 +208,7 @@ table_biomass_abundance_catch <- function( biomass_abundance_catch.biomass.units, biomass_abundance_catch.abundance.units, biomass_abundance_catch.catch.units, - dir=tables_dir + dir = tables_dir ) # Add key quantities to captions/alt text @@ -214,7 +216,7 @@ table_biomass_abundance_catch <- function( biomass_abundance_catch.biomass.units, biomass_abundance_catch.abundance.units, biomass_abundance_catch.catch.units, - dir=tables_dir + dir = tables_dir ) create_rda( @@ -230,10 +232,10 @@ table_biomass_abundance_catch <- function( } rm(biomass_abundance_catch.biomass.units, biomass_abundance_catch.abundance.units, biomass_abundance_catch.catch.units) - + if (exists("selected_module")) { rm(selected_module, envir = .GlobalEnv) } - + final } diff --git a/R/table_index.R b/R/table_index.R index 5c21a8ac..9e41058c 100644 --- a/R/table_index.R +++ b/R/table_index.R @@ -150,17 +150,17 @@ table_index <- function( ) } - create_rda( - object = final, - # get name of function and remove "table_" from it - topic_label = gsub("table_", "", utils::tail(as.character(sys.call()[[1]]), n = 1)), - fig_or_table = "table", - dat = dat, - dir = tables_dir, - scale_amount = 1, - table_df = final - ) + create_rda( + object = final, + # get name of function and remove "table_" from it + topic_label = gsub("table_", "", utils::tail(as.character(sys.call()[[1]]), n = 1)), + fig_or_table = "table", + dat = dat, + dir = tables_dir, + scale_amount = 1, + table_df = final + ) } - + final } diff --git a/R/table_landings.R b/R/table_landings.R index 7f711c9a..cf776486 100644 --- a/R/table_landings.R +++ b/R/table_landings.R @@ -43,7 +43,8 @@ #' #' @examples #' table_landings(stockplotr::example_data, -#' interactive = FALSE) +#' interactive = FALSE +#' ) #' #' table_landings( #' stockplotr::example_data, @@ -118,7 +119,7 @@ table_landings <- function( table_data <- table_data_info[[1]] indexed_vars <- table_data_info[[2]] id_col_vals <- table_data_info[[3]] - + if (is.null(unit_label)) { # remove fleet names from table_data colnames fleet_pattern <- paste0("_(", paste(fleets, collapse = "|"), ")$") @@ -133,7 +134,7 @@ table_landings <- function( unit_label <- "" } } - + # set unit label if scaled landings_label <- label_magnitude( label = "", @@ -141,7 +142,7 @@ table_landings <- function( scale_amount = scale_amount ) - # TODO: add check if there is a landings column for every error column -- if not remove the error (can keep landings) + # TODO: add check if there is a landings column for every error column -- if not remove the error (can keep landings) # merge error and landings columns and rename final_tab <- merge_error( @@ -159,13 +160,13 @@ table_landings <- function( if (make_rda == TRUE) { # Obtain relevant key quantities for captions/alt text landings.units <- unit_label - + # calculate & export key quantities export_kqs(landings.units, dir = tables_dir) - + # Add key quantities to captions/alt text insert_kqs(landings.units, dir = tables_dir) - + create_rda( object = final, # get name of function and remove "table_" from it @@ -177,10 +178,10 @@ table_landings <- function( table_df = final ) } - + if (exists("selected_module")) { rm(selected_module, envir = .GlobalEnv) } - + final } diff --git a/R/table_projections.R b/R/table_projections.R index 37e0a299..b18c429a 100644 --- a/R/table_projections.R +++ b/R/table_projections.R @@ -23,14 +23,14 @@ #' interactive = FALSE, #' module = "DERIVED_QUANTITIES" #' ) -#' +#' #' table_projections( -#' dat = stockplotr::example_data, -#' interactive = FALSE, -#' catch_label = "kg", -#' spawning_biomass_label = "kg", -#' module = c(NULL, "DERIVED_QUANTITIES", "DERIVED_QUANTITIES") -#' ) +#' dat = stockplotr::example_data, +#' interactive = FALSE, +#' catch_label = "kg", +#' spawning_biomass_label = "kg", +#' module = c(NULL, "DERIVED_QUANTITIES", "DERIVED_QUANTITIES") +#' ) table_projections <- function( dat, catch_label = NULL, @@ -52,13 +52,13 @@ table_projections <- function( # if ("landings" %notin% names(catch_lab)) { # catch_label <- c(catch_label, "landings_weight" = catch_label[["catch"]]) # } - + named_vec <- c( "catch" = catch_lab, "spawning_biomass" = "spawning_biomass", "fishing_mortality" = "fishing_mortality" ) - + # iterate through 3 label names lab_list <- purrr::map( names(named_vec), @@ -98,15 +98,17 @@ table_projections <- function( # Labs # get unit labels if not NULL unit_name <- named_vec[grep(x, names(named_vec), fixed = TRUE)][[1]] - + if (x == "fishing_mortality") { fishing_mortality_label <- "" unit_label <- fishing_mortality_label unit_name <- "fishing_mortality" } else if (is.null(get(paste0(unit_name, "_label")))) { unit_label <- filtered_data |> - dplyr::filter(grepl(x, unit_name), - !is.na(unit)) |> + dplyr::filter( + grepl(x, unit_name), + !is.na(unit) + ) |> dplyr::pull(unit) |> unique() if (is.na(unit_label) || length(unit_label) == 0) { @@ -116,7 +118,7 @@ table_projections <- function( } else { unit_label <- get(paste0(unit_name, "_label")) } - + # merge data with uncertainty and unit labels merge_error( table_data = data, @@ -131,7 +133,7 @@ table_projections <- function( purrr::compact(lab_list), dplyr::full_join, by = c("Year") - ) |> + ) |> gt::gt() final <- theme_table(combine_data) @@ -165,7 +167,7 @@ table_projections <- function( table_df = final$`_data` ) } - + if (exists("selected_module")) { rm(selected_module, envir = .GlobalEnv) } diff --git a/R/table_total_catch.R b/R/table_total_catch.R index c9779324..7965aa7a 100644 --- a/R/table_total_catch.R +++ b/R/table_total_catch.R @@ -50,13 +50,15 @@ table_total_catch <- function( tables_dir = getwd() ) { check_data(dat) - + # Filter data for catch prepared_data <- filter_data( dat = dat |> - dplyr::filter(!is.na(year), - !is.na(estimate), - label %in% c("catch_retained", "catch_dead", "catch_selected", "catch")), + dplyr::filter( + !is.na(year), + !is.na(estimate), + label %in% c("catch_retained", "catch_dead", "catch_selected", "catch") + ), label_name = "^catch", geom = "line", era = era, @@ -69,17 +71,17 @@ table_total_catch <- function( if (nrow(prepared_data) == 0 | unique(stringr::str_detect(prepared_data$label, "catchability"))) { cli::cli_abort("No catch data found.") } - + # Labs if (is.null(unit_label)) { unit_label <- unique(prepared_data$unit) unit_label <- unit_label[!is.na(unit_label)] - if (is.na(unit_label) || is.null(unit_label) || length(unit_label) == 0) { + if (is.na(unit_label) || is.null(unit_label) || length(unit_label) == 0) { cli::cli_alert_warning("No unit label found in the data. Please provide a unit label using the 'unit_label' argument.") unit_label <- "" } } - + # set unit label if scaled catch_label <- label_magnitude( label = "", @@ -196,10 +198,10 @@ table_total_catch <- function( table_df = final ) } - + if (exists("selected_module")) { rm(selected_module, envir = .GlobalEnv) } - + final } diff --git a/R/utils_plot.R b/R/utils_plot.R index 691b52fd..086eb490 100644 --- a/R/utils_plot.R +++ b/R/utils_plot.R @@ -568,32 +568,32 @@ reference_line <- function( ref_line_val <- ref_line[[1]] reference <- names(ref_line) - switch(direction, + switch(direction, "h" = { - list( - # Add geom for ref line - ggplot2::geom_hline( - data = data.frame(yintercept = ref_line_val, model = model_name, group_var = "1"), - ggplot2::aes( - yintercept = ref_line_val / scale_amount, - color = interaction(model, group_var) # model - ), - linetype = "dashed", - show.legend = FALSE + list( + # Add geom for ref line + ggplot2::geom_hline( + data = data.frame(yintercept = ref_line_val, model = model_name, group_var = "1"), + ggplot2::aes( + yintercept = ref_line_val / scale_amount, + color = interaction(model, group_var) # model ), - # add line annotation - ggplot2::annotate( - geom = "text", - # TODO: need to change this for general process - x = -Inf, - y = ref_line_val / scale_amount, - label = glue::glue("{reference}"), # glue::glue("{stringr::str_replace_all(label_name, '_', '~')}[{reference}]"), # list(bquote(label_name[.(reference)])), - parse = TRUE, - hjust = -0.05, # slight offset so text doesn't hit border - vjust = -0.5 # , #slightly above line - # size = 5 # this is not foolproof - ) + linetype = "dashed", + show.legend = FALSE + ), + # add line annotation + ggplot2::annotate( + geom = "text", + # TODO: need to change this for general process + x = -Inf, + y = ref_line_val / scale_amount, + label = glue::glue("{reference}"), # glue::glue("{stringr::str_replace_all(label_name, '_', '~')}[{reference}]"), # list(bquote(label_name[.(reference)])), + parse = TRUE, + hjust = -0.05, # slight offset so text doesn't hit border + vjust = -0.5 # , #slightly above line + # size = 5 # this is not foolproof ) + ) }, "v" = { list( @@ -622,7 +622,6 @@ reference_line <- function( ) } ) - } #------------------------------------------------------------------------------ diff --git a/R/utils_rda.R b/R/utils_rda.R index 8ece629c..cd15e956 100644 --- a/R/utils_rda.R +++ b/R/utils_rda.R @@ -376,9 +376,9 @@ fill_in_kqs <- function(df, ...) { #' #' @param ... Key quantities whose values should be added to the #' exported "key_quantities.csv" -#' +#' #' @param dir String directory to write "key_quantities.csv" to. -#' +#' #' DEFAULT: getwd() #' #' @returns Exports a file based on key quantities template, with values @@ -391,21 +391,22 @@ fill_in_kqs <- function(df, ...) { #' F.min, #' F.max, #' ) -#' +#' #' export_kqs( #' F.min, #' F.max, #' dir = fs::path(getwd(), "plots") #' ) #' } -export_kqs <- function(..., dir=getwd()) { +export_kqs <- function(..., dir = getwd()) { # Open new or existing key quantities csv if (file.exists(fs::path(dir, "key_quantities.csv"))) { cli::cli_alert_info("Key quantities text file (key_quantities.csv) exists. Newly calculated key quantities will be added to it.", wrap = TRUE) kqs <- utils::read.csv(file.path(dir, "key_quantities.csv")) } else { - if(!dir.exists(dir)) + if (!dir.exists(dir)) { dir.create(dir) + } kqs <- utils::read.csv( system.file("resources", "key_quantity_template.csv", package = "stockplotr") @@ -429,9 +430,9 @@ export_kqs <- function(..., dir=getwd()) { #' #' @param ... Key quantities whose values should be added to the #' exported "captions_alt_text.csv" -#' +#' #' @param dir String directory to write "captions_alt_text.csv" to. -#' +#' #' DEFAULT: getwd() #' #' @returns Exports a file ("captions_alt_text.csv") containing captions @@ -445,14 +446,14 @@ export_kqs <- function(..., dir=getwd()) { #' F.max #' ) #' } -insert_kqs <- function(..., dir=getwd()) { +insert_kqs <- function(..., dir = getwd()) { if (file.exists(fs::path(dir, "captions_alt_text.csv"))) { cli::cli_alert_info("Captions/alternative text file (captions_alt_text.csv) exists. Newly calculated key quantities will be added to it.", wrap = TRUE) caps_alttext <- utils::read.csv(fs::path(dir, "captions_alt_text.csv")) } else { - - if(!dir.exists(dir)) + if (!dir.exists(dir)) { dir.create(dir) + } caps_alttext <- utils::read.csv( system.file("resources", "captions_alt_text_template.csv", package = "stockplotr") @@ -540,9 +541,9 @@ insert_kqs <- function(..., dir=getwd()) { #' @param object Object. Table or plot object #' @param topic_label String. Name of the object #' @param fig_or_table String. Indicates whether the object is a "table" or "figure" -#' +#' #' Options: "figure" or "table" -#' +#' #' @param dat Data frame. Data which will fill in captions and #' alternative text for the object #' @param dir Path. Directory to where the rda will be saved diff --git a/data-raw/DATASET_RCEATTLE.R b/data-raw/DATASET_RCEATTLE.R index 7e1fada2..ba88dbca 100644 --- a/data-raw/DATASET_RCEATTLE.R +++ b/data-raw/DATASET_RCEATTLE.R @@ -5,7 +5,7 @@ remotes::install_github("afsc-assessments/Rceattle") # library(Rceattle) # library(readxl) GOApollock <- Rceattle::GOApollock -GOApollock$styr = 1977 # The SAFE model starts at 1970, so change styr to 1970 to run the full time series model (data is in there). I start them all at 1977 because thats the years with overlap. +GOApollock$styr <- 1977 # The SAFE model starts at 1970, so change styr to 1970 to run the full time series model (data is in there). I start them all at 1977 because thats the years with overlap. pollock_model <- Rceattle::fit_mod( data_list = GOApollock, inits = NULL, # Initial parameters = 0 @@ -14,7 +14,8 @@ pollock_model <- Rceattle::fit_mod( random_rec = FALSE, # No random recruitment msmMode = 0, # 0 = Single species mode, 1 = MSVPA multi-species mode verbose = 1, # Silence optimization output - phase = TRUE) # Use default phasing + phase = TRUE +) # Use default phasing # Install stockplotr pak::local_install(".") # Convert output diff --git a/man/save_all_plots.Rd b/man/save_all_plots.Rd index ef04c037..b577e9c7 100644 --- a/man/save_all_plots.Rd +++ b/man/save_all_plots.Rd @@ -97,7 +97,7 @@ save_all_plots( ), plot_abundance_at_age_options = list( scale_amount = 1, # custom scale for abundance-at-age plot - proportional = FALSE # don't proportionalize abundance-at-age + proportional = FALSE # don't proportionalize abundance-at-age ), plot_spr_options = list( ylab = "Fishing Intensity (1-SPR)/(1-SPR_ref)" # custom Y label for SPR plot diff --git a/man/table_landings.Rd b/man/table_landings.Rd index 309b4161..1b78e1f8 100644 --- a/man/table_landings.Rd +++ b/man/table_landings.Rd @@ -106,7 +106,8 @@ containing a gt-based table, caption, and LaTeX-based table. } \examples{ table_landings(stockplotr::example_data, - interactive = FALSE) + interactive = FALSE +) table_landings( stockplotr::example_data, diff --git a/man/table_projections.Rd b/man/table_projections.Rd index 6a4c4fc5..b3e3e049 100644 --- a/man/table_projections.Rd +++ b/man/table_projections.Rd @@ -70,10 +70,10 @@ table_projections( ) table_projections( - dat = stockplotr::example_data, - interactive = FALSE, - catch_label = "kg", - spawning_biomass_label = "kg", - module = c(NULL, "DERIVED_QUANTITIES", "DERIVED_QUANTITIES") - ) + dat = stockplotr::example_data, + interactive = FALSE, + catch_label = "kg", + spawning_biomass_label = "kg", + module = c(NULL, "DERIVED_QUANTITIES", "DERIVED_QUANTITIES") +) } diff --git a/tests/testthat/helper-test_functions.R b/tests/testthat/helper-test_functions.R index 78688e07..7b35a04e 100644 --- a/tests/testthat/helper-test_functions.R +++ b/tests/testthat/helper-test_functions.R @@ -1,32 +1,34 @@ #' Check for the existence and remove .rda files from test environment -#' +#' #' Checks for the existence of `dir` and `filename` as well as the -#' existence of "captions_alt_text.csv" and "key_quantities.csv". -#' Files are removed upon completion of checks. -#' +#' existence of "captions_alt_text.csv" and "key_quantities.csv". +#' Files are removed upon completion of checks. +#' #' For testing only. -#' +#' #' @param filename String. filename of figure/table .rda file #' @param dir String. directory where filename exists #' @param figs_or_tables String. whether check for a "figures" or "tables" internal directory -#' +#' #' DEFAULT: "figures" -#' -check_and_remove_tmp_files <- function(filename, dir=fs::path(getwd()), figs_or_tables="figures"){ - # expect that both figures dir and the abundance_at_age_figure.rda file exist - expect_true(dir.exists(dir)) # this check needs to exist in case save dir isnt getwd() - expect_true(dir.exists(fs::path(dir, figs_or_tables))) - expect_true(file.exists(fs::path(dir, figs_or_tables, filename))) +#' +check_and_remove_tmp_files <- function(filename, dir = fs::path(getwd()), figs_or_tables = "figures") { + # expect that both figures dir and the abundance_at_age_figure.rda file exist + expect_true(dir.exists(dir)) # this check needs to exist in case save dir isnt getwd() + expect_true(dir.exists(fs::path(dir, figs_or_tables))) + expect_true(file.exists(fs::path(dir, figs_or_tables, filename))) - # erase temporary testing files - captions_file <- fs::path(dir, "captions_alt_text.csv") - keyquant_file <- fs::path(dir, "key_quantities.csv") + # erase temporary testing files + captions_file <- fs::path(dir, "captions_alt_text.csv") + keyquant_file <- fs::path(dir, "key_quantities.csv") - if(fs::file_exists(captions_file)) - fs::file_delete(captions_file) + if (fs::file_exists(captions_file)) { + fs::file_delete(captions_file) + } - if(fs::file_exists(keyquant_file)) - fs::file_delete(keyquant_file) + if (fs::file_exists(keyquant_file)) { + fs::file_delete(keyquant_file) + } - unlink(fs::path(dir, figs_or_tables), recursive = T) + unlink(fs::path(dir, figs_or_tables), recursive = T) } diff --git a/tests/testthat/test-check_data.R b/tests/testthat/test-check_data.R index 8884b3c3..16060d09 100644 --- a/tests/testthat/test-check_data.R +++ b/tests/testthat/test-check_data.R @@ -28,8 +28,10 @@ test_that("check_data rejects lists containing invalid elements", { "biomass", list(label = "biomass", estimate = 1), list(dat), - matrix(c("biomass", "1"), nrow = 1, - dimnames = list(NULL, c("label", "estimate"))), + matrix(c("biomass", "1"), + nrow = 1, + dimnames = list(NULL, c("label", "estimate")) + ), data.frame(), data.frame(label = "biomass"), data.frame(estimate = 1) @@ -53,8 +55,10 @@ test_that("check_data rejects objects without the required structure", { 1, "biomass", list(label = "biomass", estimate = 1), - matrix(c("biomass", "1"), nrow = 1, - dimnames = list(NULL, c("label", "estimate"))), + matrix(c("biomass", "1"), + nrow = 1, + dimnames = list(NULL, c("label", "estimate")) + ), data.frame(), data.frame(label = "biomass"), data.frame(estimate = 1) diff --git a/tests/testthat/test-convert_output.R b/tests/testthat/test-convert_output.R index 51d111c5..20ea9aaf 100644 --- a/tests/testthat/test-convert_output.R +++ b/tests/testthat/test-convert_output.R @@ -14,13 +14,13 @@ test_that("convert_output works for SS3", { "BigSkate_2019" ) - models_to_test <- all_models[grepl(paste0(model_names, collapse="|"), all_models)] + models_to_test <- all_models[grepl(paste0(model_names, collapse = "|"), all_models)] # Loop through each model directory and check convert_output function for (i in seq_along(models_to_test)) { # Ensure no errors occur while converting SS3 output expect_no_error(result <- convert_output( - file = r4ss::SS_output(file.path(models_to_test[i]))#file.path(models_to_test[i], "Report.sso") + file = r4ss::SS_output(file.path(models_to_test[i])) # file.path(models_to_test[i], "Report.sso") )) # Check that the result has exactly 35 columns diff --git a/tests/testthat/test-export_rda.R b/tests/testthat/test-export_rda.R index 8f2481dc..1bd0ae7b 100644 --- a/tests/testthat/test-export_rda.R +++ b/tests/testthat/test-export_rda.R @@ -85,46 +85,46 @@ test_that("export_rda works for tables", { test_that("export_rda to custom directory location", { - topic_label <- "biomass" - fig_or_table <- "figure" - - B.min <- 100 - B.max <- 200 - - custom_dir <- fs::path(getwd(), "tests-export_rda") - - # add KQs to caps/alt text csv - insert_kqs(B.min, B.max, dir=custom_dir) - - # extract this plot's caption and alt text - caps_alttext <- extract_caps_alttext( - topic_label = topic_label, - fig_or_table = fig_or_table, - dir = custom_dir - ) - - # make a simple plot - # library(ggplot2) - final <- ggplot2::ggplot(Orange, ggplot2::aes(circumference, age)) + - ggplot2::geom_point() - - # export rda - export_rda( - object = final, - caps_alttext = caps_alttext, - figures_tables_dir = custom_dir, - topic_label = topic_label, - fig_or_table = fig_or_table - ) - - # expect that both figures dir and the biomass_figure.rda file exist - expect_true(dir.exists(fs::path(custom_dir, "figures"))) - expect_true(file.exists(fs::path( - custom_dir, "figures", "biomass_figure.rda" - ))) - - # erase temporary testing files - file.remove(fs::path(custom_dir, "captions_alt_text.csv")) - # file.remove(fs::path(getwd(), "key_quantities.csv")) # file is not made in this test - unlink(fs::path(custom_dir, "figures"), recursive = T) + topic_label <- "biomass" + fig_or_table <- "figure" + + B.min <- 100 + B.max <- 200 + + custom_dir <- fs::path(getwd(), "tests-export_rda") + + # add KQs to caps/alt text csv + insert_kqs(B.min, B.max, dir = custom_dir) + + # extract this plot's caption and alt text + caps_alttext <- extract_caps_alttext( + topic_label = topic_label, + fig_or_table = fig_or_table, + dir = custom_dir + ) + + # make a simple plot + # library(ggplot2) + final <- ggplot2::ggplot(Orange, ggplot2::aes(circumference, age)) + + ggplot2::geom_point() + + # export rda + export_rda( + object = final, + caps_alttext = caps_alttext, + figures_tables_dir = custom_dir, + topic_label = topic_label, + fig_or_table = fig_or_table + ) + + # expect that both figures dir and the biomass_figure.rda file exist + expect_true(dir.exists(fs::path(custom_dir, "figures"))) + expect_true(file.exists(fs::path( + custom_dir, "figures", "biomass_figure.rda" + ))) + + # erase temporary testing files + file.remove(fs::path(custom_dir, "captions_alt_text.csv")) + # file.remove(fs::path(getwd(), "key_quantities.csv")) # file is not made in this test + unlink(fs::path(custom_dir, "figures"), recursive = T) }) diff --git a/tests/testthat/test-extract_sis_data.R b/tests/testthat/test-extract_sis_data.R index 45641925..08238009 100644 --- a/tests/testthat/test-extract_sis_data.R +++ b/tests/testthat/test-extract_sis_data.R @@ -1,40 +1,43 @@ test_that("extract_sis_data() runs with all possible rdas present", { - savedir <- fs::path(getwd(), "test-extract_sis_data") - if(!dir.exists(savedir)) + if (!dir.exists(savedir)) { dir.create(savedir) + } - save_all_plots(stockplotr::example_data, figures_tables_dir=savedir) + save_all_plots(stockplotr::example_data, figures_tables_dir = savedir) # table_total_catch(stockplotr::example_data, # module = "TIME_SERIES", # interactive = FALSE, # make_rda = TRUE) files <- c( - fs::path(savedir, "figures", - c("biomass_figure.rda", "spawning_biomass_figure.rda", "abundance_at_age_figure.rda", "fishing_mortality_figure.rda", "index_figure.rda") - ), - fs::path(savedir, "tables", - "total_catch_table.rda") + fs::path( + savedir, "figures", + c("biomass_figure.rda", "spawning_biomass_figure.rda", "abundance_at_age_figure.rda", "fishing_mortality_figure.rda", "index_figure.rda") + ), + fs::path( + savedir, "tables", + "total_catch_table.rda" + ) ) expect_true(all(file.exists(files))) - extract_sis_data(sis_data_dir=savedir, key_quantities_dir=savedir, figures_tables_dir=savedir) + extract_sis_data(sis_data_dir = savedir, key_quantities_dir = savedir, figures_tables_dir = savedir) # erase temporary testing files - unlink(fs::path(savedir), recursive=TRUE) + unlink(fs::path(savedir), recursive = TRUE) }) test_that("extract_sis_data() runs with some of all possible rdas present", { - savedir <- fs::path(getwd(), "test-extract_sis_data") - if(!dir.exists(savedir)) + if (!dir.exists(savedir)) { dir.create(savedir) + } - plot_biomass(stockplotr::example_data, module = "TIME_SERIES", interactive = FALSE, make_rda = TRUE, figures_dir=savedir) - plot_fishing_mortality(stockplotr::example_data, interactive = FALSE, make_rda = TRUE, figures_dir=savedir) - expect_no_error(extract_sis_data(sis_data_dir=savedir, key_quantities_dir=savedir, figures_tables_dir=savedir)) + plot_biomass(stockplotr::example_data, module = "TIME_SERIES", interactive = FALSE, make_rda = TRUE, figures_dir = savedir) + plot_fishing_mortality(stockplotr::example_data, interactive = FALSE, make_rda = TRUE, figures_dir = savedir) + expect_no_error(extract_sis_data(sis_data_dir = savedir, key_quantities_dir = savedir, figures_tables_dir = savedir)) # test that extract_sis_data() exports csvs expect_true(file.exists(fs::path(savedir, "sis_assmt_template.csv"))) @@ -46,10 +49,11 @@ test_that("extract_sis_data() runs with some of all possible rdas present", { test_that("extract_sis_data() fails with no rdas present", { savedir <- fs::path(getwd(), "test-extract_sis_data") - if(!dir.exists(savedir)) + if (!dir.exists(savedir)) { dir.create(savedir) - - expect_error(extract_sis_data(sis_data_dir=savedir, key_quantities_dir=savedir, figures_tables_dir=savedir)) + } + + expect_error(extract_sis_data(sis_data_dir = savedir, key_quantities_dir = savedir, figures_tables_dir = savedir)) # erase temporary testing files unlink(fs::path(savedir), recursive = TRUE) diff --git a/tests/testthat/test-plot_natural_mortality.R b/tests/testthat/test-plot_natural_mortality.R index fb241f72..59cd88a7 100644 --- a/tests/testthat/test-plot_natural_mortality.R +++ b/tests/testthat/test-plot_natural_mortality.R @@ -2,7 +2,7 @@ test_that("plot_natural_mortality generate without errors", { # expect error-free plot with minimal arguments expect_no_error( plot_natural_mortality( - stockplotr::example_data, + stockplotr::example_data, module = "Natural_Mortality", interactive = FALSE ) diff --git a/tests/testthat/test-plot_recruitment.R b/tests/testthat/test-plot_recruitment.R index 1cd652e4..979f26fb 100644 --- a/tests/testthat/test-plot_recruitment.R +++ b/tests/testthat/test-plot_recruitment.R @@ -53,4 +53,3 @@ test_that("plot_recruitment generates plots without errors", { "gg" ) }) - diff --git a/tests/testthat/test-plot_spr.R b/tests/testthat/test-plot_spr.R index dffac3d3..5c4d984f 100644 --- a/tests/testthat/test-plot_spr.R +++ b/tests/testthat/test-plot_spr.R @@ -3,7 +3,7 @@ test_that("plot_spr generates plots without errors", { expect_no_error( plot_spr(stockplotr::example_data, interactive = FALSE) ) - + # expect error-free plot with many arguments expect_no_error( plot_spr( @@ -14,7 +14,7 @@ test_that("plot_spr generates plots without errors", { ) ) - + # expect ggplot object is returned expect_s3_class( plot_spr( diff --git a/tests/testthat/test-save_all_plots.R b/tests/testthat/test-save_all_plots.R index 4ddc4e3e..cd1b773c 100644 --- a/tests/testthat/test-save_all_plots.R +++ b/tests/testthat/test-save_all_plots.R @@ -26,10 +26,10 @@ tab_base_temp_files <- c( ) test_that("save_all_plots works when all figures/tables are plotted", { - savedir <- fs::path(getwd(), "test-save_all_plots") - if(!dir.exists(savedir)) + if (!dir.exists(savedir)) { dir.create(savedir) + } save_all_plots( stockplotr::example_data, @@ -53,125 +53,125 @@ test_that("save_all_plots works when all figures/tables are plotted", { ) # erase temporary testing files - unlink(fs::path(savedir), recursive=TRUE) - + unlink(fs::path(savedir), recursive = TRUE) }) test_that("save_all_plots with custom plot options", { - - savedir <- fs::path(getwd(), "test-save_all_plots") - if(!dir.exists(savedir)) - dir.create(savedir) + savedir <- fs::path(getwd(), "test-save_all_plots") + if (!dir.exists(savedir)) { + dir.create(savedir) + } - - save_all_plots( - stockplotr::example_data, - figures_tables_dir = savedir, - interactive = FALSE, - plot_spawning_biomass_options = list( - ref_line = "target" - ), - plot_abundance_at_age_options = list( - scale_amount = 1000 - ) + + save_all_plots( + stockplotr::example_data, + figures_tables_dir = savedir, + interactive = FALSE, + plot_spawning_biomass_options = list( + ref_line = "target" + ), + plot_abundance_at_age_options = list( + scale_amount = 1000 ) + ) - # expect that the figures and tables dirs exist - expect_true(dir.exists(fs::path(savedir, "figures"))) - expect_true(dir.exists(fs::path(savedir, "tables"))) + # expect that the figures and tables dirs exist + expect_true(dir.exists(fs::path(savedir, "figures"))) + expect_true(dir.exists(fs::path(savedir, "tables"))) - # expect that the figures are all created with expected names - - expect_equal( - sort(list.files(fs::path(savedir, "figures"))), - sort(fig_base_temp_files) - ) + # expect that the figures are all created with expected names - # expect that the tables are all created with expected names - expect_equal( - sort(list.files(fs::path(savedir, "tables"))), - sort(tab_base_temp_files) - ) + expect_equal( + sort(list.files(fs::path(savedir, "figures"))), + sort(fig_base_temp_files) + ) + + # expect that the tables are all created with expected names + expect_equal( + sort(list.files(fs::path(savedir, "tables"))), + sort(tab_base_temp_files) + ) - # erase temporary testing files - unlink(fs::path(savedir), recursive=TRUE) + # erase temporary testing files + unlink(fs::path(savedir), recursive = TRUE) }) test_that("save_all_plots returns error when plot not made", { + savedir <- fs::path(getwd(), "test-save_all_plots") + if (!dir.exists(savedir)) { + dir.create(savedir) + } - savedir <- fs::path(getwd(), "test-save_all_plots") - if(!dir.exists(savedir)) - dir.create(savedir) - - save_all_plots( - stockplotr::example_data, - figures_tables_dir = savedir, - interactive = FALSE, - plot_natural_mortality_options = list( - module = NULL - ) + save_all_plots( + stockplotr::example_data, + figures_tables_dir = savedir, + interactive = FALSE, + plot_natural_mortality_options = list( + module = NULL ) + ) - # expect that the figures and tables dirs exist - expect_true(dir.exists(fs::path(savedir, "figures"))) - expect_true(dir.exists(fs::path(savedir, "tables"))) + # expect that the figures and tables dirs exist + expect_true(dir.exists(fs::path(savedir, "figures"))) + expect_true(dir.exists(fs::path(savedir, "tables"))) - # expect that the figures are all created with expected names - # no natural_mortality_figure.rda as that throws and error - # and is not generated in this test. - expect_equal( - sort(list.files(fs::path(savedir, "figures"))), - sort(fig_base_temp_files[which(!grepl("natural_mortality", fig_base_temp_files))]) - ) + # expect that the figures are all created with expected names + # no natural_mortality_figure.rda as that throws and error + # and is not generated in this test. + expect_equal( + sort(list.files(fs::path(savedir, "figures"))), + sort(fig_base_temp_files[which(!grepl("natural_mortality", fig_base_temp_files))]) + ) - # expect that the tables are all created with expected names - expect_equal( - sort(list.files(fs::path(savedir, "tables"))), - sort(tab_base_temp_files) - ) + # expect that the tables are all created with expected names + expect_equal( + sort(list.files(fs::path(savedir, "tables"))), + sort(tab_base_temp_files) + ) - # erase temporary testing files - unlink(fs::path(savedir), recursive=TRUE) + # erase temporary testing files + unlink(fs::path(savedir), recursive = TRUE) }) test_that("save_all_plots returns error when dat is not valid", { - savedir <- fs::path(getwd(), "test-save_all_plots") - if(!dir.exists(savedir)) - dir.create(savedir) - - expect_error( - save_all_plots( - r4ss::SS_output(file.path(test_path("fixtures", "ss3_models"), "models", "Hake_2018", "Report.sso")), - figures_tables_dir = savedir, - interactive = FALSE, - plot_natural_mortality_options = list( - module = NULL - ) + savedir <- fs::path(getwd(), "test-save_all_plots") + if (!dir.exists(savedir)) { + dir.create(savedir) + } + + expect_error( + save_all_plots( + r4ss::SS_output(file.path(test_path("fixtures", "ss3_models"), "models", "Hake_2018", "Report.sso")), + figures_tables_dir = savedir, + interactive = FALSE, + plot_natural_mortality_options = list( + module = NULL ) ) + ) - expect_error( - save_all_plots( - data.frame(), - figures_tables_dir = savedir, - interactive = FALSE, - plot_natural_mortality_options = list( - module = NULL - ) + expect_error( + save_all_plots( + data.frame(), + figures_tables_dir = savedir, + interactive = FALSE, + plot_natural_mortality_options = list( + module = NULL ) ) + ) - expect_error( - save_all_plots( - data.frame(label="label"), - figures_tables_dir = savedir, - interactive = FALSE, - plot_natural_mortality_options = list( - module = NULL - ) + expect_error( + save_all_plots( + data.frame(label = "label"), + figures_tables_dir = savedir, + interactive = FALSE, + plot_natural_mortality_options = list( + module = NULL ) ) - - # erase temporary testing files - unlink(fs::path(savedir), recursive=TRUE) + ) + + # erase temporary testing files + unlink(fs::path(savedir), recursive = TRUE) }) diff --git a/tests/testthat/test-table_landings.R b/tests/testthat/test-table_landings.R index 0db427d4..b0067d98 100644 --- a/tests/testthat/test-table_landings.R +++ b/tests/testthat/test-table_landings.R @@ -51,4 +51,4 @@ test_that("table_landings generates error with incorrect module", { tables_dir = getwd() ) ) -}) \ No newline at end of file +}) diff --git a/vignettes/extract-sis-data.Rmd b/vignettes/extract-sis-data.Rmd index 2c52b7e0..cfe7f33c 100644 --- a/vignettes/extract-sis-data.Rmd +++ b/vignettes/extract-sis-data.Rmd @@ -134,4 +134,4 @@ The `extract_sis_data()` workflow extracts at most one time series for each cate * **Fmort, Recruitment, & Catch**: Multiple time series allowed per category, but exactly one must be marked Primary = Y per category. * **Spawners & Biomass**: Multiple time series allowed across both categories, but only one time series combined across both Spawners and Biomass can be marked Primary = Y. -* **Index**: Multiple time series allowed, but none can be marked Primary = Y (always N). \ No newline at end of file +* **Index**: Multiple time series allowed, but none can be marked Primary = Y (always N).