From 300efc8516291d47b2deade5de0ed679559222d2 Mon Sep 17 00:00:00 2001 From: Schiano-NOAA <125507018+Schiano-NOAA@users.noreply.github.com> Date: Mon, 11 May 2026 19:39:17 +0000 Subject: [PATCH] style and docs: run devtools::document() and style with styler or air --- DESCRIPTION | 2 +- R/convert_output.R | 165 ++++++++++---------- R/data.R | 6 +- R/html_all_figs_tables.R | 4 +- R/plot_abundance_at_age.R | 6 +- R/plot_biomass.R | 12 +- R/plot_biomass_at_age.R | 8 +- R/plot_catch_comp.R | 2 +- R/plot_fishing_mortality.R | 11 +- R/plot_indices.R | 10 +- R/plot_landings.R | 8 +- R/plot_natural_mortality.R | 6 +- R/plot_recruitment.R | 8 +- R/plot_spawning_biomass.R | 44 +++--- R/plot_stock_recruitment.R | 8 +- R/process_data.R | 18 +-- R/save_all_plots.R | 4 +- R/table_landings.R | 6 +- R/utils.R | 27 ++-- R/utils_plot.R | 3 +- R/utils_rda.R | 6 +- man/convert_output.Rd | 4 +- man/example_data.Rd | 2 +- man/plot_landings.Rd | 2 +- man/plot_spawning_biomass.Rd | 2 +- man/process_data.Rd | 2 +- man/reference_line.Rd | 2 +- man/stockplotr-package.Rd | 1 + tests/testthat/test-plot_biomass.R | 2 +- tests/testthat/test-plot_spawning_biomass.R | 1 - tests/testthat/test-save_all_plots.R | 16 +- 31 files changed, 197 insertions(+), 201 deletions(-) diff --git a/DESCRIPTION b/DESCRIPTION index 57273285..7ff57014 100644 --- a/DESCRIPTION +++ b/DESCRIPTION @@ -65,9 +65,9 @@ Suggests: testthat (>= 3.0.0) VignetteBuilder: knitr +Config/roxygen2/version: 8.0.0 Config/testthat/edition: 3 Config/testthat/parallel: false Encoding: UTF-8 Language: en-US LazyData: true -RoxygenNote: 7.3.3 diff --git a/R/convert_output.R b/R/convert_output.R index 92aff989..15b8fca9 100644 --- a/R/convert_output.R +++ b/R/convert_output.R @@ -14,11 +14,11 @@ #' #' @returns A reformatted and standardized version of assessment model results #' for application in building a stock assessment reports and to easily -#' adapt results among regional assessments. -#' @details The resulting object is simply a transformed and machine readable -#' version of a model output file. Converted data frame is always returned. +#' adapt results among regional assessments. +#' @details The resulting object is simply a transformed and machine readable +#' version of a model output file. Converted data frame is always returned. #' It will also be saved if save_dir is not NULL. -#' +#' #' #' @export #' @@ -118,28 +118,27 @@ convert_output <- function( if (is.character(file)) { if (is.null(model)) { model <- switch(stringr::str_extract(file, "\\.([^.]+)$"), - ".sso" = { - cli::cli_alert_info("Processing Stock Synthesis output file...") - "ss3" - }, - ".rdat" = { - cli::cli_alert_info("Processing BAM output file...") - "bam" - }, - ".rds" = { - cli::cli_alert_info("Processing WHAM output file...") - "wham" - }, - ".RDS" = { - cli::cli_alert_info("Processing FIMS output file...") - "fims" - }, - - cli::cli_abort("Unknown file type. Please indicate model.") + ".sso" = { + cli::cli_alert_info("Processing Stock Synthesis output file...") + "ss3" + }, + ".rdat" = { + cli::cli_alert_info("Processing BAM output file...") + "bam" + }, + ".rds" = { + cli::cli_alert_info("Processing WHAM output file...") + "wham" + }, + ".RDS" = { + cli::cli_alert_info("Processing FIMS output file...") + "fims" + }, + cli::cli_abort("Unknown file type. Please indicate model.") ) } } else { - model <- switch (class(file)[1], + model <- switch(class(file)[1], "fims" = { cli::cli_alert_info("Processing FIMS output file...") "fims" @@ -151,7 +150,7 @@ convert_output <- function( cli::cli_abort("Unknown file type. Please indicate model.") ) } - + #### SS3 #### # Convert SS3 output Report.sso file @@ -1798,26 +1797,26 @@ convert_output <- function( } else { dat <- file } - + # Extract or use fleet names if (is.null(fleet_names)) { fleet_names <- names(dat$estimated_params$index_ln_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 #### for (p in (2:length(dat))[-c(6, 9, 10)]) { extract <- dat[p] - module_name <- names(extract) + module_name <- names(extract) cli::cli_alert_info("Processing {module_name}") if (module_name == "sdrep") { ##### sdrep #### @@ -1836,30 +1835,32 @@ convert_output <- function( values <- values |> dplyr::left_join( { - values |> dplyr::group_by(label) |> dplyr::count() + values |> + dplyr::group_by(label) |> + dplyr::count() }, by = "label" - ) + ) # make year column year_col <- rep( file[["data_list"]]$styr:file[["data_list"]]$projyr, length(unique( - dplyr::filter(values_count, n == length(file[["data_list"]]$styr:file[["data_list"]]$projyr)) |> + dplyr::filter(values_count, n == length(file[["data_list"]]$styr:file[["data_list"]]$projyr)) |> dplyr::pull(label) )) ) - + df2 <- values |> dplyr::filter(n == length(file[["data_list"]]$styr:file[["data_list"]]$projyr)) |> dplyr::mutate(year = year_col) - - df2 <- values |> - dplyr::filter( - n != length(file[["data_list"]]$styr:file[["data_list"]]$projyr) - ) |> - dplyr::mutate(year = NA) |> + + df2 <- values |> + dplyr::filter( + n != length(file[["data_list"]]$styr:file[["data_list"]]$projyr) + ) |> + dplyr::mutate(year = NA) |> rbind(df2) - + # Extract parameter values ts par_fixes <- data.frame( label = names(extract[[1]]$par.fixed), @@ -1872,23 +1873,23 @@ convert_output <- function( dplyr::left_join( par_fixes_count, by = "label" - ) - + ) + year_col_par_fix <- rep( file[["data_list"]]$styr:file[["data_list"]]$endyr, length(unique( - dplyr::filter(par_fixes_count, n == length(file[["data_list"]]$styr:file[["data_list"]]$endyr)) |> + dplyr::filter(par_fixes_count, n == length(file[["data_list"]]$styr:file[["data_list"]]$endyr)) |> dplyr::pull(label) )) ) - + df3 <- par_fixes |> dplyr::filter(n == length(file[["data_list"]]$styr:file[["data_list"]]$endyr)) |> dplyr::mutate(year = year_col_par_fix) - df3 <- par_fixes |> + df3 <- par_fixes |> dplyr::filter( n != length(file[["data_list"]]$styr:file[["data_list"]]$endyr) - ) |> + ) |> dplyr::mutate(year = NA) |> rbind(df3) |> dplyr::mutate( @@ -1898,13 +1899,13 @@ convert_output <- 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") { @@ -1912,9 +1913,9 @@ convert_output <- function( # Only extract specific quantity needs # comp_data?, index_data, catch_data, weight, Ftarget, Flimit data_list_list <- list() - + ####### Indices #### - # Extract index_data + # Extract index_data df_index <- extract[[1]]$index_data |> # rename all columns to lower case to match standard dplyr::rename_with(tolower) |> @@ -1931,7 +1932,7 @@ convert_output <- function( ) |> dplyr::select(-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.") @@ -1939,7 +1940,7 @@ convert_output <- 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( @@ -1948,19 +1949,19 @@ convert_output <- function( values_to = "estimate" ) |> dplyr::mutate( - module_name = names(extract)#, + module_name = names(extract) # , # era = dplyr::if_else( # year > dat$data_list$endyr, # "fore", # NA_character_ # ) ) - + 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 + # Extract catch_data and align with log_index_hat and catch_h # Modify sdrep in outlist to include index df_catch <- extract[[1]]$catch_data |> # dplyr::filter(!is.na(Catch)) |> @@ -1988,28 +1989,28 @@ convert_output <- 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 = "indices_observed" ) - - indexing_vars_cols <- colnames(df_comp_obs)[!grepl("comp", colnames(df_comp_obs))] - + + indexing_vars_cols <- colnames(df_comp_obs)[!grepl("comp", colnames(df_comp_obs))] + df_comp_pred <- dplyr::select(df_comp_obs, dplyr::all_of(indexing_vars_cols)) |> dplyr::cross_join(as.data.frame(dat$quantities$age_hat)) |> tidyr::pivot_longer( @@ -2022,9 +2023,9 @@ convert_output <- function( dplyr::mutate( label = "composition_predicted", # NOTE: the below age mutate slows down code - age = stringr::str_replace(age, "V","") + age = stringr::str_replace(age, "V", "") ) - + # Finish adjusting comp_obs # pivot obs data df_comp_obs <- df_comp_obs |> @@ -2037,32 +2038,31 @@ convert_output <- function( dplyr::mutate( label = "composition_observed", # NOTE: the below age mutate slows down code - age = stringr::str_replace(age, "comp_","") + age = stringr::str_replace(age, "comp_", "") ) - + df_comp <- rbind(df_comp_obs, df_comp_pred) |> # 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_catch[setdiff(tolower(names(out_new)), tolower(names(df_catch)))] <- NA data_list_list[["comp_data"]] <- df_catch - + # final df for data_list module new_df <- Reduce(rbind, data_list_list) out_list[[names(extract)]] <- new_df - } else if (is.list(extract[[1]])) { # indicates vector and list ##### remaining lmnts #### if (any(vapply(extract[[1]], is.matrix, FUN.VALUE = logical(1)))) { - ############################################################## + ############################################################## df <- extract[[1]] |> expand_element(fleet_names = fleet_names) |> dplyr::mutate( module_name = module_name - ) |> suppressWarnings() + ) |> + suppressWarnings() df[setdiff(tolower(names(out_new)), tolower(names(df)))] <- NA out_list[[names(extract)]] <- df - } else if (any(vapply(extract[[1]], is.vector, FUN.VALUE = logical(1)))) { # all must be a vector to work - so there must be conditions for dfs with a mix extract_list <- list() # mod_name1 <- names(extract) @@ -2072,7 +2072,7 @@ convert_output <- 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( @@ -2102,12 +2102,12 @@ convert_output <- function( } else { cli::cli_alert_warning("Not compatible yet.") } - # } else if (is.list(extract[[1]])) { # list only - # } else if (is.matrix(extract[[1]])) { # matrix only - # } else { - # cli::cli_alert_warning(paste(names(extract), " not compatible.", sep = "")) - # } # close if statement - } # close loop over objects listed in dat file + # } else if (is.list(extract[[1]])) { # list only + # } else if (is.matrix(extract[[1]])) { # matrix only + # } else { + # cli::cli_alert_warning(paste(names(extract), " not compatible.", sep = "")) + # } # close if statement + } # close loop over objects listed in dat file # Finish out df out_new <- Reduce(rbind, out_list) |> # Add era as factor into BAM conout @@ -2116,12 +2116,11 @@ convert_output <- function( label = tolower(label), # set era era = dplyr::if_else( - year > dat$data_list$endyr, + year > dat$data_list$endyr, "fore", "time" ) ) - } else { cli::cli_abort(c( message = "Output file not compatible.", @@ -2177,13 +2176,13 @@ convert_output <- function( # con_file <- system.file("resources", "rceattle_var_names.csv", package = "stockplotr", mustWork = TRUE) # var_names_sheet <- utils::read.csv(con_file, na.strings = "") # } - + # edit: here is a different way of loading in the csv sheets con_file <- system.file("resources", glue::glue("{model}_var_names.csv"), package = "stockplotr", mustWork = TRUE) # temporarily add call to local csv so I can test # con_file <- glue::glue("~/GitHub/stockplotr/inst/resources/{model}_var_names.csv") var_names_sheet <- utils::read.csv(con_file, na.strings = "") - + if (file.exists(con_file)) { # Remove 'X' column if it exists var_names_sheet <- var_names_sheet |> diff --git a/R/data.R b/R/data.R index 3f758d14..ffc31b2c 100644 --- a/R/data.R +++ b/R/data.R @@ -1,6 +1,6 @@ #' SS3 Example data #' -#' Included data set that represents a Report.sso file converted using +#' Included data set that represents a Report.sso file converted using #' convert_output(). This example is from the 2022 Petrale sole stock assessment. #' #' @format A tibble with 591109 rows and 33 variables: @@ -39,5 +39,5 @@ #' \item{count}{indexing column of data} #' \item{block}{indexing column of data} #' } -#' -"example_data" \ No newline at end of file +#' +"example_data" diff --git a/R/html_all_figs_tables.R b/R/html_all_figs_tables.R index 9c0fddae..983ad392 100644 --- a/R/html_all_figs_tables.R +++ b/R/html_all_figs_tables.R @@ -7,11 +7,11 @@ #' #' @returns A folder ("all_tables_figures") in your working directory containing #' html and qmd files that show all tables and figures. -#' +#' #' @seealso #' \code{\link[asar:create_figures_doc]{asar::create_figures_doc()}}, #' \code{\link[asar:create_tables_doc]{asar::create_tables_doc()}} -#' +#' #' #' @export #' diff --git a/R/plot_abundance_at_age.R b/R/plot_abundance_at_age.R index 91714d58..71c6967f 100644 --- a/R/plot_abundance_at_age.R +++ b/R/plot_abundance_at_age.R @@ -22,14 +22,14 @@ #' ("rda_files") that will be created if the argument `make_rda` = TRUE. #' Default is the working directory. #' @returns A plot showing total abundance (or numbers) at age. -#' +#' #' @details The input is from an assessment model output file #' translated to a standardized output (\link[stockplotr]{convert_output}). #' There are options to return a `ggplot2` object or export an .rda object #' containing associated caption and alternative text for the figure. -#' +#' #' @seealso [convert_output()], [filter_data()], [process_data()], [plot_aa()], [export_kqs()], [insert_kqs()], [create_rda()] -#' +#' #' @export #' #' @examples diff --git a/R/plot_biomass.R b/R/plot_biomass.R index 8c41ba6e..e2b94bdb 100644 --- a/R/plot_biomass.R +++ b/R/plot_biomass.R @@ -11,14 +11,14 @@ #' regardless of how it is specified in `dat`. Other possibilities may include #' "target", "MSY", and "unfished". #' @returns A plot showing total biomass. -#' +#' #' @details The input is from an assessment model output file #' translated to a standardized output (\link[stockplotr]{convert_output}). #' There are options to return a `ggplot2` object or export an .rda object #' containing associated caption and alternative text for the figure. -#' +#' #' @seealso [convert_output()], [plot_timeseries()], [calculate_reference_point()], [reference_line()], [filter_data()], [process_data()], [export_kqs()], [insert_kqs()], [create_rda()] -#' +#' #' @export #' #' @examples @@ -108,7 +108,7 @@ plot_biomass <- function( ) } } - + # Process data for indexing/grouping # TODO: check and add into process_data step to summarize when theres >1 label processing <- process_data( @@ -116,12 +116,12 @@ plot_biomass <- function( group, facet ) - + # variable <- processing[[1]] prepared_data <- processing[[1]] group <- processing[[2]] if (!is.null(processing[[3]])) facet <- processing[[3]] - + plt <- plot_timeseries( dat = prepared_data, diff --git a/R/plot_biomass_at_age.R b/R/plot_biomass_at_age.R index 54e7ccac..d10e605d 100644 --- a/R/plot_biomass_at_age.R +++ b/R/plot_biomass_at_age.R @@ -8,16 +8,16 @@ #' @param interactive TRUE/FALSE; indicate whether the environment in which the #' function is operating is interactive. This bypasses some options for #' filtering when preparing data for the plot. Default is FALSE. -#' +#' #' @returns A plot showing total biomass at age. -#' +#' #' @details The input is from an assessment model output file #' translated to a standardized output (\link[stockplotr]{convert_output}). #' There are options to return a `ggplot2` object or export an .rda object #' containing associated caption and alternative text for the figure. -#' +#' #' @seealso [convert_output()], [filter_data()], [process_data()], [plot_aa()], [export_kqs()], [insert_kqs()], [create_rda()] -#' +#' #' @export #' #' @examples diff --git a/R/plot_catch_comp.R b/R/plot_catch_comp.R index 560aec60..9b092aa0 100644 --- a/R/plot_catch_comp.R +++ b/R/plot_catch_comp.R @@ -19,7 +19,7 @@ #' will select the most relevant module if more than 1 exists. #' #' @returns A plot showing catch or landings composition. -#' +#' #' @details This plot is made only when catch or landings are explicitly named #' in the output file. The current plot function does not combine all sources of #' catch. diff --git a/R/plot_fishing_mortality.R b/R/plot_fishing_mortality.R index 7bf802ed..c301478c 100644 --- a/R/plot_fishing_mortality.R +++ b/R/plot_fishing_mortality.R @@ -3,14 +3,14 @@ #' @inheritParams plot_spawning_biomass #' #' @returns A plot showing fishing mortality over time. -#' +#' #' @details The input is from an assessment model output file #' translated to a standardized output (\link[stockplotr]{convert_output}). #' There are options to return a `ggplot2` object or export an .rda object #' containing associated caption and alternative text for the figure. -#' +#' #' @seealso [convert_output()], [filter_data()], [process_data()], [plot_timeseries()], [reference_line()], [export_kqs()], [insert_kqs()], [create_rda()] -#' +#' #' @export #' #' @examples @@ -85,13 +85,12 @@ plot_fishing_mortality <- function( ### Make RDA ---- if (make_rda) { - F.min <- min(prepared_data$estimate) |> round(digits = 3) F.max <- max(prepared_data$estimate) |> round(digits = 3) - + export_kqs(F.min, F.max) insert_kqs(F.min, F.max) - + F.ref.pt <- as.character(ref_line) F.start.year <- min(prepared_data$year) F.end.year <- max(prepared_data$year) diff --git a/R/plot_indices.R b/R/plot_indices.R index fa9fbb90..92bb5670 100644 --- a/R/plot_indices.R +++ b/R/plot_indices.R @@ -8,14 +8,14 @@ #' filtered. (i.e. select names of fleets to zoom into the plot) #' #' @returns A plot showing the expected and predicted indices. -#' +#' #' @details The input is from an assessment model output file #' translated to a standardized output (\link[stockplotr]{convert_output}). #' There are options to return a `ggplot2` object or export an .rda object #' containing associated caption and alternative text for the figure. -#' +#' #' @seealso [convert_output()], [filter_data()], [process_data()], [plot_obsvpred()], [export_kqs()], [insert_kqs()], [create_rda()] -#' +#' #' @export #' #' @examples @@ -70,7 +70,7 @@ plot_indices <- function( prepared_data <- prepared_data |> dplyr::filter(fleet %in% focus) } - + processed_data <- process_data( dat = prepared_data, group = group, @@ -116,7 +116,7 @@ plot_indices <- function( facet_formula <- stats::reformulate(facet) plt <- plt + ggplot2::facet_wrap(facet_formula, scales = "free") } - + ### Make RDA ---- if (make_rda) { # Obtain relevant key quantities for captions/alt text diff --git a/R/plot_landings.R b/R/plot_landings.R index d1967521..ffe7876f 100644 --- a/R/plot_landings.R +++ b/R/plot_landings.R @@ -3,14 +3,14 @@ #' @inheritParams plot_spawning_biomass #' #' @returns A plot showing cumulative landings over time. -#' +#' #' @details The input is from an assessment model output file #' translated to a standardized output (\link[stockplotr]{convert_output}). #' There are options to return a `ggplot2` object or export an .rda object #' containing associated caption and alternative text for the figure. -#' +#' #' @seealso [convert_output()], [filter_data()], [process_data()], [plot_timeseries()], [export_kqs()], [insert_kqs()], [create_rda()] -#' +#' #' @export #' #' @examples @@ -48,7 +48,7 @@ plot_landings <- function( cli::cli_alert_info("Unit label was not changed. Setting unit_label to 'lbs'.") unit_label <- "lbs" } - + # Units landings_label <- label_magnitude( label = "Landings", diff --git a/R/plot_natural_mortality.R b/R/plot_natural_mortality.R index 6bb1e6af..de85727c 100644 --- a/R/plot_natural_mortality.R +++ b/R/plot_natural_mortality.R @@ -3,14 +3,14 @@ #' @inheritParams plot_spawning_biomass #' #' @returns A plot showing natural mortality at age. -#' +#' #' @details The input is from an assessment model output file #' translated to a standardized output (\link[stockplotr]{convert_output}). #' There are options to return a `ggplot2` object or export an .rda object #' containing associated caption and alternative text for the figure. -#' +#' #' @seealso [convert_output()], [filter_data()], [process_data()], [plot_timeseries()], [export_kqs()], [insert_kqs()], [create_rda()] -#' +#' #' @export #' #' @examples diff --git a/R/plot_recruitment.R b/R/plot_recruitment.R index c8cbef99..cedae3f0 100644 --- a/R/plot_recruitment.R +++ b/R/plot_recruitment.R @@ -4,14 +4,14 @@ #' @param unit_label units for recruitment #' #' @returns A plot showing recruitment over time. -#' +#' #' @details The input is from an assessment model output file #' translated to a standardized output (\link[stockplotr]{convert_output}). #' There are options to return a `ggplot2` object or export an .rda object #' containing associated caption and alternative text for the figure. -#' -#' @seealso [convert_output()], [filter_data()], [process_data()], [plot_timeseries()], [export_kqs()], [insert_kqs()], [create_rda()] -#' +#' +#' @seealso [convert_output()], [filter_data()], [process_data()], [plot_timeseries()], [export_kqs()], [insert_kqs()], [create_rda()] +#' #' @export #' #' @examples diff --git a/R/plot_spawning_biomass.R b/R/plot_spawning_biomass.R index 176f0cd0..acf4d586 100644 --- a/R/plot_spawning_biomass.R +++ b/R/plot_spawning_biomass.R @@ -38,7 +38,7 @@ #' Default: "metric tons" #' @param lbs A logical value indicating whether to convert the y-axis values from #' kilograms to pounds. The default units match the default in the -#' unit_label argument - 'metric tons'. +#' unit_label argument - 'metric tons'. #' #' Default: `FALSE` #' @param module (Optional) A string indicating the module_name found in `dat`. @@ -68,14 +68,14 @@ #' #' Default: `FALSE` #' @param ... Arguments called from \link[ggplot2]{geom_line} or \link[ggplot2]{geom_point} -#' +#' #' @return A plot showing spawning biomass over time. -#' +#' #' @details The input is from an assessment model output file #' translated to a standardized output (\link[stockplotr]{convert_output}). #' There are options to return a `ggplot2` object or export an .rda object #' containing associated caption and alternative text for the figure. -#' +#' #' @note #' All plotting functions automatically recognize indexing variables and will #' use them in groupings and/or facetting. @seealso [process_data()]. @@ -123,7 +123,7 @@ plot_spawning_biomass <- function( cli::cli_alert_info("Unit label was not changed. Setting unit_label to 'lbs'.") unit_label <- "lbs" } - + # TODO: Fix the unit label if scaling. Maybe this is up to the user to do if # they want something scaled then they have to supply a better unit name # or we create a helper function to do this. @@ -135,10 +135,10 @@ plot_spawning_biomass <- function( label = "Spawning Biomass", unit_label = unit_label, scale_amount = dplyr::if_else( - lbs, - ifelse(unit_label %in% c("mt", "mts", "metric tons", "metric ton"), 1000, 1) * scale_amount, + lbs, + ifelse(unit_label %in% c("mt", "mts", "metric tons", "metric ton"), 1000, 1) * scale_amount, scale_amount - ), + ), legend = TRUE ) } @@ -157,24 +157,24 @@ plot_spawning_biomass <- function( # Filter data for spawning biomass prepared_data <- filter_data( - dat = dat, - label_name = ifelse(relative, glue::glue("spawning_biomass_spawning_biomass_{ref_line}|spawning_biomass_ratio"), "^spawning_biomass$"), - geom = geom, - era = era, - group = group, - facet = facet, - module = module, - scale_amount = scale_amount, - interactive = interactive - ) - + dat = dat, + label_name = ifelse(relative, glue::glue("spawning_biomass_spawning_biomass_{ref_line}|spawning_biomass_ratio"), "^spawning_biomass$"), + geom = geom, + era = era, + group = group, + facet = facet, + module = module, + scale_amount = scale_amount, + interactive = interactive + ) + 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'.") stop() } - } - + } + # process the data for grouping processing <- process_data( dat = prepared_data, @@ -187,7 +187,7 @@ plot_spawning_biomass <- function( plot_data <- processing[[1]] group <- processing[[2]] if (!is.null(processing[[3]])) facet <- processing[[3]] - + # Override grouping variable when there is only NA's if (!is.null(group)) { if (group %notin% colnames(plot_data)) group <- NULL diff --git a/R/plot_stock_recruitment.R b/R/plot_stock_recruitment.R index 673841d9..ff3ba387 100644 --- a/R/plot_stock_recruitment.R +++ b/R/plot_stock_recruitment.R @@ -9,15 +9,15 @@ #' @param recruitment_label units for recruitment #' #' @returns A plot showing the stock recruitment relationship. -#' +#' #' @details The input is from an assessment model output file #' translated to a standardized output (\link[stockplotr]{convert_output}). #' There are options to return a `ggplot2` object or export an .rda object #' containing associated caption and alternative text for the figure. -#' +#' #' @seealso [convert_output()], [filter_data()], [process_data()], [plot_timeseries()], [export_kqs()], [insert_kqs()], [create_rda()] -#' -#' +#' +#' #' @export #' #' @examples diff --git a/R/process_data.R b/R/process_data.R index 08559c48..3200b409 100644 --- a/R/process_data.R +++ b/R/process_data.R @@ -12,7 +12,7 @@ #' variable(s) of the data. #' @param lbs A logical value indicating whether to convert the y-axis values from #' kilograms to pounds. The default units match the default in the -#' unit_label argument - 'metric tons'. +#' unit_label argument - 'metric tons'. #' #' Default: `FALSE` #' @param method A string describing the method of summarizing data when group @@ -27,11 +27,11 @@ #' \item{facet}{A string or vector of strings identifying the faceting #' variable(s) of the data. If NULL, no faceting variable is identified. Any #' identified indexed variables found in this function will be added to facet.} -#' +#' #' @details Automatically detects potential grouping and faceting data from a #' dataframe output from \link[stockplotr]{filter_data}. -#' -#' +#' +#' #' @export #' #' @examples { @@ -314,7 +314,7 @@ process_data <- function( group <- NULL } } - + # Ensure that index_variables -- group or facets are non-numeric to be plotted accurately data <- data |> dplyr::mutate( @@ -323,14 +323,14 @@ process_data <- function( as.character ) ) - + if (lbs) { data <- data |> dplyr::mutate( # multiple by conversion from kg to lbs -- default then becomes thousands of lbs estimate = (estimate * 2.20462), - estimate_lower = NA_real_, #(estimate_lower * 2.20462), - estimate_upper = NA_real_, #(estimate_upper * 2.20462) + estimate_lower = NA_real_, # (estimate_lower * 2.20462), + estimate_upper = NA_real_, # (estimate_upper * 2.20462) ) } @@ -352,7 +352,7 @@ process_data <- function( #' #' @returns A dataframe of processed data ready for formatting into a table. #' @details Input is an object created with \link[stockplotr]{filter_data}. -#' +#' #' @export #' #' @examples { diff --git a/R/save_all_plots.R b/R/save_all_plots.R index 84030372..9d9132b8 100644 --- a/R/save_all_plots.R +++ b/R/save_all_plots.R @@ -43,9 +43,9 @@ #' @param proportional T/F to scale size of bubble plots #' #' @returns Rda files for each figure/table. -#' +#' #' @seealso [convert_output()], [create_rda()] -#' +#' #' @details The input is from an assessment model output file #' translated to a standardized output (\link[stockplotr]{convert_output}). #' diff --git a/R/table_landings.R b/R/table_landings.R index 52d14eac..46028440 100644 --- a/R/table_landings.R +++ b/R/table_landings.R @@ -14,15 +14,15 @@ #' "landings_predicted", "landings". #' #' @returns A table ready of landed catch by fleet and year. -#' +#' #' @details The input is from an assessment model output file #' translated to a standardized output (\link[stockplotr]{convert_output}). #' There are options to return a [gt::gt()] object or export an rda object #' containing a gt-based table, caption, and LaTeX-based table. -#' +#' #' @seealso [convert_output()], [filter_data()], [process_table()], [export_kqs()], [insert_kqs()], [create_rda()] #' @export -#' +#' #' @examples #' table_landings(stockplotr::example_data) #' diff --git a/R/utils.R b/R/utils.R index 6ba1da95..08cb3b82 100644 --- a/R/utils.R +++ b/R/utils.R @@ -198,14 +198,14 @@ SS3_extract_fleet <- function(dat, vers) { # input_list = unlisted object from model output expand_element <- function(input_list, fleet_names = "Pollock") { - # Use map_dfr to iterate over each element of the list # .id = "origin_var" keeps track of which list element the data came from purrr::imap_dfr(input_list, function(x, name) { - # Skip empty/null elements immediately - if (length(x) == 0 || is.null(x)) return(NULL) - + if (length(x) == 0 || is.null(x)) { + return(NULL) + } + # Standardize current element 'x' to a Long Data Frame if (!is.null(dim(x)) && length(dim(x)) > 1) { # Handles Arrays/Matrices @@ -225,25 +225,25 @@ expand_element <- function(input_list, fleet_names = "Pollock") { )) |> dplyr::select(-dim_info) } - + # Process the labels df |> dplyr::mutate( label_init = as.character(label_init), - + # Pull parameter name label = dplyr::case_when( stringr::str_extract(label_init, "^[^\\.]+") == "rec_pars" ~ stringr::str_extract(label_init, "[^\\.]+$"), TRUE ~ stringr::str_extract(label_init, "^[^\\.]+") - ), - + ), + # Extract Age age = dplyr::case_when( - grepl("age", label_init, ignore.case = TRUE) ~ + grepl("age", label_init, ignore.case = TRUE) ~ as.numeric(stringr::str_extract(label_init, "(?<=\\.[Aa]ge)[0-9]+(?=\\.|$)")), TRUE ~ NA_real_ ), - + # Extract Sex sex = dplyr::case_when( grepl("Sex.combined|combined", label_init, ignore.case = TRUE) ~ "combined", @@ -251,16 +251,16 @@ expand_element <- function(input_list, fleet_names = "Pollock") { grepl("male", label_init, ignore.case = TRUE) ~ "male", # check havent seen example of this! TRUE ~ NA_character_ ), - + # Extract Year (4 digits) year = dplyr::case_when( grepl("[0-9]{4}", label_init) ~ as.numeric(stringr::str_extract(label_init, "[0-9]{4}")), TRUE ~ NA_real_ ), - + # Extract Fleet fleet = dplyr::case_when( - grepl(paste0(fleet_names, collapse = "|"), label_init) ~ + grepl(paste0(fleet_names, collapse = "|"), label_init) ~ stringr::str_extract(label_init, paste0(fleet_names, collapse = "|")), TRUE ~ NA_character_ ) @@ -270,4 +270,3 @@ expand_element <- function(input_list, fleet_names = "Pollock") { dplyr::select(-label_init) }) } - diff --git a/R/utils_plot.R b/R/utils_plot.R index e294167d..7f76b890 100644 --- a/R/utils_plot.R +++ b/R/utils_plot.R @@ -26,7 +26,7 @@ #' @details The user can create a line, point, or area plot, where the x-axis is #' year and y can vary for any time series quantity. Currently, grouping is #' restricted to one group where faceting can be any number of facets. -#' +#' #' @export #' #' @examples @@ -952,7 +952,6 @@ calculate_reference_point <- function( } else { ref_line_val } - } #------------------------------------------------------------------------------ diff --git a/R/utils_rda.R b/R/utils_rda.R index abe31d1f..b22ebaa6 100644 --- a/R/utils_rda.R +++ b/R/utils_rda.R @@ -56,7 +56,7 @@ fill_in_kqs <- function(df, ...) { #' added next to the names of the key quantities specified as ellipsis #' arguments. File is saved as "key_quantities.csv" to the working directory. #' @seealso [fill_in_kqs()], [insert_kqs()] -#' +#' #' @examples \dontrun{ #' export_kqs( #' F.min, @@ -96,7 +96,7 @@ export_kqs <- function(...) { #' and alternative text for figures and tables, with key quantities inserted #' into the "captions_alt_text_template.csv" template's placeholders. #' @seealso [fill_in_kqs()], [export_kqs()] -#' +#' #' @examples \dontrun{ #' insert_kqs( #' F.min, @@ -582,7 +582,7 @@ extract_caps_alttext <- function(topic_label = NULL, #' @returns An rda file with a figure's ggplot, caption, and alternative text, or #' a table's gt-based table, caption, and LaTeX-based table. #' @seealso [create_rda()], [extract_caps_alttext()] -#' +#' #' @export #' #' @examples diff --git a/man/convert_output.Rd b/man/convert_output.Rd index 5dad2c6e..2d238a1a 100644 --- a/man/convert_output.Rd +++ b/man/convert_output.Rd @@ -27,8 +27,8 @@ A reformatted and standardized version of assessment model results Format stock assessment output files to a standardized format. } \details{ -The resulting object is simply a transformed and machine readable -version of a model output file. Converted data frame is always returned. +The resulting object is simply a transformed and machine readable +version of a model output file. Converted data frame is always returned. It will also be saved if save_dir is not NULL. } \examples{ diff --git a/man/example_data.Rd b/man/example_data.Rd index 90e120b4..3cbf0892 100644 --- a/man/example_data.Rd +++ b/man/example_data.Rd @@ -46,7 +46,7 @@ A tibble with 591109 rows and 33 variables: example_data } \description{ -Included data set that represents a Report.sso file converted using +Included data set that represents a Report.sso file converted using convert_output(). This example is from the 2022 Petrale sole stock assessment. } \keyword{datasets} diff --git a/man/plot_landings.Rd b/man/plot_landings.Rd index 534fde54..a2419108 100644 --- a/man/plot_landings.Rd +++ b/man/plot_landings.Rd @@ -50,7 +50,7 @@ Default: NULL} \item{lbs}{A logical value indicating whether to convert the y-axis values from kilograms to pounds. The default units match the default in the -unit_label argument - 'metric tons'. +unit_label argument - 'metric tons'. Default: `FALSE`} diff --git a/man/plot_spawning_biomass.Rd b/man/plot_spawning_biomass.Rd index fff4f851..595807d4 100644 --- a/man/plot_spawning_biomass.Rd +++ b/man/plot_spawning_biomass.Rd @@ -65,7 +65,7 @@ Options: "early", "time", "fore" (forecast), or NULL (all data)} \item{lbs}{A logical value indicating whether to convert the y-axis values from kilograms to pounds. The default units match the default in the -unit_label argument - 'metric tons'. +unit_label argument - 'metric tons'. Default: `FALSE`} diff --git a/man/process_data.Rd b/man/process_data.Rd index ce7bb7cb..e4e2b6b2 100644 --- a/man/process_data.Rd +++ b/man/process_data.Rd @@ -18,7 +18,7 @@ variable(s) of the data.} \item{lbs}{A logical value indicating whether to convert the y-axis values from kilograms to pounds. The default units match the default in the -unit_label argument - 'metric tons'. +unit_label argument - 'metric tons'. Default: `FALSE`} diff --git a/man/reference_line.Rd b/man/reference_line.Rd index fc8fade9..5005a441 100644 --- a/man/reference_line.Rd +++ b/man/reference_line.Rd @@ -23,7 +23,7 @@ Default: 1} \item{lbs}{A logical value indicating whether to convert the y-axis values from kilograms to pounds. The default units match the default in the -unit_label argument - 'metric tons'. +unit_label argument - 'metric tons'. Default: `FALSE`} } diff --git a/man/stockplotr-package.Rd b/man/stockplotr-package.Rd index ce67c60e..0dcd782c 100644 --- a/man/stockplotr-package.Rd +++ b/man/stockplotr-package.Rd @@ -22,6 +22,7 @@ Useful links: Authors: \itemize{ + \item Samantha Schiano \email{samantha.schiano@noaa.gov} (\href{https://orcid.org/0009-0003-3744-6428}{ORCID}) \item Sophie Breitbart \email{sophie.breitbart@noaa.gov} (\href{https://orcid.org/0000-0001-9641-9786}{ORCID}) [contributor] \item Steve Saul \email{steven.saul@noaa.gov} } diff --git a/tests/testthat/test-plot_biomass.R b/tests/testthat/test-plot_biomass.R index b9e87194..f9b40089 100644 --- a/tests/testthat/test-plot_biomass.R +++ b/tests/testthat/test-plot_biomass.R @@ -7,7 +7,7 @@ load(file.path( # Below is now moot bc relative is coming from model results # Make another sample dataset for testing relative # n <- 448 -# +# # sim_df <- data.frame( # label = "biomass", # estimate = rlnorm(n, meanlog = 6.2, sdlog = 1.6), diff --git a/tests/testthat/test-plot_spawning_biomass.R b/tests/testthat/test-plot_spawning_biomass.R index 8dc1d811..267c2094 100644 --- a/tests/testthat/test-plot_spawning_biomass.R +++ b/tests/testthat/test-plot_spawning_biomass.R @@ -59,4 +59,3 @@ test_that("rda file made when indicated", { file.remove(fs::path(getwd(), "key_quantities.csv")) unlink(fs::path(getwd(), "figures"), recursive = T) }) - diff --git a/tests/testthat/test-save_all_plots.R b/tests/testthat/test-save_all_plots.R index ee5bc68c..1b268f39 100644 --- a/tests/testthat/test-save_all_plots.R +++ b/tests/testthat/test-save_all_plots.R @@ -41,15 +41,15 @@ test_that("save_all_plots works when all figures/tables are plotted", { ) # expect that the tables are all created with expected names - tab_base_temp_files <- c( + tab_base_temp_files <- c( # "bnc_table.rda", - # "indices.abundance_table.rda", - "landings_table.rda" - ) - expect_equal( - list.files(fs::path(getwd(), "tables")), - tab_base_temp_files - ) + # "indices.abundance_table.rda", + "landings_table.rda" + ) + expect_equal( + list.files(fs::path(getwd(), "tables")), + tab_base_temp_files + ) # erase temporary testing files file.remove(fs::path(getwd(), "captions_alt_text.csv"))