diff --git a/DESCRIPTION b/DESCRIPTION index bb9bc23c..7ea28d0a 100644 --- a/DESCRIPTION +++ b/DESCRIPTION @@ -61,6 +61,8 @@ Suggests: quarto, r4ss, rmarkdown, + ggrepel, + ggdist, testthat (>= 3.0.0) VignetteBuilder: knitr diff --git a/NAMESPACE b/NAMESPACE index c7bad17d..b5f7da69 100644 --- a/NAMESPACE +++ b/NAMESPACE @@ -34,6 +34,7 @@ export(plot_obsvpred) export(plot_recruitment) export(plot_recruitment_deviations) export(plot_retrospective) +export(plot_retrospective_squid) export(plot_runs_test) export(plot_selectivity) export(plot_spawning_biomass) diff --git a/R/convert_output.R b/R/convert_output.R index adfc503d..65eab2a7 100644 --- a/R/convert_output.R +++ b/R/convert_output.R @@ -254,6 +254,8 @@ convert_output <- function( # }, 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], diff --git a/R/plot_joint_residuals.R b/R/plot_joint_residuals.R index aa1def07..13007b9a 100644 --- a/R/plot_joint_residuals.R +++ b/R/plot_joint_residuals.R @@ -156,7 +156,7 @@ plot_joint_residuals <- function( data = labels, ggplot2::aes(x = Inf, y = Inf, label = .data$text), hjust = 1.05, vjust = 1.3, - fill = "white", alpha = 0.8, label.size = 0, + fill = "white", alpha = 0.8, linewidth = 0, inherit.aes = FALSE ) } diff --git a/R/plot_retrospective.R b/R/plot_retrospective.R index e7ea5485..451a8f0d 100644 --- a/R/plot_retrospective.R +++ b/R/plot_retrospective.R @@ -142,8 +142,8 @@ plot_retrospective <- function( 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) @@ -230,3 +230,230 @@ plot_retrospective <- function( plt } + +#' Plot retrospective recruitment deviations +#' +#' Plot estimate recruitment deviations by cohort across retrospective +#' model 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 cohort_years Integer. vector of cohort years (year in which recruitment +#' occurred), to plot. May include forecast years. May be of different length than +#' `end_years`. +#' +#' Default: NULL (most recent `length(end_years)` cohorts) +#' +#' @param relative Logical. Whether to plot traditional squid plot, or to plot +#' recruitment deviations relative to the value for which the most data is +#' available. This create a "funnel" plot. +#' +#' Default: FALSE +#' +#' @param group String. Single column that groups the data. +#' +#' Default: "model" +#' +#' @return A plot showing estimates of recruitment for each cohort. +#' +#' @details The input is from an assessment model output file +#' translated to a standardized output (\link[stockplotr]{convert_output}). +#' There are options to return a `ggplot2` object or export an .rda object +#' containing associated caption and alternative text for the figure. +#' +#' @note +#' All plotting functions automatically recognize indexing variables and will +#' use them in groupings and/or facetting, but will prioritize the defined +#' group or facet by the function arguments. @seealso [process_data()]. +#' +#' @seealso [convert_output()], [plot_timeseries()], [calculate_reference_point()], [reference_line()], [filter_data()], [process_data()], [export_kqs()], [insert_kqs()], [create_rda()], [plot_retrospective()] +#' +#' @export +#' +#' @examples +#' \dontrun{ +#' +#' plot_retrospective_squid( +#' dat = ss3_simple, +#' end_years = 0:-5 +#' ) +#' +#' x <- list(); +#' x[[1]] <- r4ss::SS_output(fs::path(getwd(), "model_runs", "base_model")) +#' for (y in 1:10) { # ten retrospective model runs +#' x[[length(x) + 1]] <- r4ss::SS_output(fs::path(getwd(), "model_runs", "base_model_retros", "retro", paste0("retro-", y)) +#' } +#' names(x) <- paste0("retro-",0:10) +#' retrospective_dat <- convert_output(x) +#' +#' plot_retrospective_squid( +#' dat = retrospective_dat, +#' end_years = 0:10, # ten years of retrospective peels +#' cohort_years = 2010:2024, # plot these 15 cohorts +#' relative = FALSE, +#' interactive = FALSE, +#' module = "recruit" +#' ) +#' } +plot_retrospective_squid <- function( + dat, + end_years = NULL, + cohort_years = NULL, + relative = FALSE, + module=NULL, + model=NULL, + group = "model", + interactive=TRUE, + make_rda = FALSE, + figures_dir = getwd(), + ... +) { + + 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) { + cli::cli_alert_info("Different number of end_years and available models.") + 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 (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))) { + cli::cli_alert("`end_years` provided without names. names automatically applied.") + names(end_years) <- dat$model |> unique() + } + + check_data(dat) + + prepared_data <- filter_data( + dat, + label_name="recruitment_deviations", + module = module, + model = names(end_years), + era = NULL, + interactive = interactive, + geom = "line", + group = group, + allow_multiple_models = TRUE + ) + + if(is.null(cohort_years)){ + cohort_years <- (max(prepared_data$year)-n_models):max(prepared_data$year) + } + + squid_dat <- prepared_data |> + dplyr::distinct() |> + dplyr::filter(year %in% cohort_years) |> + # dplyr::select(estimate, year, model, era) |> + dplyr::mutate(max_year = max(year)) |> + split(~year) |> + purrr::imap(function(df, index){ + df |> + dplyr::mutate(cohort_age = max_year - year - dplyr::row_number() + 1) |> + dplyr::filter(cohort_age >= 0) + }) |> + purrr::list_rbind() + + # Convert from squid to funnel plot + if(relative){ + squid_dat <- squid_dat |> + dplyr::group_by(year) |> + dplyr::mutate( + estimate = estimate-estimate[cohort_age==max(cohort_age)], + estimate_lower = estimate_lower-estimate_lower[cohort_age==max(cohort_age)], + estimate_upper = estimate_upper-estimate_upper[cohort_age==max(cohort_age)] + ) + } + + squid_dat <- squid_dat |> + dplyr::ungroup() |> + dplyr::group_by(year) |> + dplyr::mutate( + # if relative=TRUE, place labels at the youngest cohort age; otherwise, place them at the oldest cohort age. + cohort_label = ifelse( + cohort_age == (if (relative) min(cohort_age) else max(cohort_age)) & !duplicated(cohort_age), + as.character(year), + "" + ) + ) |> + dplyr::ungroup() |> + dplyr::mutate( + cohort_year=factor(year), + cohort_age=factor(cohort_age, levels=0:max(squid_dat$cohort_age)) + ) + + plt <- ggplot2::ggplot(squid_dat)+ + ggdist::geom_lineribbon( + ggplot2::aes( + x=cohort_age, + y=estimate, ymin=estimate_lower, ymax=estimate_upper, + color=cohort_year, group=cohort_year, fill=cohort_year + ), + linewidth=0.75, alpha=0.3 + )+ + ggplot2::geom_point( + ggplot2::aes(x=cohort_age, y=estimate, color=cohort_year), + size=2 + )+ + ggrepel::geom_text_repel( + ggplot2::aes(x=cohort_age, y=estimate, label=cohort_label, color=cohort_year), + nudge_x=ifelse(squid_dat$cohort_label == "", 0, if (relative) -0.25 else 0.25), + direction="y", hjust=if (relative) 1 else 0, point.padding=0.25, box.padding=0.3, + max.overlaps=Inf, show.legend=FALSE, seed=1 + )+ + ggplot2::geom_hline(yintercept=0.0, linetype="solid", color="gray")+ + # geom_hline(yintercept=c(-2, 2), linetype="dashed")+ + ggplot2::scale_x_discrete(expand=ggplot2::expansion(add=if (relative) c(1.5, 0.6) else c(0.6, 1.5)))+ + ggplot2::scale_y_continuous( + limits=c( + min(-1,min(squid_dat$estimate*1.5)), + max(1, max(squid_dat$estimate*1.5)) + ) + )+ + ggplot2::guides( + color=ggplot2::guide_legend("Cohort Year"), + fill=ggplot2::guide_legend("Cohort Year") + )+ + ggplot2::labs(x="Cohort Age", y="Recruitment Deviation")+ + theme_noaa() + + if (make_rda) { + create_rda( + object = plt, + topic_label = glue::glue("squid_retrospective_{quantity}"), + fig_or_table = "figure", + dat = NULL, + dir = figures_dir, + ref_line = ifelse(!is.null(names(ref_line)), names(ref_line), ref_line), + scale_amount = scale_amount + ) + + cli::cli_alert_danger("No captions, alt-text, or key quantities were stored at this time.") + } + + if (exists("selected_module")) { + rm(selected_module, envir = .GlobalEnv) + } + + if (exists("selected_model")) { + rm(selected_model, envir = .GlobalEnv) + } + + plt + +} diff --git a/man/plot_retrospective_squid.Rd b/man/plot_retrospective_squid.Rd new file mode 100644 index 00000000..c548664d --- /dev/null +++ b/man/plot_retrospective_squid.Rd @@ -0,0 +1,130 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/plot_retrospective.R +\name{plot_retrospective_squid} +\alias{plot_retrospective_squid} +\title{Plot retrospective recruitment deviations} +\usage{ +plot_retrospective_squid( + dat, + end_years = NULL, + cohort_years = NULL, + relative = FALSE, + module = NULL, + model = NULL, + group = "model", + interactive = TRUE, + make_rda = FALSE, + figures_dir = getwd(), + ... +) +} +\arguments{ +\item{dat}{Data frame or list. A tibble or named list of tibbles (input as \code{list()}) +returned from \link[stockplotr]{convert_output}. + +If inputting a list of tibbles, the first tibble's reference point defined +in \code{ref_line} is used to plot a reference line or calculate relative spawning biomass.} + +\item{end_years}{Integer. vector of what year, relative to the maximum +year present in \code{dat}, should be treated as the final year for each +model. Should be <= 0. + +Default: 0} + +\item{cohort_years}{Integer. vector of cohort years (year in which recruitment +occurred), to plot. May include forecast years. May be of different length than +\code{end_years}. + +Default: NULL (most recent \code{length(end_years)} cohorts)} + +\item{relative}{Logical. Whether to plot traditional squid plot, or to plot +recruitment deviations relative to the value for which the most data is +available. This create a "funnel" plot. + +Default: FALSE} + +\item{module}{Character vector. (Optional) Module name found in \code{dat$module_name}. +If selecting >1 module, place them in a vector like c("module1", "module2"). + +Default: NULL + +If the interactive and >1 module_name is found, user will select the +module_name in the console. @seealso \code{\link[=filter_data]{filter_data()}}} + +\item{model}{Character vector. (Optional) Model name found in \code{dat$model}. +If selecting >1 model, place them in a vector like c("model1", "model2"). + +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{group}{String. Single column that groups the data. + +Default: "model"} + +\item{interactive}{Logical. TRUE/FALSE; indicate whether the environment is interactive. + +Default: \code{FALSE}} + +\item{make_rda}{Logical. TRUE/FALSE; indicate whether to save the object and +make an automated caption and alternative text in the form of an \code{rda} object. If TRUE, +the rda will be exported to the folder indicated in the argument "figures_dir". + +Default: \code{FALSE}.} + +\item{figures_dir}{Path. Path to the "figures" folder. + +Default: \code{getwd()} + +The folder is created within the path if it does not exist.} + +\item{...}{Arguments called from \link[ggplot2]{geom_line} or \link[ggplot2]{geom_point}} +} +\value{ +A plot showing estimates of recruitment for each cohort. +} +\description{ +Plot estimate recruitment deviations by cohort across retrospective +model peels. +} +\details{ +The input is from an assessment model output file +translated to a standardized output (\link[stockplotr]{convert_output}). +There are options to return a \code{ggplot2} object or export an .rda object +containing associated caption and alternative text for the figure. +} +\note{ +All plotting functions automatically recognize indexing variables and will +use them in groupings and/or facetting, but will prioritize the defined +group or facet by the function arguments. @seealso \code{\link[=process_data]{process_data()}}. +} +\examples{ +\dontrun{ + +plot_retrospective_squid( + dat = ss3_simple, + end_years = 0:-5 +) + +x <- list(); +x[[1]] <- r4ss::SS_output(fs::path(getwd(), "model_runs", "base_model")) +for (y in 1:10) { # ten retrospective model runs + x[[length(x) + 1]] <- r4ss::SS_output(fs::path(getwd(), "model_runs", "base_model_retros", "retro", paste0("retro-", y)) +} +names(x) <- paste0("retro-",0:10) +retrospective_dat <- convert_output(x) + +plot_retrospective_squid( + dat = retrospective_dat, + end_years = 0:10, # ten years of retrospective peels + cohort_years = 2010:2024, # plot these 15 cohorts + relative = FALSE, + interactive = FALSE, + module = "recruit" +) +} +} +\seealso{ +\code{\link[=convert_output]{convert_output()}}, \code{\link[=plot_timeseries]{plot_timeseries()}}, \code{\link[=calculate_reference_point]{calculate_reference_point()}}, \code{\link[=reference_line]{reference_line()}}, \code{\link[=filter_data]{filter_data()}}, \code{\link[=process_data]{process_data()}}, \code{\link[=export_kqs]{export_kqs()}}, \code{\link[=insert_kqs]{insert_kqs()}}, \code{\link[=create_rda]{create_rda()}}, \code{\link[=plot_retrospective]{plot_retrospective()}} +} diff --git a/tests/testthat/test-convert_output.R b/tests/testthat/test-convert_output.R index 7a17a196..059f6977 100644 --- a/tests/testthat/test-convert_output.R +++ b/tests/testthat/test-convert_output.R @@ -71,7 +71,7 @@ test_that("missing arguments trigger warnings or errors", { models = "fake_model", save_dir = fs::path("fixtures", "ss3_models_converted", "Hake_2018") ), - "`file` not found." + "Output file not compatible." ) dir.create(fs::path("fixtures", "ss3_models_converted", "Hake_2018"), recursive = TRUE) diff --git a/tests/testthat/test-convert_output_fims.R b/tests/testthat/test-convert_output_fims.R index 436190a0..f7710cf3 100644 --- a/tests/testthat/test-convert_output_fims.R +++ b/tests/testthat/test-convert_output_fims.R @@ -100,7 +100,7 @@ test_that("FIMS estimates are relabeled and get years and eras", { expect_false(any(c("expected_recruitment", "log_devs") %in% out$label)) # Without start_year, years are the FIMS year indices - expect_message(convert_output(est, model = "fims"), "start_year") + expect_message(convert_output(est, models = "fims"), "start_year") expect_equal(range(convert_fims(est)$year[convert_fims(est)$label == "spawning_biomass"]), c(1, 31)) }) diff --git a/tests/testthat/test-plot_data_availability.R b/tests/testthat/test-plot_data_availability.R index 58e7fae8..aa2fd47a 100644 --- a/tests/testthat/test-plot_data_availability.R +++ b/tests/testthat/test-plot_data_availability.R @@ -5,7 +5,7 @@ test_that("plot_data_availability works with each example model output", { pollock = stockplotr::pollock, ss3_simple = stockplotr::ss3_simple, vermilion_snapper = stockplotr::vermilion_snapper, - fims = suppressMessages(convert_output(est, model = "fims", start_year = 2001)) + fims = suppressMessages(convert_output(est, models = "fims", start_year = 2001)) ) for (name in names(datasets)) { p <- plot_data_availability(datasets[[name]]) diff --git a/tests/testthat/test-plot_index.R b/tests/testthat/test-plot_index.R index 2ae88b18..2f4fbecb 100644 --- a/tests/testthat/test-plot_index.R +++ b/tests/testthat/test-plot_index.R @@ -85,7 +85,7 @@ test_that("plot_index can use a log scale", { test_that("plot_index intervals work for FIMS output", { est <- readRDS(test_path("fixtures", "fims_output", "fims_estimates.rds")) - fims <- suppressMessages(convert_output(est, model = "fims", start_year = 2001)) + fims <- suppressMessages(convert_output(est, models = "fims", start_year = 2001)) p <- suppressMessages(plot_index(fims, interval = 0.95, interactive = FALSE)) ints <- p$layers[[1]]$data rows <- est[est$label == "index_expected" & !is.na(est$observed), ] @@ -131,7 +131,7 @@ test_that("plot_index can plot all indices relative to their means", { expect_no_error(ggplot2::ggplot_build(p)) expect_no_error(ggplot2::ggplot_build(suppressMessages(plot_index(stockplotr::ss3_simple, relative = TRUE, interactive = FALSE)))) est <- readRDS(test_path("fixtures", "fims_output", "fims_estimates.rds")) - fims <- suppressMessages(convert_output(est, model = "fims", start_year = 2001)) + fims <- suppressMessages(convert_output(est, models = "fims", start_year = 2001)) p <- suppressMessages(plot_index(fims, relative = TRUE, interactive = FALSE)) expect_equal(mean(p$layers[[2]]$data$estimate[p$layers[[2]]$data$label == "index_observed"]), 1) }) diff --git a/tests/testthat/test-plot_joint_residuals.R b/tests/testthat/test-plot_joint_residuals.R index 64e1a1fb..16b301e1 100644 --- a/tests/testthat/test-plot_joint_residuals.R +++ b/tests/testthat/test-plot_joint_residuals.R @@ -5,7 +5,7 @@ test_that("plot_joint_residuals works with each example model output and option" pollock = stockplotr::pollock, ss3_simple = stockplotr::ss3_simple, vermilion_snapper = stockplotr::vermilion_snapper, - fims = suppressMessages(convert_output(est, model = "fims", start_year = 2001)) + fims = suppressMessages(convert_output(est, models = "fims", start_year = 2001)) ) for (name in names(datasets)) { # ss3_simple also has catch labeled as an index in the "catch" module @@ -36,7 +36,7 @@ test_that("residual_stat gives the RMSE and the SDNR with its critical value", { test_that("plot_joint_residuals overlays indices with the statistic, boxplots, and smoother", { resid <- index_residuals(stockplotr::example_data, interactive = FALSE) stat <- residual_stat(resid) - p <- plot_joint_residuals(stockplotr::example_data, interactive = FALSE) + expect_no_warning(p <- plot_joint_residuals(stockplotr::example_data, interactive = FALSE)) layer <- function(p, geom) p$layers[[which(sapply(p$layers, function(l) inherits(l$geom, geom)))]]$data expect_setequal(levels(p$data$index), paste0(stat$series[1:2], " (", stat$value[1:2], ")")) expect_equal(layer(p, "GeomLabel")$text, stat$text[3]) diff --git a/tests/testthat/test-plot_retrospective.R b/tests/testthat/test-plot_retrospective.R index 7cbba1c8..949eee6a 100644 --- a/tests/testthat/test-plot_retrospective.R +++ b/tests/testthat/test-plot_retrospective.R @@ -12,6 +12,40 @@ count_geoms <- function(plot, build, geom) { }) } +test_that("squid plot labels each cohort at the appropriate endpoint", { + prepared <- expand.grid(year = 2018:2020, model = paste0("model", 1:3)) + prepared$estimate <- seq_len(nrow(prepared)) / 10 + prepared$estimate_lower <- prepared$estimate - 0.1 + prepared$estimate_upper <- prepared$estimate + 0.1 + + testthat::local_mocked_bindings( + check_data = function(...) NULL, + filter_data = function(...) prepared, + .package = "stockplotr" + ) + + for (relative in c(FALSE, TRUE)) { + plot <- plot_retrospective_squid(prepared, end_years = 0:-2, relative = relative, interactive = FALSE) + built <- ggplot2::ggplot_build(plot) + label_layer <- which(vapply(plot$layers, function(layer) { + inherits(layer$geom, "GeomTextRepel") + }, logical(1))) + labels <- built$data[[label_layer]] + labels <- labels[labels$label != "", ] + points <- built$data[[2]] + + expect_setequal(labels$label, as.character(2018:2020)) + expect_equal(nrow(labels), 3) + for (index in seq_len(nrow(labels))) { + matching_points <- points[points$colour == labels$colour[index], ] + endpoint <- if (relative) which.min(matching_points$x) else which.max(matching_points$x) + nudge <- if (relative) -0.25 else 0.25 + expect_equal(labels$x[index] - nudge, matching_points$x[endpoint]) + expect_equal(labels$y[index], matching_points$y[endpoint]) + } + } +}) + test_that("plot_retrospective with SS3 models", { x <- list() for (y in 0:-5) { diff --git a/tests/testthat/test-plot_runs_test.R b/tests/testthat/test-plot_runs_test.R index 1fe69818..d58a4ae1 100644 --- a/tests/testthat/test-plot_runs_test.R +++ b/tests/testthat/test-plot_runs_test.R @@ -1,6 +1,6 @@ fims_converted <- function() { est <- readRDS(test_path("fixtures", "fims_output", "fims_estimates.rds")) - suppressMessages(convert_output(est, model = "fims", start_year = 2001)) + suppressMessages(convert_output(est, models = "fims", start_year = 2001)) } test_that("residual_control estimates limits and the runs test", {