From 2864008b3f53fa6e4fe58fa7f2d5723edcde3b1b Mon Sep 17 00:00:00 2001 From: Schiano-NOAA <125507018+Schiano-NOAA@users.noreply.github.com> Date: Wed, 18 Nov 2026 19:51:49 +0000 Subject: [PATCH] style and docs: run devtools::document() and style with styler or air --- DESCRIPTION | 8 +- R/conout_bam.R | 4 +- R/conout_rceattle.R | 4 +- R/conout_ss3.R | 8 +- R/convert_output.R | 465 ++++++++++---------- R/plot_composition_diagnostics.R | 1 - R/plot_retrospective.R | 164 ++++--- R/utils_composition.R | 4 +- R/utils_plot.R | 32 +- man/convert_output.Rd | 4 +- 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 +- 17 files changed, 408 insertions(+), 414 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_bam.R b/R/conout_bam.R index 4f55aa7a..90f2f71a 100644 --- a/R/conout_bam.R +++ b/R/conout_bam.R @@ -3,10 +3,10 @@ #' Does not change naming conventions. #' #' @inheritParams convert_output -#' +#' #' @param file. Assessment model output file path. Currently accepts SS3 #' Report.sso file, BAM .rda file, Rceattle model object, and FIMS model object. -#' +#' #' @param out_new The empty standard output data frame from #' [convert_output()], which sets the columns of the output. #' diff --git a/R/conout_rceattle.R b/R/conout_rceattle.R index 4baacd94..dca7916e 100644 --- a/R/conout_rceattle.R +++ b/R/conout_rceattle.R @@ -3,10 +3,10 @@ #' Does not change naming conventions. #' #' @inheritParams convert_output -#' +#' #' @param file. Assessment model output file path. Currently accepts SS3 #' Report.sso file, BAM .rda file, Rceattle model object, and FIMS model object. -#' +#' #' @param out_new The empty standard output data frame from #' [convert_output()], which sets the columns of the output. #' diff --git a/R/conout_ss3.R b/R/conout_ss3.R index 79afe4fe..04b6b231 100644 --- a/R/conout_ss3.R +++ b/R/conout_ss3.R @@ -4,10 +4,10 @@ #' file or returned object from `r4ss::ss_output()`. #' #' @inheritParams convert_output -#' +#' #' @param file. Assessment model output file path. Currently accepts SS3 #' Report.sso file, BAM .rda file, Rceattle model object, and FIMS model object. -#' +#' #' @param out_new The empty standard output data frame from #' [convert_output()], which sets the columns of the output. #' @@ -1263,7 +1263,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( @@ -1278,7 +1278,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 3622f13d..9f5be6c4 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. @@ -67,9 +67,9 @@ #' save_dir = here::here("standard_output.rda") #' ) #' convert_output( -#' file = list("model1"=here::here("model1", "Report.sso"), "model2"=here::here("model2", "Report.sso")), +#' file = list("model1" = here::here("model1", "Report.sso"), "model2" = here::here("model2", "Report.sso")), #' model = c("ss3", "ss3"), -#' fleet_names = list("model1"=c("TWL", "NONTWL"), "model2"=c("Fishery1", "Survey1", "Survey2")), +#' fleet_names = list("model1" = c("TWL", "NONTWL"), "model2" = c("Fishery1", "Survey1", "Survey2")), #' save_dir = here::here("standard_output.rda") #' ) #' } @@ -80,268 +80,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(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(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_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_retrospective.R b/R/plot_retrospective.R index fea5df17..7cca54ef 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 = "All", # 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}"), @@ -222,9 +219,8 @@ plot_retrospective <- function( cli::cli_alert_danger("No captions, alt-text, or key quantities were stored at this time.") } - - plt + plt } # plot_retrospective(dat) 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 cfb47702..bf7ddd5a 100644 --- a/R/utils_plot.R +++ b/R/utils_plot.R @@ -700,8 +700,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 |> @@ -1156,31 +1156,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 diff --git a/man/convert_output.Rd b/man/convert_output.Rd index 71f61f17..1015f271 100644 --- a/man/convert_output.Rd +++ b/man/convert_output.Rd @@ -80,9 +80,9 @@ convert_output( save_dir = here::here("standard_output.rda") ) convert_output( - file = list("model1"=here::here("model1", "Report.sso"), "model2"=here::here("model2", "Report.sso")), + file = list("model1" = here::here("model1", "Report.sso"), "model2" = here::here("model2", "Report.sso")), model = c("ss3", "ss3"), - fleet_names = list("model1"=c("TWL", "NONTWL"), "model2"=c("Fishery1", "Survey1", "Survey2")), + fleet_names = list("model1" = c("TWL", "NONTWL"), "model2" = c("Fishery1", "Survey1", "Survey2")), save_dir = here::here("standard_output.rda") ) } 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 853f6563..efb2872a 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")) - 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")) + 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 f12c97c6..c0e34df2 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")) - 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")) + 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 5e633c51..933c9441 100644 --- a/tests/testthat/test-utils_plot.R +++ b/tests/testthat/test-utils_plot.R @@ -183,9 +183,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, @@ -195,7 +195,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