diff --git a/.Rbuildignore b/.Rbuildignore index c33ea379..e5aba7db 100644 --- a/.Rbuildignore +++ b/.Rbuildignore @@ -6,3 +6,5 @@ ^_pkgdown\.yml$ ^docs$ ^pkgdown$ +^\.positai$ +^\.claude$ diff --git a/.gitignore b/.gitignore index 1d947447..32db5cb3 100644 --- a/.gitignore +++ b/.gitignore @@ -13,3 +13,4 @@ docs stockplotr.Rproj *.Rproj !vignettes/figures/ +.positai diff --git a/DESCRIPTION b/DESCRIPTION index 46a2a9d9..d4e15fbf 100644 --- a/DESCRIPTION +++ b/DESCRIPTION @@ -1,7 +1,7 @@ Type: Package Package: stockplotr Title: Tables and Figures for Stock Assessments -Version: 0.12.0 +Version: 0.12.0.9000 Authors@R: c( person("Samantha", "Schiano", , "samantha.schiano@noaa.gov", role = c("aut", "cre"), comment = c(ORCID = "0009-0003-3744-6428")), diff --git a/NAMESPACE b/NAMESPACE index 19b69c0f..e5c39491 100644 --- a/NAMESPACE +++ b/NAMESPACE @@ -14,7 +14,7 @@ export(plot_biomass) export(plot_biomass_at_age) export(plot_catch_comp) export(plot_fishing_mortality) -export(plot_indices) +export(plot_index) export(plot_landings) export(plot_natural_mortality) export(plot_obsvpred) @@ -27,5 +27,6 @@ export(process_data) export(process_table) export(reference_line) export(save_all_plots) +export(table_index) export(table_landings) export(theme_noaa) diff --git a/R/convert_output.R b/R/convert_output.R index 78ebad67..9251e658 100644 --- a/R/convert_output.R +++ b/R/convert_output.R @@ -1933,7 +1933,7 @@ convert_output <- function( uncertainty = log_sd ) |> dplyr::mutate( - # label = "indices_observed", + # label = "index_observed", uncertainty_label = "log_sd", indices_predicted = dat$quantities$index_hat ) |> @@ -2013,7 +2013,7 @@ convert_output <- function( df_comp_obs <- dat$data_list$comp_data |> dplyr::rename_with(tolower) |> dplyr::mutate( - label = "indices_observed" + label = "index_observed" ) indexing_vars_cols <- colnames(df_comp_obs)[!grepl("comp", colnames(df_comp_obs))] diff --git a/R/plot_indices.R b/R/plot_index.R similarity index 95% rename from R/plot_indices.R rename to R/plot_index.R index a2a61d49..3adb37cc 100644 --- a/R/plot_indices.R +++ b/R/plot_index.R @@ -13,7 +13,7 @@ #' filtered. (i.e. select names of fleets to zoom into the plot) #' #' Default: NULL -#' @returns A plot showing the expected and predicted indices. +#' @returns A plot showing the expected and predicted index. #' #' @details The input is from an assessment model output file #' translated to a standardized output (\link[stockplotr]{convert_output}). @@ -25,13 +25,13 @@ #' @export #' #' @examples -#' plot_indices( +#' plot_index( #' dat = stockplotr:::example_data, #' unit_label = "fish/hr", #' interactive = FALSE #' ) #' -plot_indices <- function( +plot_index <- function( dat, unit_label = "", group = NULL, @@ -57,7 +57,7 @@ plot_indices <- function( # Filter data prepared_data <- filter_data( dat, - label_name = "indices", + label_name = "index", era = NULL, geom = "line", # ifelse guarantees the code doesn't miss grouping when label has > 1 value @@ -98,8 +98,8 @@ plot_indices <- function( dat = prepared_data, x = "year", y = "estimate", - observed_label = "indices_observed", - predicted_label = "indices_predicted", + observed_label = "index_observed", + predicted_label = "index_predicted", geom = "line", xlab = "Year", ylab = "Estimated Index", diff --git a/R/process_data.R b/R/process_data.R index 11ce6e7d..09c4bd59 100644 --- a/R/process_data.R +++ b/R/process_data.R @@ -532,8 +532,8 @@ process_table <- function( dplyr::rename( !!mod_uncert_lab := uncertainty ) |> - # set values to strings to include training zeros from rounding - dplyr::mutate(estimate = sprintf(glue::glue("%.{digits}f"), estimate)) |> + # set values to strings to include trailing zeros from rounding and # format large estimate values with commas + dplyr::mutate(estimate = formatC(estimate, format = "f", digits = digits, big.mark = ",")) |> tidyr::pivot_wider( id_cols = dplyr::all_of(c(stringr::str_to_title(mod_cols))), values_from = dplyr::all_of(c("estimate", mod_uncert_lab)), diff --git a/R/save_all_plots.R b/R/save_all_plots.R index 8db8bd57..737b57e8 100644 --- a/R/save_all_plots.R +++ b/R/save_all_plots.R @@ -80,7 +80,7 @@ #' #' Default: "mt" #' -#' @param indices_unit_label Units for index of abundance/CPUE +#' @param index_unit_label Units for index of abundance/CPUE #' #' Default: "" #' @@ -119,7 +119,7 @@ #' save_all_plots(dat, #' ref_line = "unfished", #' ref_line_sb = "target", -#' indices_unit_label = "CPUE", +#' index_unit_label = "CPUE", #' biomass_at_age_scale_amount = 1, #' biomass_at_age_unit_label = "metric tons" #' ) @@ -150,15 +150,15 @@ save_all_plots <- function( # imported from plot_biomass_at_age biomass_at_age_scale_amount = 1, biomass_at_age_unit_label = "mt", - # imported from plot_indices - indices_unit_label = "", + # imported from plot_index + index_unit_label = "", # imported from table_afsc_tier- add potential unique arguments after dev # imported from table_bnc biomass_unit_label = "mt", catch_unit_label = "mt", catch_scale_amount = 1 # imported from table_harvest_projection- add potential unique arguments after dev - # imported from table_indices- zero unique arguments + # imported from table_index- zero unique arguments # imported from table_landings- zero unique arguments ) { make_rda <- TRUE @@ -419,18 +419,18 @@ save_all_plots <- function( tryCatch( { - cli::cli_h2("plot_indices") - plot_indices(dat, - unit_label = indices_unit_label, + cli::cli_h2("plot_index") + plot_index(dat, + unit_label = index_unit_label, make_rda = TRUE, interactive = FALSE, figures_dir = figures_tables_dir ) # |> suppressWarnings() |> invisible() }, error = function(e) { - cli::cli_alert_danger("plot_indices failed to run.") + cli::cli_alert_danger("plot_index failed to run.") cli::cli_alert("Tip: check that your arguments are correct.") - cli::cli_li("indices_unit_label = {indices_unit_label}") + cli::cli_li("index_unit_label = {index_unit_label}") print(e) } ) @@ -462,8 +462,8 @@ save_all_plots <- function( # tryCatch( # { - # cli::cli_h2("table_indices") - # table_indices( + # cli::cli_h2("table_index") + # table_index( # dat, # make_rda = TRUE, # tables_dir = figures_tables_dir @@ -472,7 +472,7 @@ save_all_plots <- function( # # invisible() # }, # error = function(e) { - # cli::cli_alert_danger("table_indices failed to run.") + # cli::cli_alert_danger("table_index failed to run.") # cli::cli_alert("Tip: check that your arguments are correct.") # print(e) # } diff --git a/R/table_afsc_tier.R b/R/table_afsc_tier.R index 6ed6cd39..abb24da8 100644 --- a/R/table_afsc_tier.R +++ b/R/table_afsc_tier.R @@ -4,7 +4,7 @@ table_afsc_tier <- function() { # -adds make_rda and tables_dir as arguments # -defines topic_label, fig_or_table; and # -makes an rda if make_rda = TRUE - # (see table_indices.R for reference) + # (see table_index.R for reference) # for the rda-related fxns to work, the final table has to be called tab # identify output diff --git a/R/table_harvest_projection.R b/R/table_harvest_projection.R index 6a3c2b20..525f91d8 100644 --- a/R/table_harvest_projection.R +++ b/R/table_harvest_projection.R @@ -4,7 +4,7 @@ table_harvest_projection <- function() { # -adds make_rda and tables_dir as arguments # -defines topic_label, fig_or_table; and # -makes an rda if make_rda = TRUE - # (see table_indices.R for reference) + # (see table_index.R for reference) # for the rda-related fxns to work, the final table has to be called tab level <- c( diff --git a/R/table_index.R b/R/table_index.R new file mode 100644 index 00000000..3297c46d --- /dev/null +++ b/R/table_index.R @@ -0,0 +1,182 @@ +#' Index of abundance table +#' +#' @inheritParams plot_recruitment +#' @param group A string of a single column that groups the data. +#' +#' Set group = "none" to summarize data over all indexing values. +#' +#' Default: NULL +#' Options: Including, but not limited to: "year", "area", "fleet", "sex", "none", NULL +#' @param method A string describing the method of summarizing data when group +#' is set to "none". +#' +#' Default: "sum" +#' +#' Options: "sum" or "mean" +#' @param digits Numeric value indicating the number of digits values in the +#' table will be rounded to. +#' +#' Default: 2 +#' @param tables_dir The location of the folder containing the generated table +#' rda files ("tables") that will be created if the argument `make_rda` = TRUE. +#' +#' Default: the working directory (`getwd()`) +#' @param label The label that will be chosen from the input file. If unspecified, +#' the function will search the "label" column and use the first matching label +#' in this ordered list: "index_weight", "index_numbers", "index_expected", +#' "index_predicted", "index". +#' +#' Default: NULL +#' +#' @returns A table of observed annual index of abundance plus error, +#' stratified by fleet. +#' @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 +#' \dontrun{ +#' table_index(dat) +#' +#' table_index( +#' dat, +#' make_rda = TRUE, +#' tables_dir = getwd() +#' ) +#' } +table_index <- function( + dat, + era = NULL, + interactive = TRUE, + group = NULL, + method = "sum", + module = NULL, + label = NULL, + digits = 2, + make_rda = FALSE, + tables_dir = getwd() + ) { + + # TODO: do group and facet need to be uncommented and updated? + # Filter data for landings + prepared_data <- filter_data( + dat = dat, + label_name = "index", + geom = "line", + era = era, + module = module, + scale_amount = 1, + interactive = interactive + ) |> + dplyr::mutate(estimate = round(as.numeric(estimate), digits = digits), + uncertainty = round(as.numeric(uncertainty), digits = digits)) + + # Add check if there is any data + if (nrow(prepared_data) == 0) { + cli::cli_abort("No index data found.") + } + + # get uncertainty label by model + uncert_lab <- prepared_data |> + dplyr::filter(!is.na(uncertainty_label)) |> + dplyr::group_by(model) |> + dplyr::reframe(unique_uncert = unique(uncertainty_label)) # changed to reframe -- may cause errors + uncert_lab <- stats::setNames(uncert_lab$unique_uncert, uncert_lab$model) + # if (length(unique(uncert_lab)) == 1) uncert_lab <- unique(uncert_lab) # might need this line + + # This needs to be adjusted when comparing different models and diff error + if (length(uncert_lab) > 1 & length(unique(uncert_lab)) == 1 | length(names(uncert_lab)) == 1) { # prepared_data$model + # cli::cli_alert_warning("More than one value for uncertainty exists: {uncert_lab}") + uncert_lab <- uncert_lab[[1]] + # cli::cli_alert_warning("The first value ({uncert_lab}) will be chosen.") + } + + if (is.na(uncert_lab)) uncert_lab <- "uncertainty" + + # get fleet names + # TODO: change from fleets to id_group AFTER the process data step and adjust throughout the table based on indexing + fleets <- unique(prepared_data$fleet) |> + # sort numerically even if fleets are 100% characters + stringr::str_sort(numeric = TRUE) + + # TODO: fix this so that fleet names aren't removed if, e.g., group = "fleet" + table_data_info <- process_table( + dat = prepared_data, + # group = group, + method = method, + label = label, + digits = digits + ) + table_data <- table_data_info[[1]] + indexed_vars <- table_data_info[[2]] + id_col_vals <- table_data_info[[3]] + + # id_group_vals <- sapply(id_cols, function(x) unique(prepared_data[[x]]), simplify = FALSE) + # TODO: add check if there is a index column for every error column -- if not remove the error (can keep index) + + # merge error and index columns and rename + df_list <- merge_error( + table_data, + uncert_lab, + fleets, + label = "index", + unit_label = "" # should this be CPUE? + ) + + # transform dfs into tables + final <- lapply(df_list, function(df) { + df |> + gt::gt() |> + add_theme() + }) + + # export figure to rda if argument = T + if (make_rda == TRUE) { + + # Caption contains no key quantities for index table + # So, export captions/alt text csv if absent + if (!file.exists(fs::path(getwd(), "captions_alt_text.csv"))) { + caps_alttext <- utils::read.csv( + system.file("resources", "captions_alt_text_template.csv", package = "stockplotr") + ) + # export df with captions and alt text to csv + utils::write.csv( + x = caps_alttext, + file = fs::path(getwd(), "captions_alt_text.csv"), + row.names = FALSE + ) + } + + if (length(df_list) == 1) { + create_rda( + object = final$label, + # get name of function and remove "table_" from it + topic_label = gsub("table_", "", as.character(sys.call()[[1]])), + fig_or_table = "table", + dat = dat, + dir = tables_dir, + scale_amount = 1, + unit_label = unit_label, + table_df = final + ) + } + } else { + cli::cli_alert_warning("Multiple tables cannot be exported at this time.") + cli::cli_alert_info("We are currently developing this feature.") + } + + # Send table(s) to viewer + if (!is.data.frame(table_data)) { + for (t in final) { + print(t) + } + # Return table list invisibly + return(invisible(final)) + } else { + # Return finished table (when only one table) + return(final) + } +} diff --git a/R/table_indices.R b/R/table_indices.R deleted file mode 100644 index 90b20992..00000000 --- a/R/table_indices.R +++ /dev/null @@ -1,173 +0,0 @@ -# #' Create Indices of Abundance Table -# #' -# #' @inheritParams plot_recruitment -# #' @param tables_dir The location of the folder containing the generated table -# #' rda files ("tables") that will be created if the argument `make_rda` = TRUE. -# #' Default: the working directory (`getwd()`) -# #' @returns A table of observed annual indices of abundance plus error -# #' stratified by fleet. -# #' @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 -# #' \dontrun{ -# #' table_indices(dat) -# #' -# #' table_indices( -# #' dat, -# #' end_year = 2024, -# #' make_rda = TRUE, -# #' tables_dir = getwd() -# #' ) -# #' } -# table_indices <- function( -# dat, -# end_year = format(Sys.Date(), "%Y"), -# make_rda = FALSE, -# tables_dir = getwd()) { -# # create plot-specific variables to use throughout fxn for naming and IDing -# topic_label <- "indices.abundance" - -# # identify output -# fig_or_table <- "table" - -# # check year isn't past end_year if not projections plot -# check_year( -# end_year = end_year, -# fig_or_table = fig_or_table, -# topic = topic_label -# ) - -# # Load data -# output <- dat |> -# dplyr::filter(module_name == "INDEX_2" | module_name == "t.series") |> -# dplyr::filter(year <= end_year) -# # Check for U -# if (any(unique(output$module_name == "INDEX_2"))) { -# output <- output |> -# dplyr::filter( -# grepl("expected_indices", label) | grepl("indices_predicted", label) -# ) # grepl("input_indices", label) | -# } else if (any(unique(output$module_name == "t.series"))) { -# output <- output |> -# dplyr::filter(grepl("cpue", label)) -# } - -# # Extract fleet names -# fleet_names <- unique(as.character(output$fleet)) -# factors <- c("year", "fleet", "fleet_name", "age", "sex", "area", "seas", "season", "time", "era", "subseas", "subseason", "platoon", "platoo", "growth_pattern", "gp") -# # re-structure df for table -# indices <- output |> -# tidyr::pivot_wider( -# # id_cols = c(year, uncertainty, uncertainty_label), -# names_from = label, -# values_from = estimate -# ) |> -# dplyr::select(year, fleet, unique(output$label), uncertainty, uncertainty_label) # |> - -# # na.omit() -# # check if uncertainty is a measure in the df -# if (all(is.na(indices$uncertainty))) { -# indices <- indices |> -# dplyr::select(-c(uncertainty_label, uncertainty)) -# } else { -# uncertainty_col <- paste("uncertainty_", unique(indices$uncertainty_label), sep = "") -# colnames(indices) <- stringr::str_replace(colnames(indices), "^uncertainty$", uncertainty_col) -# indices <- dplyr::select(indices, -uncertainty_label) -# } - -# # Check if observed/inital values are in the df -# if (any(grepl("observed", colnames(indices)))) { -# indices <- indices |> -# dplyr::select(-colnames(indices)[grep(c("observed"), colnames(indices))]) -# } - -# # rename columns to remove cpue/effort -# if (any(grep("_indices", colnames(indices)))) { -# colnames(indices) <- stringr::str_replace_all(colnames(indices), "_indices", "") -# } else if (any(grep("indices_", colnames(indices)))) { -# colnames(indices) <- stringr::str_replace_all(colnames(indices), "indices_", "") -# } else { -# colnames(indices) <- stringr::str_replace_all(colnames(indices), "cpue_", "") -# } - -# # Check for which column is U and filter out na values -# if (any(grep("predicted", colnames(indices)))) { -# indices <- indices |> -# dplyr::filter(!is.na(predicted)) -# } -# if (any(grep("expected", colnames(indices)))) { -# indices <- indices |> -# dplyr::filter(!is.na(expected)) -# } - -# # move fleet data into own columns -# indices2 <- indices |> -# tidyr::pivot_wider( -# names_from = fleet, -# values_from = colnames(indices)[!colnames(indices) %in% c("year", "fleet")] -# ) |> -# dplyr::select(year, dplyr::ends_with(fleet_names)) - -# fleet_col_names <- stringr::str_extract(colnames(indices2)[colnames(indices2) != "year"], "[^_]+$") -# if (any(grepl("[0-9]+", fleet_col_names))) { -# fleet_header_lab <- "" -# fleet_col_names <- paste("Fleet ", fleet_col_names) -# } else { -# fleet_header_lab <- "Fleet" -# } - -# tab <- indices2 |> -# dplyr::mutate(dplyr::across(where(is.numeric), ~ round(.x, 2)), -# year = as.character(year) -# ) |> -# flextable::flextable() |> -# flextable::set_header_labels( -# # TODO: set uncertainty to the actual value instead of word uncertainty -# values = c("Year", rep(c("Estimated CPUE", "Uncertainty"), (ncol(indices2) - 1) / 2)) -# ) |> -# flextable::add_header_row( -# values = c(fleet_header_lab, fleet_col_names) -# ) |> -# flextable::merge_h(part = "header") |> -# flextable::align(part = "header") - -# final <- suppressWarnings(add_theme(tab)) - -# # export table to rda if argument = T -# if (make_rda) { -# # run write_captions.R if its output doesn't exist -# if (!file.exists( -# fs::path(getwd(), "captions_alt_text.csv") -# ) -# ) { -# stockplotr::write_captions( -# dat = dat, -# dir = tables_dir, -# year = end_year -# ) -# } - -# # extract this plot's caption and alt text -# caps_alttext <- extract_caps_alttext( -# topic_label = topic_label, -# fig_or_table = fig_or_table, -# dir = tables_dir -# ) - - -# export_rda( -# object = final, -# caps_alttext = caps_alttext, -# figures_tables_dir = tables_dir, -# # get name of function and remove "table_" from it -# topic_label = gsub("table_", "", as.character(sys.call()[[1]])), -# fig_or_table = fig_or_table -# ) -# } -# final -# } diff --git a/R/utils_rda.R b/R/utils_rda.R index a2125ecc..8ab617ca 100644 --- a/R/utils_rda.R +++ b/R/utils_rda.R @@ -404,11 +404,11 @@ create_rda <- function( # mod.fit.catch.max <- # maximum catch -## mod_fit_abun (model fit to abundance indices plot)- don't code quantities yet -# start year of model fit to abundance indices plot +## mod_fit_abun (model fit to abundance index plot)- don't code quantities yet +# start year of model fit to abundance index plot # mod.fit.abun.start.year <- -# end year of model fit to abundance indices plot +# end year of model fit to abundance index plot # mod.fit.abun.end.year <- ## mod_fit_discards- will be by fleet diff --git a/inst/resources/bam_var_names.csv b/inst/resources/bam_var_names.csv index 2f788ed7..84a4c385 100644 --- a/inst/resources/bam_var_names.csv +++ b/inst/resources/bam_var_names.csv @@ -182,13 +182,13 @@ sel.age,sel.v,sel_v sel.age,sel.v.Mcvt,sel_v_Mcvt ,sel.m,sel_m ,sel.m.D,sel_m_D -comp.mats,lcomp.ob,length_composition_expected +comp.mats,lcomp.ob,length_composition_observed ,lcomp.pr,length_composition_predicted -,lcomp.D.ob,length_composition_discard_expected +,lcomp.D.ob,length_composition_discard_observed ,lcomp.D.pr,length_composition_discard_predicted -,acomp.ob,age_composition_expected +,acomp.ob,age_composition_observed ,acomp.pr,age_composition_predicted -,acomp.Mcvt.ob,age_composition_expected +,acomp.Mcvt.ob,age_composition_observed ,acomp.Mcvt.pr,age_composition_predicted sdnr,sdnr.U,sdnr_U t.series,F.Fmsy,F_F_msy @@ -209,17 +209,20 @@ t.series,total.L.klb,landings_weight t.series,total.L.knum,landings_numbers t.series,total.D.klb,discards_weight t.series,total.D.knum,discards_numbers -t.series,U.ob,indices_expected -t.series,U.pr,indices_predicted -t.series,cv.U,indices_cv +t.series,U.ob,index_observed +t.series,U.pr,index_predicted +t.series,cv.U,index_cv +t.series,u.ob,index_observed +t.series,u.pr,index_predicted +t.series,cv.u,index_cv t.series,q.rate.mult,catchability_rate t.series,q.DD.mult,q_DD_mult t.series,q.DD.B.4plus,q_DD_B_4plus t.series,q.RW.log.dev,q_RW_log_dev -t.series,L.ob,landings_expected +t.series,L.ob,landings_observed t.series,L.pr,landings_predicted t.series,cv.L,landings_cv -t.series,D.ob,discard_expected +t.series,D.ob,discard_observed t.series,D.pr,discard_predicted t.series,cv.D,discard_cv t.series,cl.D.release,cl_D_release diff --git a/inst/resources/captions_alt_text_template.csv b/inst/resources/captions_alt_text_template.csv index 07e829c0..3ccf825b 100644 --- a/inst/resources/captions_alt_text_template.csv +++ b/inst/resources/captions_alt_text_template.csv @@ -12,7 +12,7 @@ maturity.schedule,figure,The relationship between the proportion mature and fish fecundity.at.length,figure,Fecundity (in number of eggs) as a function of fish length. ,"Point and line graph showing observations of measured fecundity and measured length from the same fish and an exponential fit through those points displayed as a line. The x axis shows length in fecundity.length.units, which spans from fecundity.length.min to fecundity.length.max. The y axis shows fecundity in fecundity.units, which spans from fecundity.min to fecundity.max." catch,figure,"Historical catch for each year in which there is composition data, for each fleet or survey.","Cumulative area plot showing the catch for each year and fleet or survey. The x axis shows the year, which spans from catch.year.min to catch.year.max. The y axis shows the proportion of the total catch by each fleet or survey and spans from tot.catch.min to tot.catch.max." CAL,figure,"Histograms showing the proportion of the catch in each length group, each year for which there is composition data, for fleet or survey fleet.or.survey.name.","Histograms for each year and fleet for which there is data (one per year grouped by fleet or survey), which show the proportion of the catch in each length group. The x axis of each histogram contains length intervals, which span from cal.length.min to cal.length.max. The y axis of each histogram contains the proportion of the catch and spans from 0--1." -indices,figure,Catch per unit effort (CPUE) over time for fleet or survey. 95\\% confidence intervals are shown for each survey/fleet.,"Line graph showing catch per unit effort (CPUE) over time, stratified by survey/fleet. The x axis shows the year, which spans from cpue.start.year to cpue.end.year. The y axis shows CPUE in cpue.units, which spans from cpue.min to cpue.max." +index,figure,Catch per unit effort (CPUE) over time for fleet or survey. 95\\% confidence intervals are shown for each survey/fleet.,"Line graph showing catch per unit effort (CPUE) over time, stratified by survey/fleet. The x axis shows the year, which spans from cpue.start.year to cpue.end.year. The y axis shows CPUE in cpue.units, which spans from cpue.min to cpue.max." abundance_at_age,figure,Model estimate of population numbers at age over time. The relative size of each bubble for a given year and age indicates the relative abundance in that category compared with others. ,"Bubble plot showing relative age proportions over time. The x axis shows the year, which spans from pop.naa.start.year to pop.naa.end.year. The y axis shows age in years, which spans from pop.naa.age.min to pop.naa.age.max. The size of the bubbles range from pop.naa.fish.min to pop.naa.fish.max." mod.fit.catch,figure,Observed catch from the data input file (points) and model estimated catch (line) over time for fleet.or.survey.name. ,"Point and line graph showing observed catch from the data input file as points and model estimated catch as a line over time for fleet.or.survey.name. The x axis shows years, which spans from mod.fit.catch.start.year to mod.fit.catch.end.year. The y axis shows catch in mod.fit.catch.units, which spans from mod.fit.catch.min to mod.fit.catch.max." mod.fit.abun,figure,Assessment model fits to input catch per unit of effort index values over time calculated from fleet.or.survey.name.,"Point and line graph showing the assessment model fit, displayed as a line, to input catch per unit effort index values, displayed as points over time, for fleet.or.survey.name. The x axis shows years, which spans from mod.fit.abun.start.year to mod.fit.abun.end.year. The y axis shows catch per unit effort in cpue.units, which spans from cpue.min to cpue.max." @@ -37,7 +37,7 @@ life.history.params,table,Life history parameters used in the stock assessment m landings,table,Landed catch by fleet and year in landings.units., discards,table,Discarded catch by fleet and year in discards.tbl.units., age.length.key,table,Age-length key: the proportion of fish for each age that belong to a particular length group. , -indices,table,Calculated indices of abundance and their corresponding CVs for the fleets and surveys identified in the column headers. , +index,table,Calculated index of abundance and corresponding CVs for the fleets and surveys identified in the column headers. , model.runs,table,"The base configuration and alternative sensitivity analysis configurations of the stock assessment model, in which parameters and/or data input streams are changed from one configuration to another.", derived.quantities,table,Derived quantities calculated by the base configuration of the stock assessment model., est.params,table,Parameters used in the base stock assessment model and whether the parameter was estimated by the model or fixed (i.e. not allowed to be estimated or changed by the model). CVs for estimated models are provided., diff --git a/inst/resources/fims_var_names.csv b/inst/resources/fims_var_names.csv index 3a678437..3d295826 100644 --- a/inst/resources/fims_var_names.csv +++ b/inst/resources/fims_var_names.csv @@ -2,12 +2,12 @@ module_name,label,alt_label Fleet,age_to_length_conversion, Fleet,agecomp_expected,age_composition_expected Fleet,agecomp_proportion,age_composition_proportion -Fleet,index_expected,indices_expected -Fleet,index_naa,indices -Fleet,index_nal,indices -Fleet,index_numbers,indices_numbers -Fleet,index_waa,indicies_weight -Fleet,index_weight,indicies_weight +Fleet,index_expected, +Fleet,index_naa,index +Fleet,index_nal,index +Fleet,index_numbers, +Fleet,index_waa,index_weight +Fleet,index_weight, Fleet,landings_expected, Fleet,landings_naa,landings Fleet,landings_nal,landings @@ -34,9 +34,9 @@ selectivity,slope, ,AgeCompositionExpected,age_composition_expected ,AgeCompositionProportion,age_composition_proportion ,FMort,fishing_mortality -,IndexExpected,indices_expected -,IndexNumberAtAge,indices_numbers -,IndexNumberAtLength,indices_numbers +,IndexExpected,index_expected +,IndexNumberAtAge,index_numbers +,IndexNumberAtLength,index_numbers ,LandingsExpected,landings_expected ,LandingsNumberAtAge,landings_numbers ,LandingsNumberAtLength,landings_numbers diff --git a/inst/resources/ss3_var_names.csv b/inst/resources/ss3_var_names.csv index 13053e5a..5d97027a 100644 --- a/inst/resources/ss3_var_names.csv +++ b/inst/resources/ss3_var_names.csv @@ -57,9 +57,9 @@ OVERALL_COMPS,female, OVERALL_COMPS,male, BIOMASS_AT_AGE,biomass, CATCH,obs,landings_observed_weight -INDEX_2,obs,indices_observed +INDEX_2,obs,index_observed CATCH,exp,landings_predicted_weight -INDEX_2,exp,indices_predicted +INDEX_2,exp,index_predicted CATCH,mult, CATCH,exp*mult, CATCH,f, diff --git a/man/plot_indices.Rd b/man/plot_index.Rd similarity index 94% rename from man/plot_indices.Rd rename to man/plot_index.Rd index cec8ad08..d7f15a22 100644 --- a/man/plot_indices.Rd +++ b/man/plot_index.Rd @@ -1,10 +1,10 @@ % Generated by roxygen2: do not edit by hand -% Please edit documentation in R/plot_indices.R -\name{plot_indices} -\alias{plot_indices} +% Please edit documentation in R/plot_index.R +\name{plot_index} +\alias{plot_index} \title{Plot Index of Abundance} \usage{ -plot_indices( +plot_index( dat, unit_label = "", group = NULL, @@ -73,7 +73,7 @@ The folder is created within the path if it does not exist.} \item{...}{Arguments called from \link[ggplot2]{geom_line} or \link[ggplot2]{geom_point}} } \value{ -A plot showing the expected and predicted indices. +A plot showing the expected and predicted index. } \description{ Plot Index of Abundance @@ -85,7 +85,7 @@ There are options to return a `ggplot2` object or export an .rda object containing associated caption and alternative text for the figure. } \examples{ -plot_indices( +plot_index( dat = stockplotr:::example_data, unit_label = "fish/hr", interactive = FALSE diff --git a/man/save_all_plots.Rd b/man/save_all_plots.Rd index 45bc0e8a..b4f73106 100644 --- a/man/save_all_plots.Rd +++ b/man/save_all_plots.Rd @@ -22,7 +22,7 @@ save_all_plots( abundance_at_age_unit_label = "fish", biomass_at_age_scale_amount = 1, biomass_at_age_unit_label = "mt", - indices_unit_label = "", + index_unit_label = "", biomass_unit_label = "mt", catch_unit_label = "mt", catch_scale_amount = 1 @@ -121,7 +121,7 @@ Default: 1} Default: "mt"} -\item{indices_unit_label}{Units for index of abundance/CPUE +\item{index_unit_label}{Units for index of abundance/CPUE Default: ""} @@ -153,7 +153,7 @@ translated to a standardized output (\link[stockplotr]{convert_output}). save_all_plots(dat, ref_line = "unfished", ref_line_sb = "target", - indices_unit_label = "CPUE", + index_unit_label = "CPUE", biomass_at_age_scale_amount = 1, biomass_at_age_unit_label = "metric tons" ) diff --git a/man/table_index.Rd b/man/table_index.Rd new file mode 100644 index 00000000..f7c1ef99 --- /dev/null +++ b/man/table_index.Rd @@ -0,0 +1,108 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/table_index.R +\name{table_index} +\alias{table_index} +\title{Index of abundance table} +\usage{ +table_index( + dat, + era = NULL, + interactive = TRUE, + group = NULL, + method = "sum", + module = NULL, + label = NULL, + digits = 2, + make_rda = FALSE, + tables_dir = getwd() +) +} +\arguments{ +\item{dat}{A tibble or named list of tibbles (input as `list()`) +returned from \link[stockplotr]{convert_output}. + +If inputting a list of tibbles, the first tibble's reference point defined +in `ref_line` is used to plot a reference line or calculate relative spawning biomass.} + +\item{era}{A string naming the era of data. + +Default: "time" + +Options: "early", "time", "fore" (forecast), or NULL (all data)} + +\item{interactive}{A logical value indicating if the environment is interactive. + +Default: `FALSE`} + +\item{group}{A string of a single column that groups the data. + +Set group = "none" to summarize data over all indexing values. + +Default: NULL +Options: Including, but not limited to: "year", "area", "fleet", "sex", "none", NULL} + +\item{method}{A string describing the method of summarizing data when group +is set to "none". + +Default: "sum" + +Options: "sum" or "mean"} + +\item{module}{(Optional) A string indicating the module_name found in `dat`. +If selecting >1 module, place them in a vector like c("module1", "module2"). + +Default: NULL + +If the interactive and >1 module_name is found, user will select the +module_name in the console. @seealso [filter_data()]} + +\item{label}{The label that will be chosen from the input file. If unspecified, +the function will search the "label" column and use the first matching label +in this ordered list: "index_weight", "index_numbers", "index_expected", +"index_predicted", "index". + +Default: NULL} + +\item{digits}{Numeric value indicating the number of digits values in the +table will be rounded to. + +Default: 2} + +\item{make_rda}{A logical value indicating whether to save the object and +make an automated caption and alternative text in the form of an `rda` object. If TRUE, +the rda will be exported to the folder indicated in the argument "figures_dir". + +Default: `FALSE`.} + +\item{tables_dir}{The location of the folder containing the generated table +rda files ("tables") that will be created if the argument `make_rda` = TRUE. + +Default: the working directory (`getwd()`)} +} +\value{ +A table of observed annual index of abundance plus error, +stratified by fleet. +} +\description{ +Index of abundance table +} +\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. +} +\examples{ +\dontrun{ +table_index(dat) + +table_index( + dat, + make_rda = TRUE, + tables_dir = getwd() +) +} +} +\seealso{ +[convert_output()], [filter_data()], [process_table()], [export_kqs()], [insert_kqs()], [create_rda()] +} diff --git a/tests/testthat/test-html_all_figs_tables.R b/tests/testthat/test-html_all_figs_tables.R index cbc7bb7a..bf4c423f 100644 --- a/tests/testthat/test-html_all_figs_tables.R +++ b/tests/testthat/test-html_all_figs_tables.R @@ -12,7 +12,7 @@ load(file.path( # recruitment_scale_amount = 1, # ref_line = c("unfished" = 1000), # ref_line_sb = "msy", -# indices_unit_label = "CPUE", +# index_unit_label = "CPUE", # figures_tables_dir = getwd() # ) |> # suppressWarnings() @@ -49,7 +49,7 @@ load(file.path( # recruitment_scale_amount = 1, # ref_line = c("unfished"=1000), # ref_line_sb = "msy", -# indices_unit_label = "CPUE", +# index_unit_label = "CPUE", # figures_tables_dir = getwd() # ) |> # suppressWarnings() @@ -79,7 +79,7 @@ load(file.path( # ref_line = "unfished", # ref_point = 1000, # ref_line_sb = "msy", -# indices_unit_label = "CPUE", +# index_unit_label = "CPUE", # figures_tables_dir = getwd() # ) |> # suppressWarnings() diff --git a/tests/testthat/test-plot_indices.R b/tests/testthat/test-plot_indices.R index e4053e74..cccf9df2 100644 --- a/tests/testthat/test-plot_indices.R +++ b/tests/testthat/test-plot_indices.R @@ -4,31 +4,31 @@ load(file.path( "std_output.rda" )) -test_that("plot_indices generates plots without errors", { +test_that("plot_index generates plots without errors", { # expect error-free plot with minimal arguments expect_no_error( - plot_indices(out_new) + plot_index(out_new) ) # expect ggplot object is returned expect_s3_class( - plot_indices(out_new), + plot_index(out_new), "gg" ) }) test_that("rda file made when indicated", { # export rda - plot_indices(out_new, + plot_index(out_new, make_rda = TRUE, unit_label = "metric tons", figures_dir = getwd() ) - # expect that both figures dir and the indices_figure.rda file exist + # expect that both figures dir and the index_figure.rda file exist expect_true(dir.exists(fs::path(getwd(), "figures"))) - expect_true(file.exists(fs::path(getwd(), "figures", "indices_figure.rda"))) + expect_true(file.exists(fs::path(getwd(), "figures", "index_figure.rda"))) # erase temporary testing files file.remove(fs::path(getwd(), "captions_alt_text.csv")) diff --git a/tests/testthat/test-save_all_plots.R b/tests/testthat/test-save_all_plots.R index 1b268f39..f5ebfca2 100644 --- a/tests/testthat/test-save_all_plots.R +++ b/tests/testthat/test-save_all_plots.R @@ -11,7 +11,7 @@ test_that("save_all_plots works when all figures/tables are plotted", { recruitment_scale_amount = 1, ref_line = c("unfished" = 1000), ref_line_sb = c("msy"), - # indices_unit_label = "CPUE", + # index_unit_label = "CPUE", figures_tables_dir = getwd(), interactive = FALSE ) @@ -23,7 +23,7 @@ test_that("save_all_plots works when all figures/tables are plotted", { # expect that the figures are all created with expected names fig_base_temp_files <- c( "biomass_figure.rda", - "indices_figure.rda", + "index_figure.rda", "fishing_mortality_figure.rda", "landings_figure.rda", "natural_mortality_figure.rda", @@ -43,7 +43,7 @@ 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( # "bnc_table.rda", - # "indices.abundance_table.rda", + # "index.abundance_table.rda", "landings_table.rda" ) expect_equal( diff --git a/tests/testthat/test-table_indices.R b/tests/testthat/test-table_indices.R index 50081a07..13f2cc78 100644 --- a/tests/testthat/test-table_indices.R +++ b/tests/testthat/test-table_indices.R @@ -1,65 +1,57 @@ -# # load sample dataset -# load(file.path( -# "fixtures", "ss3_models_converted", "Hake_2018", -# "std_output.rda" -# )) - -# test_that("table_indices generates plots without errors", { -# # expect error-free plot with minimal arguments -# expect_no_error( -# stockplotr::table_indices(out_new) -# ) - -# # expect error-free plot with many arguments -# expect_no_error( -# stockplotr::table_indices( -# out_new, -# end_year = 2024, -# make_rda = FALSE, -# tables_dir = getwd() -# ) -# ) - - -# # expect flextable object is returned -# expect_s3_class( -# stockplotr::table_indices( -# out_new, -# make_rda = FALSE, -# tables_dir = getwd() -# ), -# "flextable" -# ) -# }) - -# test_that("rda file made when indicated", { -# # export rda -# table_indices( -# out_new, -# end_year = 2024, -# make_rda = TRUE, -# tables_dir = getwd() -# ) - -# # expect that both tables dir and the indices.abundance_table.rda file exist -# expect_true(dir.exists(fs::path(getwd(), "tables"))) -# expect_true(file.exists(fs::path(getwd(), "tables", "indices.abundance_table.rda"))) - -# # erase temporary testing files -# file.remove(fs::path(getwd(), "captions_alt_text.csv")) -# file.remove(fs::path(getwd(), "key_quantities.csv")) - -# unlink(fs::path(getwd(), "tables"), recursive = T) -# }) - -# test_that("table_indices generates error with future end_year", { -# # expect error -# expect_error( -# stockplotr::table_indices( -# out_new, -# end_year = 2035, -# make_rda = TRUE, -# tables_dir = getwd() -# ) -# ) -# }) +# load sample dataset +load(file.path( + "fixtures", "ss3_models_converted", "Hake_2018", + "std_output.rda" +)) + +test_that("table_index generates plots without errors", { + # expect error-free plot with minimal arguments + expect_no_error( + table_index( + out_new, + interactive = FALSE + ) + ) + + # expect error-free plot with many arguments + expect_no_error( + table_index( + dat = out_new, + make_rda = FALSE, + tables_dir = getwd() + ) + ) + + + # expect gt object is returned + # adjust this test to work for multiple output tables + # expect_s3_class( + # table_index( + # dat = out_new, + # unit_label = "mt", + # era = NULL, + # interactive = FALSE, + # module = "CATCH", + # make_rda = FALSE, + # tables_dir = getwd() + # ), + # "gt_tbl" + # ) +}) + +test_that("rda file made when indicated", { + # export rda + table_index( + dat = out_new, + make_rda = TRUE, + tables_dir = getwd() + ) + + # expect that both tables dir and the index_table.rda file exist + expect_true(dir.exists(fs::path(getwd(), "tables"))) + expect_true(file.exists(fs::path(getwd(), "tables", "index_table.rda"))) + + # erase temporary testing files + file.remove(fs::path(getwd(), "captions_alt_text.csv")) + unlink(fs::path(getwd(), "tables"), recursive = T) +}) diff --git a/vignettes/faqs.Rmd b/vignettes/faqs.Rmd index 6f860fbd..51155a14 100644 --- a/vignettes/faqs.Rmd +++ b/vignettes/faqs.Rmd @@ -21,7 +21,7 @@ For more context, please read the function documentation and refer to the docume # Captions and alternative text (alt text) ## How are captions and alt text constructed? -When a plotting function (e.g., `plot_biomass()`, `table_indices()`, `save_all_plots()`) is run, placeholders within the plot's associated alt text and captions are replaced with key quantities (see the [{asar} package's Accessibility vignette](https://nmfs-ost.github.io/asar/articles/accessibility_guide.html) and the {stockplotr} ["How captions and alternative text are generated" vignette](https://nmfs-ost.github.io/stockplotr/articles/how-caps-alttext-are-made.html) for more details). +When a plotting function (e.g., `plot_biomass()`, `table_index()`, `save_all_plots()`) is run, placeholders within the plot's associated alt text and captions are replaced with key quantities (see the [{asar} package's Accessibility vignette](https://nmfs-ost.github.io/asar/articles/accessibility_guide.html) and the {stockplotr} ["How captions and alternative text are generated" vignette](https://nmfs-ost.github.io/stockplotr/articles/how-caps-alttext-are-made.html) for more details). As stated in the [Accessibility vignette's "Your to-do list" section](https://nmfs-ost.github.io/asar/articles/accessibility_guide.html#your-to-do-list), **you should always:**