From 5f90d6a666894e684afa398738339d1071136948 Mon Sep 17 00:00:00 2001 From: sbreitbart-NOAA <181890943+sbreitbart-NOAA@users.noreply.github.com> Date: Thu, 19 Nov 2026 18:09:34 +0000 Subject: [PATCH] style and docs: run devtools::document() and style with styler or air --- DESCRIPTION | 8 +- R/conout_ss3.R | 4 +- R/convert_output.R | 461 ++++++++++---------- R/plot_abundance_at_age.R | 4 +- R/plot_composition_diagnostics.R | 1 - R/plot_recruitment.R | 2 +- R/plot_retrospective.R | 166 ++++--- R/plot_selectivity.R | 2 +- R/plot_spawning_biomass.R | 2 +- R/plot_spr.R | 2 +- R/plot_stock_recruitment.R | 2 +- R/table_biomass_abundance_catch.R | 4 +- R/table_index.R | 4 +- R/table_landings.R | 3 +- R/table_projections.R | 10 +- R/table_total_catch.R | 2 +- R/utils_composition.R | 4 +- R/utils_plot.R | 128 +++--- man/filter_data.Rd | 12 +- man/filter_interactive.Rd | 12 +- man/plot_discard.Rd | 1 + man/plot_retrospective.Rd | 10 +- tests/testthat/test-convert_output.R | 30 +- tests/testthat/test-export_rda.R | 4 +- tests/testthat/test-plot_abundance_at_age.R | 17 +- tests/testthat/test-plot_retrospective.R | 42 +- tests/testthat/test-plot_spawning_biomass.R | 17 +- tests/testthat/test-utils_plot.R | 8 +- 28 files changed, 477 insertions(+), 485 deletions(-) diff --git a/DESCRIPTION b/DESCRIPTION index 39284503..bb9bc23c 100644 --- a/DESCRIPTION +++ b/DESCRIPTION @@ -53,6 +53,7 @@ Imports: tidyselect, utils Suggests: + FIMS, flextable, here, kableExtra, @@ -60,13 +61,12 @@ Suggests: quarto, r4ss, rmarkdown, - testthat (>= 3.0.0), - FIMS + testthat (>= 3.0.0) VignetteBuilder: knitr Remotes: - r4ss/r4ss, - NOAA-FIMS/FIMS + NOAA-FIMS/FIMS, + r4ss/r4ss Config/roxygen2/version: 8.1.1 Config/testthat/edition: 3 Config/testthat/parallel: true diff --git a/R/conout_ss3.R b/R/conout_ss3.R index e7278220..fb3f528b 100644 --- a/R/conout_ss3.R +++ b/R/conout_ss3.R @@ -1264,7 +1264,7 @@ conout_ss3 <- function( ) } out_new <- Reduce(rbind, out_list) - + # Composition data by bin from r4ss (lendbase, agedbase, condbase) if (!is.character(file)) { comp_rows <- ss3_composition_rows( @@ -1279,7 +1279,7 @@ conout_ss3 <- function( out_new <- rbind(out_new, comp_rows) } } - + out_new |> dplyr::mutate( fleet = if (any(unique(out_new$fleet) %in% fleet_names)) fleet else fleet_names[fleet], diff --git a/R/convert_output.R b/R/convert_output.R index 0742ca5c..3edb5bc8 100644 --- a/R/convert_output.R +++ b/R/convert_output.R @@ -3,30 +3,30 @@ #' Format stock assessment output file to a standardized tibble. #' #' @param files List of Paths. Assessment model output file paths. Currently accepts SS3 -#' `r4ss::ss_output()` or Report.sso file (being deprecated), BAM .rda file, Rceattle model object, -#' and FIMS output (the tibble returned by `FIMS::get_estimates()`, a `FIMSFit` object, or an .rds -#' file with either). If multiple elements, all valid models will be read, converted, and +#' `r4ss::ss_output()` or Report.sso file (being deprecated), BAM .rda file, Rceattle model object, +#' and FIMS output (the tibble returned by `FIMS::get_estimates()`, a `FIMSFit` object, or an .rds +#' file with either). If multiple elements, all valid models will be read, converted, and #' appended together. -#' +#' #' `names(files)` will be used as the name of the model in the output. -#' +#' #' @param models Character vector Assessment model used in evaluation #' #' Default: NULL #' #' Options: "ss3", "bam", "fims", "rceattle" -#' +#' #' Should match length of `files` if >1 model. -#' +#' #' @param fleet_names List of named character vectors. Names of fleets in the assessment model as #' shortened in the output file or names of fleets to replace the native fleet #' names in the output. For example, if fleet names in the model are 1, 2, 3 #' then fleet_names = c("fleet1" = 1, "fleet2" = 2, "fleet3" = 3). #' #' Default: NULL -#' +#' #' Should match length of `files` if >1 model. -#' +#' #' @param save_dir Path. Full file path to save the converted output file. If #' saved file name is not indicated, the file will be saved as "std_output.rda" #' in the file path provided. @@ -86,268 +86,267 @@ convert_output <- function( save_dir = NULL, start_year = NULL ) { - # Is user inputs a single model file and doesn't wrap it as a list object # First check handles WHAM and Rceattle models, second check handles single model input, # final check handles FIMS models - if(any(grepl("Data_File|data_list", names(files))) || is.character(files) || is.data.frame(files)){ + if (any(grepl("Data_File|data_list", names(files))) || is.character(files) || is.data.frame(files)) { cli::cli_alert("`files` is a single model. Converting to list object.") files <- list(files) names(files) <- "model_1" } - if(!all(is.null(models)) && length(models) != length(files)){ + if (!all(is.null(models)) && length(models) != length(files)) { cli::cli_alert_warning("Number of model types entered does not equal number of models.") - models <- c(models, rep(NA, length(files)-length(models))) # can't store NULL in vector so make a string + models <- c(models, rep(NA, length(files) - length(models))) # can't store NULL in vector so make a string cli::cli_alert(glue::glue("Model types are: {paste0(\"'\",models,\"'\", collapse=\",\")}")) } - if(!all(is.null(fleet_names)) && length(fleet_names) != length(files)){ + if (!all(is.null(fleet_names)) && length(fleet_names) != length(files)) { cli::cli_alert_warning("Number of fleet_names entered is not equal to number of models.") - fleet_names <- c(fleet_names, rep(list(NULL), length(files)-length(fleet_names))) + fleet_names <- c(fleet_names, rep(list(NULL), length(files) - length(fleet_names))) names(fleet_names) <- names(files) cli::cli_alert(glue::glue("Fleets names are: {str(fleet_names)}")) } - - processed <- purrr::imap(files, function(file, model_name){ - i <- which(names(files)==model_name) - if (is.character(file) && grepl("Report.sso", file)) { - lifecycle::deprecate_warn( - 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" - ) + + processed <- purrr::imap(files, function(file, model_name) { + i <- which(names(files) == model_name) + if (is.character(file) && grepl("Report.sso", file)) { + lifecycle::deprecate_warn( + 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)) { + cli::cli_alert("save_dir does not contain a file name. Saved output will be named `std_output.rda`.") + save_dir <- file.path(save_dir, "std_output.rda") } - - # 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)) { - cli::cli_alert("save_dir does not contain a file name. Saved output will be named `std_output.rda`.") - save_dir <- file.path(save_dir, "std_output.rda") - } - } + } - #### out_new #### - # Blank dataframe and set up to mold output into - out_new <- data.frame( - module_name = NA, - label = NA, - time = NA, - era = NA, - year = NA, - month = NA, - season = NA, - subseason = NA, - birthseas = NA, - initial = NA, - estimate = NA, - uncertainty = NA, - uncertainty_label = NA, - likelihood = NA, - fleet = NA, - platoon = NA, - area = NA, - age = NA, - sex = NA, - growth_pattern = NA, - # gradient = NA, - # estimated = NA, # TRUE/FALSE - # Additional factors from SS3 - bio_pattern = NA, - settlement = NA, - morph = NA, - beg_mid = NA, - type = NA, - factor = NA, - # sexes = NA, # remove sexes to see how it impacts the results - part = NA, - kind = NA, - nsim = NA, - # TODO: add age_a and len_bins into just bins - add the age value in age - bin = NA, - age_a = NA, - len_bins = NA, - count = NA, - block = NA - # model_name = model_name - ) - out_new <- out_new[-1, ] + #### out_new #### + # Blank dataframe and set up to mold output into + out_new <- data.frame( + module_name = NA, + label = NA, + time = NA, + era = NA, + year = NA, + month = NA, + season = NA, + subseason = NA, + birthseas = NA, + initial = NA, + estimate = NA, + uncertainty = NA, + uncertainty_label = NA, + likelihood = NA, + fleet = NA, + platoon = NA, + area = NA, + age = NA, + sex = NA, + growth_pattern = NA, + # gradient = NA, + # estimated = NA, # TRUE/FALSE + # Additional factors from SS3 + bio_pattern = NA, + settlement = NA, + morph = NA, + beg_mid = NA, + type = NA, + factor = NA, + # sexes = NA, # remove sexes to see how it impacts the results + part = NA, + kind = NA, + nsim = NA, + # TODO: add age_a and len_bins into just bins - add the age value in age + bin = NA, + age_a = NA, + len_bins = NA, + count = NA, + block = NA + # model_name = model_name + ) + out_new <- out_new[-1, ] - # Check if path links to a valid file - if (is.character(file)) { - url_pattern <- "^(https?|ftp|file):\\/\\/[-A-Za-z0-9+&@#\\/%?=~_|!:,.;]*[-A-Za-z0-9+&@#\\/%=~_|]$" - if (grepl(url_pattern, file)) { - check <- tryCatch( - { - headers <- curlGetHeaders(file) - attributes(headers)[["status"]] - }, - error = function(e) { - 404 - } - ) - if (check == 404) cli::cli_abort(c(message = "Invalid URL.")) - } else { - if (!file.exists(file)) { - cli::cli_abort(c( - message = "`file` not found.", - "i" = "`file` entered as {file}" - )) + # Check if path links to a valid file + if (is.character(file)) { + url_pattern <- "^(https?|ftp|file):\\/\\/[-A-Za-z0-9+&@#\\/%?=~_|!:,.;]*[-A-Za-z0-9+&@#\\/%=~_|]$" + if (grepl(url_pattern, file)) { + check <- tryCatch( + { + headers <- curlGetHeaders(file) + attributes(headers)[["status"]] + }, + error = function(e) { + 404 } + ) + if (check == 404) cli::cli_abort(c(message = "Invalid URL.")) + } else { + if (!file.exists(file)) { + cli::cli_abort(c( + message = "`file` not found.", + "i" = "`file` entered as {file}" + )) } } + } - # Recognize model through file extension - if (is.character(file) && tolower(stringr::str_extract(file, "\\.([^.]+)$")) == ".rds") { - file <- readRDS(file) - } - if (is.character(file)) { - if (is.null(models) || is.na(models[i])) { - 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.") - ) - } - } else if (is.null(models) || is.na(models[i])){ - model <- switch(class(file)[1], - "FIMSFit" = { - cli::cli_alert_info("Processing FIMS output file...") - "fims" - }, - "fims" = { - cli::cli_alert_info("Processing FIMS output file...") - "fims" - }, - "Rceattle" = { - cli::cli_alert_info("Processing Rceattle output file...") - "rceattle" + # Recognize model through file extension + if (is.character(file) && tolower(stringr::str_extract(file, "\\.([^.]+)$")) == ".rds") { + file <- readRDS(file) + } + if (is.character(file)) { + if (is.null(models) || is.na(models[i])) { + model <- switch(stringr::str_extract(file, "\\.([^.]+)$"), + ".sso" = { + cli::cli_alert_info("Processing Stock Synthesis output file...") + "ss3" }, - "list" = { - if (any(grepl("wham_version", names(file)))) { - cli::cli_alert_info("Processing WHAM output file...") - "wham" - } else { - cli::cli_alert_info("Processing SS3 r4ss 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 <- models[i] } + } else if (is.null(models) || is.na(models[i])) { + model <- switch(class(file)[1], + "FIMSFit" = { + cli::cli_alert_info("Processing FIMS output file...") + "fims" + }, + "fims" = { + cli::cli_alert_info("Processing FIMS output file...") + "fims" + }, + "Rceattle" = { + cli::cli_alert_info("Processing Rceattle output file...") + "rceattle" + }, + "list" = { + if (any(grepl("wham_version", names(file)))) { + cli::cli_alert_info("Processing WHAM output file...") + "wham" + } else { + cli::cli_alert_info("Processing SS3 r4ss output file...") + "ss3" + } + }, + cli::cli_abort("Unknown file type. Please indicate model.") + ) + } else { + model <- models[i] + } - #### SS3 #### - # SS3 groupings: https://docs.google.com/spreadsheets/d/11-k0xOo3Bit1MbJf2ZjmymzsUNCRhgGkVfXV1jNEdbM/edit?gid=0#gid=0 - # Convert SS3 output Report.sso file - if (tolower(model) == "ss3") { - out_new <- conout_ss3(file = file, out_new = out_new, fleet_names = fleet_names) - } else if (model %in% c("bam", "BAM")) { - #### BAM #### - out_new <- conout_bam(file = file, out_new = out_new, fleet_names = fleet_names) - #### WHAM ---- - } else if (model == "wham") { - # This is how Bai read the ASAP output - # asap_output conversion written by Bai Li - # asap_output <- dget(file.path(casedir, "output", subdir, paste("s", keep_sim_id[om_sim], sep = ""), "asap3.rdat")) - # setwd(file.path(casedir, "output", subdir, paste("s", keep_sim_id[om_sim], sep = ""))) - # asap_std <- readRep("asap3", suffix = ".std") - cli::cli_abort("WHAM output not currently compatible.") - #### AMAK #### - } else if (model == "amak") { - cli::cli_abort("AMAK output not currently compatible.") - #### JABBA #### - } else if (tolower(model) == "jabba") { - cli::cli_abort("JABBA output not currently compatible.") - #### FIMS #### - } else if (model == "fims") { - out_new <- conout_fims(file = file, out_new = out_new, start_year = start_year) - #### Rceattle #### - } else if (model == "rceattle") { + #### SS3 #### + # SS3 groupings: https://docs.google.com/spreadsheets/d/11-k0xOo3Bit1MbJf2ZjmymzsUNCRhgGkVfXV1jNEdbM/edit?gid=0#gid=0 + # Convert SS3 output Report.sso file + if (tolower(model) == "ss3") { + out_new <- conout_ss3(file = file, out_new = out_new, fleet_names = fleet_names) + } else if (model %in% c("bam", "BAM")) { + #### BAM #### + out_new <- conout_bam(file = file, out_new = out_new, fleet_names = fleet_names) + #### WHAM ---- + } else if (model == "wham") { + # This is how Bai read the ASAP output + # asap_output conversion written by Bai Li + # asap_output <- dget(file.path(casedir, "output", subdir, paste("s", keep_sim_id[om_sim], sep = ""), "asap3.rdat")) + # setwd(file.path(casedir, "output", subdir, paste("s", keep_sim_id[om_sim], sep = ""))) + # asap_std <- readRep("asap3", suffix = ".std") + cli::cli_abort("WHAM output not currently compatible.") + #### AMAK #### + } else if (model == "amak") { + cli::cli_abort("AMAK output not currently compatible.") + #### JABBA #### + } else if (tolower(model) == "jabba") { + cli::cli_abort("JABBA output not currently compatible.") + #### FIMS #### + } else if (model == "fims") { + 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) - } else { - cli::cli_abort(c( - message = "Output file not compatible.", - "i" = "`model` entered as {model}.", - "i" = "Accepted `model` options: ss3, bam, or fims." - )) - } + } else { + cli::cli_abort(c( + message = "Output file not compatible.", + "i" = "`model` entered as {model}.", + "i" = "Accepted `model` options: ss3, bam, or fims." + )) + } - # Call in csv for model - con_file <- system.file("resources", glue::glue("{tolower(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 = "") + # Call in csv for model + con_file <- system.file("resources", glue::glue("{tolower(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 (tolower(model) == "bam") { - var_names_sheet <- var_names_sheet |> - dplyr::mutate(label = tolower(label)) - } + if (tolower(model) == "bam") { + var_names_sheet <- var_names_sheet |> + dplyr::mutate(label = tolower(label)) + } - if (file.exists(con_file)) { - # Remove 'X' column if it exists - var_names_sheet <- var_names_sheet |> - dplyr::select(-dplyr::any_of("X")) - if (tolower(model) == "ss3" & !is.character(file)) { - var_names_sheet <- var_names_sheet |> dplyr::select(-module_name) - out_new <- dplyr::left_join(out_new, var_names_sheet, by = "label") - } else { - var_names_sheet <- var_names_sheet |> - dplyr::distinct(module_name, label, .keep_all = TRUE) - out_new <- dplyr::left_join( - out_new, - var_names_sheet, - by = c("module_name", "label"), - relationship = "many-to-one" - ) - } - out_new <- out_new |> - dplyr::mutate(label = dplyr::case_when( - !is.na(alt_label) ~ alt_label, - # TODO: add this to ss3_var_names.xlsx - label == "dev" & module_name == "SPAWN_RECRUIT" ~ "recruitment_deviation", - # TODO: add this to ss3_var_names.xlsx - label == "dev" & module_name == "SPAWN_RECRUIT_CURVE" ~ "recruitment_deviation", - # TODO: add this to ss3_var_names.xlsx - label == "dev" & module_name == "DISCARD_OUTPUT" ~ "discard_deviation", - TRUE ~ label - )) |> - dplyr::select(-alt_label) |> - dplyr::rename(length_bins = len_bins) + if (file.exists(con_file)) { + # Remove 'X' column if it exists + var_names_sheet <- var_names_sheet |> + dplyr::select(-dplyr::any_of("X")) + if (tolower(model) == "ss3" & !is.character(file)) { + var_names_sheet <- var_names_sheet |> dplyr::select(-module_name) + out_new <- dplyr::left_join(out_new, var_names_sheet, by = "label") + } else { + var_names_sheet <- var_names_sheet |> + dplyr::distinct(module_name, label, .keep_all = TRUE) + out_new <- dplyr::left_join( + out_new, + var_names_sheet, + by = c("module_name", "label"), + relationship = "many-to-one" + ) } + out_new <- out_new |> + dplyr::mutate(label = dplyr::case_when( + !is.na(alt_label) ~ alt_label, + # TODO: add this to ss3_var_names.xlsx + label == "dev" & module_name == "SPAWN_RECRUIT" ~ "recruitment_deviation", + # TODO: add this to ss3_var_names.xlsx + label == "dev" & module_name == "SPAWN_RECRUIT_CURVE" ~ "recruitment_deviation", + # TODO: add this to ss3_var_names.xlsx + label == "dev" & module_name == "DISCARD_OUTPUT" ~ "discard_deviation", + TRUE ~ label + )) |> + dplyr::select(-alt_label) |> + dplyr::rename(length_bins = len_bins) + } - out_new <- out_new |> - dplyr::mutate( - model=model_name, - year=as.character(year), - month=as.character(month), - block=as.character(.data$block), - fleet=as.character(fleet) - ) - return(tibble::tibble(out_new)) + out_new <- out_new |> + dplyr::mutate( + model = model_name, + year = as.character(year), + month = as.character(month), + block = as.character(.data$block), + fleet = as.character(fleet) + ) + return(tibble::tibble(out_new)) }) - out_new <- dplyr::bind_rows(processed) # aggregate all of the models + out_new <- dplyr::bind_rows(processed) # aggregate all of the models #### Exporting #### diff --git a/R/plot_abundance_at_age.R b/R/plot_abundance_at_age.R index 9cbdfbae..9c77aebb 100644 --- a/R/plot_abundance_at_age.R +++ b/R/plot_abundance_at_age.R @@ -41,7 +41,7 @@ #' Default: NULL #' #' If the interactive and >1 model is found, user will select the -#' model in the console. @seealso [filter_data()] +#' model in the console. @seealso [filter_data()] #' @param interactive A logical value indicating if the environment is interactive. #' #' Default: `FALSE` @@ -102,7 +102,7 @@ plot_abundance_at_age <- function( geom = "point", group = "age", module = module, - model = model, + model = model, scale_amount = scale_amount, interactive = interactive, allow_multiple_models = TRUE diff --git a/R/plot_composition_diagnostics.R b/R/plot_composition_diagnostics.R index 4fc994c9..b8861b31 100644 --- a/R/plot_composition_diagnostics.R +++ b/R/plot_composition_diagnostics.R @@ -520,4 +520,3 @@ plot_composition_andre <- function( plot.caption = ggplot2::element_text(hjust = 0, size = 9) ) } - diff --git a/R/plot_recruitment.R b/R/plot_recruitment.R index d63658d4..ced98abd 100644 --- a/R/plot_recruitment.R +++ b/R/plot_recruitment.R @@ -202,7 +202,7 @@ plot_recruitment <- function( rm(selected_module, envir = .GlobalEnv) } - if(exists("selected_model")){ + if (exists("selected_model")) { rm(selected_model, envir = .GlobalEnv) } diff --git a/R/plot_retrospective.R b/R/plot_retrospective.R index 151b4cef..e7ea5485 100644 --- a/R/plot_retrospective.R +++ b/R/plot_retrospective.R @@ -1,38 +1,38 @@ #' Plot retrospective peels -#' -#' Plot a given quantity across multiple models with differing +#' +#' Plot a given quantity across multiple models with differing #' end years, so as to plot retrospective peels. -#' +#' #' @inheritParams plot_spawning_biomass -#' +#' #' @param end_years Integer. vector of what year, relative to the maximum #' year present in `dat`, should be treated as the final year for each #' model. Should be <= 0. -#' +#' #' Default: 0 -#' -#' @param quantity String. Assessment quantity to plot (e.g., spawning biomass, +#' +#' @param quantity String. Assessment quantity to plot (e.g., spawning biomass, #' biomass, recruitment, etc.). Should correspond to an existing `plot_*` function. -#' -#' Default: "spawning_biomass" -#' +#' +#' Default: "spawning_biomass" +#' #' @param show_end_year_points Logical. Whether to add points at the terminal year #' for each model peel. -#' +#' #' Default: TRUE -#' +#' #' @param mohns_rho Numeric. Externally calculated value(s) of Mohn's rho. Should be #' either a single value or of length `end_years-1`. Value of NULL disables #' reporting Mohn's rho statistic on plot. If vector, names of vector entries should #' match with model names. -#' +#' #' Default: NULL -#' +#' #' @param group String. Single column that groups the data. -#' +#' #' Default: "model" -#' -#' @return A plot showing values of an assessment quantity across different +#' +#' @return A plot showing values of an assessment quantity across different #' retrospective peels. #' #' @details The input is from an assessment model output file @@ -54,162 +54,159 @@ #' dat = ss3_simple, #' end_years = 0:-5, #' quantity = "spawning_biomass", -#' show_end_year_points=TRUE +#' show_end_year_points = TRUE #' ) #' plot_retrospective( #' dat = ss3_simple, #' end_years = 0:-5, #' quantity = "spr", -#' show_end_year_points=TRUE, -#' interactive=FALSE, +#' show_end_year_points = TRUE, +#' interactive = FALSE, #' module = "derived_quants" #' ) #' plot_retrospective( #' dat = ss3_simple, #' end_years = 0:-5, #' quantity = "spr", -#' show_end_year_points=TRUE, +#' show_end_year_points = TRUE, #' mohns_rho = c(0.023, 0.01, 1.25, 0.845, 0.068), -#' interactive=FALSE, +#' interactive = FALSE, #' module = "derived_quants" #' ) plot_retrospective <- function( dat, - end_years=NULL, - quantity="spawning_biomass", - show_end_year_points=TRUE, + end_years = NULL, + quantity = "spawning_biomass", + show_end_year_points = TRUE, mohns_rho = NULL, - group="model", - make_rda=FALSE, - figures_dir=getwd(), + group = "model", + make_rda = FALSE, + figures_dir = getwd(), ... -){ - +) { # plot_biomass, plot_spawning_biomass, plot_fishing_mortality, plot_recruitment, plot_spr quantity <- match.arg(quantity, c("biomass", "spawning_biomass", "fishing_mortality", "recruitment", "spr")) - func_name <- paste0("plot_",quantity) - if(!(func_name %in% ls(getNamespace("stockplotr")))){ + func_name <- paste0("plot_", quantity) + if (!(func_name %in% ls(getNamespace("stockplotr")))) { cli::cli_abort("`quantity` not valid. Should correspond to one of the available stockplotr plotting functions.") } n_models <- length(unique(dat$model)) - if(is.null(end_years)) end_years <- rep(0, n_models) - if(length(end_years) != n_models && n_models > 1){ + if (is.null(end_years)) end_years <- rep(0, n_models) + if (length(end_years) != n_models && n_models > 1) { cli::cli_alert_info("Different number of end_years and available models.") - end_years <- c(end_years, rep(0, n_models-length(end_years))) + end_years <- c(end_years, rep(0, n_models - length(end_years))) } # Convert end_years to negatives for math - if(any(end_years > 0)){ - end_years[which(end_years > 0)] <- end_years[which(end_years > 0)]*-1 + if (any(end_years > 0)) { + end_years[which(end_years > 0)] <- end_years[which(end_years > 0)] * -1 } - if(n_models == 1) + if (n_models == 1) { cli::cli_alert_info("Only 1 model detected in `dat`. Function expects multiple models corresponding to unique retrospective peels.") + } - if(is.null(names(end_years))){ + if (is.null(names(end_years))) { cli::cli_alert("`end_years` provided without names. names automatically applied.") names(end_years) <- dat$model |> unique() } - if(!all(is.null(mohns_rho)) && length(mohns_rho) != n_models-1){ + if (!all(is.null(mohns_rho)) && length(mohns_rho) != n_models - 1) { cli::cli_alert_warning("Invalid number of mohn's rho values provided. Should be number of peels - 1. Mohn's rho values will not be reported.") mohns_rho <- NULL } - if(!all(is.null(mohns_rho)) && is.null(names(mohns_rho))){ + if (!all(is.null(mohns_rho)) && is.null(names(mohns_rho))) { cli::cli_alert("`mohns_rho` values provided without names. names automatically applied.") names(mohns_rho) <- unique(dat$model)[-1] } retro_dat <- dat |> dplyr::filter(!is.na(year), !is.na(estimate)) |> - dplyr::mutate(term_year=max(year)) |> + dplyr::mutate(term_year = max(year)) |> dplyr::rowwise() |> dplyr::mutate( - max_yr = term_year+end_years[which(model==names(end_years))], - peel = abs(end_years[which(model==names(end_years))]) + max_yr = term_year + end_years[which(model == names(end_years))], + peel = abs(end_years[which(model == names(end_years))]) ) |> dplyr::ungroup() |> - dplyr::filter(year < max_yr-1) |> + dplyr::filter(year < max_yr - 1) |> dplyr::select(-term_year, -max_yr) - + func_pars <- list( - dat = retro_dat, - group="peel", + dat = retro_dat, + group = "peel", model = names(end_years), # turn this on to bypass interactive model selection and plot all available models - make_rda=FALSE # don't want to overwrite files from non-retro plots + make_rda = FALSE # don't want to overwrite files from non-retro plots # ... ) plt <- do.call(func_name, func_pars) - plot_data <- plt$layers[[2]]$data |> + plot_data <- plt$layers[[2]]$data |> dplyr::rename( - dplyr::any_of(c(estimate="predicted_recruitment")) + dplyr::any_of(c(estimate = "predicted_recruitment")) ) - if(show_end_year_points){ + if (show_end_year_points) { # get data from the "geom_line" elements and identfiy terminal year estimate - term_dat <- plot_data |> - dplyr::slice_max(order_by=year, n=1, by=model) + term_dat <- plot_data |> + dplyr::slice_max(order_by = year, n = 1, by = model) - plt <- plt+ + plt <- plt + ggplot2::geom_point( - data=term_dat, + data = term_dat, ggplot2::aes( - x=.data[["year"]], - y=.data[["estimate"]], - color={ - if (length(unique(.data[["model"]])) > 1) { - interaction(model, group_var) - } else { - group_var - } + x = .data[["year"]], + y = .data[["estimate"]], + color = { + if (length(unique(.data[["model"]])) > 1) { + interaction(model, group_var) + } else { + group_var } + } ), - size=3.5 + size = 3.5 ) } - if(!all(is.null(mohns_rho))){ - + if (!all(is.null(mohns_rho))) { mohns_df <- data.frame( label = sprintf("%.3f", mohns_rho) ) - mohns_df$model = names(mohns_rho) - mohns_df$vjust = 0.5 + seq_along(mohns_rho-1)*1.5 + mohns_df$model <- names(mohns_rho) + mohns_df$vjust <- 0.5 + seq_along(mohns_rho - 1) * 1.5 mohns_df$label <- paste0(mohns_df$model, " Mohns Rho:\t", mohns_df$label) plt <- plt + ggplot2::geom_text( data = mohns_df, ggplot2::aes( - x=Inf, - y=Inf, - label=label, - vjust=vjust + x = Inf, + y = Inf, + label = label, + vjust = vjust ), # family = "mono", - size=6, - hjust=1.1 + size = 6, + hjust = 1.1 ) - } plt <- plt + - ggplot2::scale_color_discrete(labels=unique(retro_dat$model))+ - ggplot2::scale_fill_discrete(labels=unique(retro_dat$model))+ + ggplot2::scale_color_discrete(labels = unique(retro_dat$model)) + + ggplot2::scale_fill_discrete(labels = unique(retro_dat$model)) + ggplot2::guides( - color=ggplot2::guide_legend("Peel"), - fill=ggplot2::guide_legend("Peel") + color = ggplot2::guide_legend("Peel"), + fill = ggplot2::guide_legend("Peel") ) - if(make_rda){ - + if (make_rda) { create_rda( object = plt, topic_label = glue::glue("retrospective_{quantity}"), @@ -227,10 +224,9 @@ plot_retrospective <- function( rm(selected_module, envir = .GlobalEnv) } - if(exists("selected_model")){ + if (exists("selected_model")) { rm(selected_model, envir = .GlobalEnv) } - - plt + plt } diff --git a/R/plot_selectivity.R b/R/plot_selectivity.R index 6a40ae8b..48169f13 100644 --- a/R/plot_selectivity.R +++ b/R/plot_selectivity.R @@ -200,7 +200,7 @@ plot_selectivity <- function( rm(selected_module, envir = .GlobalEnv) } - if(exists("selected_model")){ + if (exists("selected_model")) { rm(selected_model, envir = .GlobalEnv) } diff --git a/R/plot_spawning_biomass.R b/R/plot_spawning_biomass.R index 887cc3ef..7dea2b04 100644 --- a/R/plot_spawning_biomass.R +++ b/R/plot_spawning_biomass.R @@ -320,7 +320,7 @@ plot_spawning_biomass <- function( rm(selected_module, envir = .GlobalEnv) } - if(exists("selected_model")){ + if (exists("selected_model")) { rm(selected_model, envir = .GlobalEnv) } diff --git a/R/plot_spr.R b/R/plot_spr.R index a8638fe9..1acd96d1 100644 --- a/R/plot_spr.R +++ b/R/plot_spr.R @@ -174,7 +174,7 @@ plot_spr <- function( rm(selected_module, envir = .GlobalEnv) } - if(exists("selected_model")){ + if (exists("selected_model")) { rm(selected_model, envir = .GlobalEnv) } diff --git a/R/plot_stock_recruitment.R b/R/plot_stock_recruitment.R index ceed4c8f..b5444773 100644 --- a/R/plot_stock_recruitment.R +++ b/R/plot_stock_recruitment.R @@ -243,7 +243,7 @@ plot_stock_recruitment <- function( rm(selected_module, envir = .GlobalEnv) } - if(exists("selected_model")){ + if (exists("selected_model")) { rm(selected_model, envir = .GlobalEnv) } diff --git a/R/table_biomass_abundance_catch.R b/R/table_biomass_abundance_catch.R index f64af75b..70997228 100644 --- a/R/table_biomass_abundance_catch.R +++ b/R/table_biomass_abundance_catch.R @@ -85,7 +85,7 @@ table_biomass_abundance_catch <- function( # Do this so that we don't have to repeatedly choose the same model selected_model <- model - + # Aiming for totals # iterate through label_names lab_list <- purrr::map( @@ -244,7 +244,7 @@ table_biomass_abundance_catch <- function( rm(selected_module, envir = .GlobalEnv) } - if(exists("selected_model")){ + if (exists("selected_model")) { rm(selected_model, envir = .GlobalEnv) } diff --git a/R/table_index.R b/R/table_index.R index 2efc5def..3efdf5f1 100644 --- a/R/table_index.R +++ b/R/table_index.R @@ -169,9 +169,9 @@ table_index <- function( rm(selected_module, envir = .GlobalEnv) } - if(exists("selected_model")){ + if (exists("selected_model")) { rm(selected_model, envir = .GlobalEnv) } final -} \ No newline at end of file +} diff --git a/R/table_landings.R b/R/table_landings.R index 9f43a88c..977cda14 100644 --- a/R/table_landings.R +++ b/R/table_landings.R @@ -193,10 +193,9 @@ table_landings <- function( rm(selected_module, envir = .GlobalEnv) } - if(exists("selected_model")){ + if (exists("selected_model")) { rm(selected_model, envir = .GlobalEnv) } final } - diff --git a/R/table_projections.R b/R/table_projections.R index 5ce6b6c3..73745893 100644 --- a/R/table_projections.R +++ b/R/table_projections.R @@ -79,13 +79,13 @@ table_projections <- function( allow_multiple_models = FALSE ) |> dplyr::mutate( - estimate = if(x != "fishing_mortality"){ - round(as.numeric(estimate), digits=0) - }else{ + estimate = if (x != "fishing_mortality") { + round(as.numeric(estimate), digits = 0) + } else { round(as.numeric(estimate), digits = 4) } ) |> - # estimate = ifelse(x != "fishing_mortality", round(as.numeric(estimate), digits = 0), round(as.numeric(estimate), digits = 4))) |> + # estimate = ifelse(x != "fishing_mortality", round(as.numeric(estimate), digits = 0), round(as.numeric(estimate), digits = 4))) |> dplyr::mutate(uncertainty = round(as.numeric(uncertainty), digits = 2)) |> dplyr::distinct() # only preserve unique rows @@ -188,7 +188,7 @@ table_projections <- function( rm(selected_module, envir = .GlobalEnv) } - if(exists("selected_model")){ + if (exists("selected_model")) { rm(selected_model, envir = .GlobalEnv) } diff --git a/R/table_total_catch.R b/R/table_total_catch.R index 5af7d80e..92caaea0 100644 --- a/R/table_total_catch.R +++ b/R/table_total_catch.R @@ -206,7 +206,7 @@ table_total_catch <- function( rm(selected_module, envir = .GlobalEnv) } - if(exists("selected_model")){ + if (exists("selected_model")) { rm(selected_model, envir = .GlobalEnv) } diff --git a/R/utils_composition.R b/R/utils_composition.R index d4bc4cd7..6862e09a 100644 --- a/R/utils_composition.R +++ b/R/utils_composition.R @@ -657,7 +657,7 @@ is_ss3_fit_summary <- function(dat) { is.data.frame(dat) && all(c("module_name", "label", "estimate") %in% names(dat)) && any(dat$module_name %in% c("FIT_LEN_COMPS", "FIT_AGE_COMPS", "FIT_SIZE_COMPS") & - dat$label %in% "effn") + dat$label %in% "effn") } # Sample sizes from the Stock Synthesis FIT_*_COMPS tables in @@ -671,7 +671,7 @@ comp_sample_size_from_ss3 <- function(dat, comp_type = NULL) { names(dat) ) fit <- dat[dat$module_name %in% c("FIT_LEN_COMPS", "FIT_AGE_COMPS", "FIT_SIZE_COMPS") & - dat$label %in% c("nsamp_adj", "effn", "part", "ageerr"), c(keys, "label", "estimate")] + dat$label %in% c("nsamp_adj", "effn", "part", "ageerr"), c(keys, "label", "estimate")] # convert_output() keeps the values from each row of the SS3 table # together, in order, so a new composition starts at each "part" (or # "nsamp_adj" in output without partitions) diff --git a/R/utils_plot.R b/R/utils_plot.R index 7f2e00b1..fab04df9 100644 --- a/R/utils_plot.R +++ b/R/utils_plot.R @@ -676,7 +676,7 @@ cap_first_letter <- function(s) { #' @param label_name String. Name of the label used to filter #' the data. #' @param allow_multiple_models Logical. Whether to allow multiple models. -#' +#' #' Default: TRUE #' #' @returns a data frame that is preformatted for plotting with ggplot2. @@ -686,12 +686,12 @@ cap_first_letter <- function(s) { #' \dontrun{ #' filter_data(dat, "biomass", "line", group = "fleet") #' filter_data( -#' dat, -#' label = "biomass", -#' geom = "line", -#' module="derived_quants", -#' model=NULL, -#' allow_multiple_models=FALSE # can only select one model to filter by +#' dat, +#' label = "biomass", +#' geom = "line", +#' module = "derived_quants", +#' model = NULL, +#' allow_multiple_models = FALSE # can only select one model to filter by #' ) #' } filter_data <- function( @@ -707,13 +707,12 @@ filter_data <- function( interactive = TRUE, allow_multiple_models = TRUE ) { - # Check if there are multiple module_names present model_select <- filter_interactive( dat, - column_name="model", - column_value=model, - interactive=interactive, + column_name = "model", + column_value = model, + interactive = interactive, allow_multiple_selection = allow_multiple_models ) dat <- model_select$plot_data @@ -725,8 +724,8 @@ filter_data <- function( label_name <- gsub(" ", "_", tolower(label_name)) model_label <- any(grepl("model", colnames(dat))) - if(!model_label){ - dat <- dat |> dplyr::mutate(model="1") + if (!model_label) { + dat <- dat |> dplyr::mutate(model = "1") } plot_data <- dat |> @@ -802,9 +801,9 @@ filter_data <- function( # Check if there are multiple module_names present module_select <- filter_interactive( plot_data, - column_name="module_name", - column_value=module, - interactive=interactive, + column_name = "module_name", + column_value = module, + interactive = interactive, allow_multiple_selection = TRUE ) plot_data <- module_select$plot_data @@ -1140,31 +1139,33 @@ add_reference_line <- function( # 2. custom input vector = c("sable23_msy"=30, "sable25_msy"=40) -- user must indicate which model in label otherwise it will assign in order of dat # 3. input vector of labels = c("msy", "target") # getting data set - an ifelse statement in the fxn wasn't working - if("model" %in% colnames(dat)){ - model_names <- dat |> dplyr::distinct(model) |> dplyr::pull(model) - n_models <- length(model_names) - }else{ + if ("model" %in% colnames(dat)) { + model_names <- dat |> + dplyr::distinct(model) |> + dplyr::pull(model) + n_models <- length(model_names) + } else { n_models <- 1 } - + ref_lines_list <- list() if (!is.null(ref_line)) { # Check if length of ref_line = dat -- replicate value if not # Need to check this # if (!is.data.frame(dat) & length(ref_line) != length(dat)) ref_line <- rep(ref_line, length(dat)) - - if(n_models > 1 & length(ref_line)==1) ref_line <- rep(ref_line, n_models) - + + if (n_models > 1 & length(ref_line) == 1) ref_line <- rep(ref_line, n_models) + # Put into for loop and add lines sequentially to plt for (i in 1:length(ref_line)) { # find the reference point value if (is.null(names(ref_line[i]))) { ref_line_x <- calculate_reference_point( - dat = if(n_models == 1){ - dat - } else { - dat |> dplyr::filter(model == model_names[i]) - }, + dat = if (n_models == 1) { + dat + } else { + dat |> dplyr::filter(model == model_names[i]) + }, reference_name = glue::glue("{label}_{ref_line[i]}"), lbs = lbs ) / scale_amount @@ -1218,38 +1219,38 @@ add_reference_line <- function( #' Filter plot data interactively -#' +#' #' Allows user to interactively select values from those available #' to filter their data by. -#' +#' #' @param dat data.frame. A tibble or named list of tibbles (input as `list()`) #' returned from \link[stockplotr]{convert_output}. -#' +#' #' @param column_name String. Name of the column to allow interactive filtering for. -#' +#' #' @param column_value String. Value of the column to filter by. If NULL, interactive #' selection will be enabled. -#' +#' #' Default: NULL -#' -#' @param interactive Logical. indicate whether the environment is interactive. -#' +#' +#' @param interactive Logical. indicate whether the environment is interactive. +#' #' Default: TRUE -#' +#' #' @param allow_multiple_selection Logical. Whether to allow the selection of multiple inputs. -#' +#' #' Default: FALSE -#' +#' #' @return List. filtered data.frame (`plot_data`) and selected option(`selected`). -#' +#' #' @examples #' \dontrun{ -#' filter_interactive( -#' dat = example_dat, -#' column_name = "model", -#' column_value = NULL, -#' allow_multiple_selection = TRUE # allow selecting multiple models -#' ) +#' filter_interactive( +#' dat = example_dat, +#' column_name = "model", +#' column_value = NULL, +#' allow_multiple_selection = TRUE # allow selecting multiple models +#' ) #' } filter_interactive <- function( dat, @@ -1257,22 +1258,21 @@ filter_interactive <- function( column_value = NULL, interactive = TRUE, allow_multiple_selection = TRUE -){ +) { + pretty_columns <- c("module_name" = "module", "model" = "model") - pretty_columns <- c("module_name"="module", "model"="model") - plot_dat <- dat selected <- unique(dat[[column_name]]) - if(length(unique(dat[[column_name]])) > 1){ + if (length(unique(dat[[column_name]])) > 1) { available_names <- unique(dat[[column_name]]) - if(!is.null(column_value)){ - if(length(column_value) > 1 && !allow_multiple_selection){ + if (!is.null(column_value)) { + if (length(column_value) > 1 && !allow_multiple_selection) { cli::cli_alert_danger("Multiple {pretty_columns[column_name]}s provided, but only 1 allowed. Defaulting to first available {pretty_columns[column_name]} name: {available_names[1]}.") column_value <- available_names[1] } plot_dat <- dat |> dplyr::filter(.data[[column_name]] %in% column_value) selected <- column_value - }else{ + } else { cli::cli_alert_warning("Multiple {pretty_columns[column_name]}s found in data. \n") options <- c() for (i in seq_along(available_names)) { @@ -1280,22 +1280,22 @@ filter_interactive <- function( options[i] <- paste0(available_names[i]) } - if(column_name == "model"){ + if (column_name == "model") { options <- c(options, "All") } - if(interactive()){ - if(interactive){ + if (interactive()) { + if (interactive) { selection <- utils::select.list( options, - multiple=allow_multiple_selection, + multiple = allow_multiple_selection, title = glue::glue("Select one of the following {pretty_columns[column_name]} names") ) - question1 <- if(length(selection)==0 || identical(selection, "")){ + question1 <- if (length(selection) == 0 || identical(selection, "")) { options[1] - }else if("All" %in% selection){ + } else if ("All" %in% selection) { options[-length(options)] - }else{ + } else { selection } @@ -1303,11 +1303,11 @@ filter_interactive <- function( if (length(selected) < 1 || (length(selected) > 1 && !allow_multiple_selection)) { selected <- available_names[1] } - }else{ + } else { selected <- available_names[1] cli::cli_alert_info("Selection bypassed. Filtering by {selected}.") } - }else{ + } else { selected <- available_names[1] cli::cli_alert_info(glue::glue("Environment not interactive. Selecting {selected}.")) } @@ -1319,7 +1319,7 @@ filter_interactive <- function( } } } - out <- list("plot_data"=plot_dat, "selected"=selected) + out <- list("plot_data" = plot_dat, "selected" = selected) return(out) } diff --git a/man/filter_data.Rd b/man/filter_data.Rd index 68e661da..3168a2f4 100644 --- a/man/filter_data.Rd +++ b/man/filter_data.Rd @@ -92,12 +92,12 @@ Filter data for input into aesthetics for ggplot2 \dontrun{ filter_data(dat, "biomass", "line", group = "fleet") filter_data( - dat, - label = "biomass", - geom = "line", - module="derived_quants", - model=NULL, - allow_multiple_models=FALSE # can only select one model to filter by + dat, + label = "biomass", + geom = "line", + module = "derived_quants", + model = NULL, + allow_multiple_models = FALSE # can only select one model to filter by ) } } diff --git a/man/filter_interactive.Rd b/man/filter_interactive.Rd index cc6944ff..92cf024d 100644 --- a/man/filter_interactive.Rd +++ b/man/filter_interactive.Rd @@ -40,11 +40,11 @@ to filter their data by. } \examples{ \dontrun{ - filter_interactive( - dat = example_dat, - column_name = "model", - column_value = NULL, - allow_multiple_selection = TRUE # allow selecting multiple models - ) +filter_interactive( + dat = example_dat, + column_name = "model", + column_value = NULL, + allow_multiple_selection = TRUE # allow selecting multiple models +) } } diff --git a/man/plot_discard.Rd b/man/plot_discard.Rd index bbf9b76b..caca4458 100644 --- a/man/plot_discard.Rd +++ b/man/plot_discard.Rd @@ -96,6 +96,7 @@ Default: NULL If the interactive and >1 model is found, user will select the model in the console. @seealso \code{\link[=filter_data]{filter_data()}}} + \item{predicted}{Logical. TRUE (Default) or FALSE; show the discards predicted by the model as lines, with the observed discards as points, to show the fit to the observed discards. The predicted discards are shown diff --git a/man/plot_retrospective.Rd b/man/plot_retrospective.Rd index 4c27b27d..b3f2602e 100644 --- a/man/plot_retrospective.Rd +++ b/man/plot_retrospective.Rd @@ -88,23 +88,23 @@ plot_retrospective( dat = ss3_simple, end_years = 0:-5, quantity = "spawning_biomass", - show_end_year_points=TRUE + show_end_year_points = TRUE ) plot_retrospective( dat = ss3_simple, end_years = 0:-5, quantity = "spr", - show_end_year_points=TRUE, - interactive=FALSE, + show_end_year_points = TRUE, + interactive = FALSE, module = "derived_quants" ) plot_retrospective( dat = ss3_simple, end_years = 0:-5, quantity = "spr", - show_end_year_points=TRUE, + show_end_year_points = TRUE, mohns_rho = c(0.023, 0.01, 1.25, 0.845, 0.068), - interactive=FALSE, + interactive = FALSE, module = "derived_quants" ) } diff --git a/tests/testthat/test-convert_output.R b/tests/testthat/test-convert_output.R index d0f7a4cd..3761774e 100644 --- a/tests/testthat/test-convert_output.R +++ b/tests/testthat/test-convert_output.R @@ -331,27 +331,25 @@ test_that("convert_output refuses a multispecies Rceattle fit", { }) test_that("convert_output on multiple SS3 models", { - model_files <- list( - "hake2018"=fs::path("fixtures", "ss3_models", "models", "Hake_2018"), - "BigSkate2019"=fs::path("fixtures", "ss3_models", "models", "BigSkate_2019") - ) + model_files <- list( + "hake2018" = fs::path("fixtures", "ss3_models", "models", "Hake_2018"), + "BigSkate2019" = fs::path("fixtures", "ss3_models", "models", "BigSkate_2019") + ) - models_r4ss <- lapply(model_files, \(x) r4ss::SS_output(x)) + models_r4ss <- lapply(model_files, \(x) r4ss::SS_output(x)) - expect_no_error(result <- convert_output(models_r4ss)) - expect_equal(dim(result)[2], 36) - expect_equal(result$model %>% unique, c("hake2018", "BigSkate2019")) + expect_no_error(result <- convert_output(models_r4ss)) + expect_equal(dim(result)[2], 36) + expect_equal(result$model %>% unique(), c("hake2018", "BigSkate2019")) }) test_that("convert_output on SS3 and Rceattle model", { + ss3_hake2018 <- r4ss::SS_output(fs::path("fixtures", "ss3_models", "models", "Hake_2018")) + rceattle_atf <- readRDS(fs::path("fixtures", "rceattle_goa_atf.rds")) - ss3_hake2018 <- r4ss::SS_output(fs::path("fixtures", "ss3_models", "models", "Hake_2018")) - rceattle_atf <- readRDS(fs::path("fixtures", "rceattle_goa_atf.rds")) + models <- list("ss3_hake" = ss3_hake2018, "rceattle_atf" = rceattle_atf) - models <- list("ss3_hake"=ss3_hake2018, "rceattle_atf"=rceattle_atf) - - expect_no_error(result <- convert_output(models)) - expect_equal(dim(result)[2], 36) - expect_equal(result$model %>% unique, c("ss3_hake", "rceattle_atf")) + expect_no_error(result <- convert_output(models)) + expect_equal(dim(result)[2], 36) + expect_equal(result$model %>% unique(), c("ss3_hake", "rceattle_atf")) }) - diff --git a/tests/testthat/test-export_rda.R b/tests/testthat/test-export_rda.R index f198a3bd..5b22caf7 100644 --- a/tests/testthat/test-export_rda.R +++ b/tests/testthat/test-export_rda.R @@ -8,7 +8,7 @@ test_that("export_rda works for figures", { custom_dir <- fs::path(getwd(), "tests-export_rda") # add KQs to caps/alt text csv - insert_kqs(B.min, B.max, dir=custom_dir) + insert_kqs(B.min, B.max, dir = custom_dir) # extract this plot's caption and alt text caps_alttext <- extract_caps_alttext( @@ -53,7 +53,7 @@ test_that("export_rda works for tables", { custom_dir <- fs::path(getwd(), "tests-export_rda") # add KQs to caps/alt text csv - insert_kqs(B.min, B.max, dir=custom_dir) + insert_kqs(B.min, B.max, dir = custom_dir) # extract this plot's caption and alt text caps_alttext <- extract_caps_alttext( diff --git a/tests/testthat/test-plot_abundance_at_age.R b/tests/testthat/test-plot_abundance_at_age.R index 140e23ae..091d6d09 100644 --- a/tests/testthat/test-plot_abundance_at_age.R +++ b/tests/testthat/test-plot_abundance_at_age.R @@ -166,15 +166,14 @@ test_that("plot contains a legend", { }) test_that("plot_abundace_at_age generates plots for multiple models", { - dat <- convert_output(list( - "model1" = r4ss::SS_output(test_path("fixtures", "ss3_models", "models", "Hake_2018")), - "model2" = r4ss::SS_output(test_path("fixtures", "ss3_models", "models", "Hake_2019_semi-parametric_selex")) - )) - - expect_no_error(plt <- plot_abundance_at_age(dat, module="natage", model=c("model1", "model2"))) - expect_s3_class(plt, "gg") + dat <- convert_output(list( + "model1" = r4ss::SS_output(test_path("fixtures", "ss3_models", "models", "Hake_2018")), + "model2" = r4ss::SS_output(test_path("fixtures", "ss3_models", "models", "Hake_2019_semi-parametric_selex")) + )) - p <- ggplot2::ggplot_build(plt) - expect_equal(length(unique(p$data[[1]]$PANEL)), 4) + expect_no_error(plt <- plot_abundance_at_age(dat, module = "natage", model = c("model1", "model2"))) + expect_s3_class(plt, "gg") + p <- ggplot2::ggplot_build(plt) + expect_equal(length(unique(p$data[[1]]$PANEL)), 4) }) diff --git a/tests/testthat/test-plot_retrospective.R b/tests/testthat/test-plot_retrospective.R index 6cab6312..7cbba1c8 100644 --- a/tests/testthat/test-plot_retrospective.R +++ b/tests/testthat/test-plot_retrospective.R @@ -1,8 +1,10 @@ -count_geoms <- function(plot, build, geom){ +count_geoms <- function(plot, build, geom) { sapply(seq_along(plot$layers), function(i) { if (inherits(plot$layers[[i]]$geom, "GeomPoint")) { layer_data <- build$data[[i]] - if (nrow(layer_data) == 0) return(0) + if (nrow(layer_data) == 0) { + return(0) + } length(unique(layer_data$group)) } else { 0 @@ -11,23 +13,23 @@ count_geoms <- function(plot, build, geom){ } test_that("plot_retrospective with SS3 models", { - x <- list(); - for (y in 0:-5) { - x[[length(x) + 1]] <- r4ss::SS_output(paste0('https://raw.githubusercontent.com/iagomosqueira/2026_sol.27.4_review/refs/heads/main/stock_weights/model/ss3_nochange/retrospectives/retro', y)) - } - names(x) <- paste0("retro-",0:5) - dat <- convert_output(x) - - retro <- plot_retrospective( - dat = dat, - end_years = 0:5, - module = "derived_quants" - ) - - built <- ggplot2::ggplot_build(retro) - - expect_equal(sum(count_geoms(retro, built, "GeomLine")), 6) - expect_equal(sum(count_geoms(retro, built, "GeomPoint")), 6) + x <- list() + for (y in 0:-5) { + x[[length(x) + 1]] <- r4ss::SS_output(paste0("https://raw.githubusercontent.com/iagomosqueira/2026_sol.27.4_review/refs/heads/main/stock_weights/model/ss3_nochange/retrospectives/retro", y)) + } + names(x) <- paste0("retro-", 0:5) + dat <- convert_output(x) + + retro <- plot_retrospective( + dat = dat, + end_years = 0:5, + module = "derived_quants" + ) + + built <- ggplot2::ggplot_build(retro) + + expect_equal(sum(count_geoms(retro, built, "GeomLine")), 6) + expect_equal(sum(count_geoms(retro, built, "GeomPoint")), 6) }) # test_that("plot_retrospective with FIMS models", { @@ -59,4 +61,4 @@ test_that("plot_retrospective with SS3 models", { # module="derived_quants" # ) -# }) \ No newline at end of file +# }) diff --git a/tests/testthat/test-plot_spawning_biomass.R b/tests/testthat/test-plot_spawning_biomass.R index 8f26e1c5..97303c2f 100644 --- a/tests/testthat/test-plot_spawning_biomass.R +++ b/tests/testthat/test-plot_spawning_biomass.R @@ -58,15 +58,14 @@ test_that("plot_spawning_biomass generates plots without errors", { # }) test_that("plot_spawning_biomass generates plots for multiple models", { - dat <- convert_output(list( - "model1" = r4ss::SS_output(test_path("fixtures", "ss3_models", "models", "platoons")), - "model2" = r4ss::SS_output(test_path("fixtures", "ss3_models", "models", "Empirical_Wtatage_Age_Selex")) - )) + dat <- convert_output(list( + "model1" = r4ss::SS_output(test_path("fixtures", "ss3_models", "models", "platoons")), + "model2" = r4ss::SS_output(test_path("fixtures", "ss3_models", "models", "Empirical_Wtatage_Age_Selex")) + )) - expect_no_error(plt <- plot_spawning_biomass(dat, module="derived_quants", model=c("model1", "model2"))) - expect_s3_class(plt, "gg") - - p <- ggplot2::ggplot_build(plt) - expect_equal(length(unique(p$data[[1]]$group)), 2) + expect_no_error(plt <- plot_spawning_biomass(dat, module = "derived_quants", model = c("model1", "model2"))) + expect_s3_class(plt, "gg") + p <- ggplot2::ggplot_build(plt) + expect_equal(length(unique(p$data[[1]]$group)), 2) }) diff --git a/tests/testthat/test-utils_plot.R b/tests/testthat/test-utils_plot.R index 6457ba2d..f75b25f1 100644 --- a/tests/testthat/test-utils_plot.R +++ b/tests/testthat/test-utils_plot.R @@ -184,9 +184,9 @@ test_that("reference and scalar utility helpers behave as expected", { mm_dat <- make_utils_plot_multimodel_data() mm_dat <- mm_dat |> dplyr::add_row( label = "biomass_msy", - estimate = 120, module_name="TIME_SERIES", - year=NA, fleet=NA, age=NA, season=NA, uncertainty=NA, uncertainty_label=NA, - era="time", model="model_one" + estimate = 120, module_name = "TIME_SERIES", + year = NA, fleet = NA, age = NA, season = NA, uncertainty = NA, uncertainty_label = NA, + era = "time", model = "model_one" ) ts_dat <- filter_data( dat = mm_dat, @@ -196,7 +196,7 @@ test_that("reference and scalar utility helpers behave as expected", { ) base_plot <- plot_timeseries(ts_dat, geom = "line") - ref_plot <- base_plot + add_reference_line(mm_dat, ref_line="msy", label="biomass") + ref_plot <- base_plot + add_reference_line(mm_dat, ref_line = "msy", label = "biomass") expect_true(has_hline(ref_plot)) # make sure it has A line expect_equal(sum(sapply(ref_plot$layers, function(layer) inherits(layer$geom, "GeomHline"))), 2) # make sure it has TWO lines