diff --git a/NAMESPACE b/NAMESPACE index e5e67881..c7bad17d 100644 --- a/NAMESPACE +++ b/NAMESPACE @@ -33,6 +33,7 @@ export(plot_natural_mortality) export(plot_obsvpred) export(plot_recruitment) export(plot_recruitment_deviations) +export(plot_retrospective) export(plot_runs_test) export(plot_selectivity) export(plot_spawning_biomass) diff --git a/R/plot_retrospective.R b/R/plot_retrospective.R new file mode 100644 index 00000000..fea5df17 --- /dev/null +++ b/R/plot_retrospective.R @@ -0,0 +1,230 @@ +#' Plot retrospective peels +#' +#' 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, +#' biomass, recruitment, etc.). Should correspond to an existing `plot_*` function. +#' +#' 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 +#' retrospective 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 `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()] +#' +#' @export +#' +#' @examples +#' plot_retrospective( +#' dat = ss3_simple, +#' end_years = 0:-5, +#' quantity = "spawning_biomass", +#' show_end_year_points=TRUE +#' ) +#' plot_retrospective( +#' dat = ss3_simple, +#' end_years = 0:-5, +#' quantity = "spr", +#' 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, +#' mohns_rho = c(0.023, 0.01, 1.25, 0.845, 0.068), +#' interactive=FALSE, +#' module = "derived_quants" +#' ) +plot_retrospective <- function( + dat, + end_years=NULL, + quantity="spawning_biomass", + show_end_year_points=TRUE, + mohns_rho = NULL, + 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")))){ + 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){ + 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() + } + + 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))){ + 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::rowwise() |> + dplyr::mutate( + 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::select(-term_year, -max_yr) + + + func_pars <- list( + 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 + ... + ) + + plt <- do.call(func_name, func_pars) + plot_data <- plt$layers[[2]]$data |> + dplyr::rename( + dplyr::any_of(c(estimate="predicted_recruitment")) + ) + + 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) + + plt <- plt+ + ggplot2::geom_point( + 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 + } + } + ), + size=3.5 + ) + } + + 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$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 + ), + # family = "mono", + 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::guides( + color=ggplot2::guide_legend("Peel"), + fill=ggplot2::guide_legend("Peel") + ) + + + if(make_rda){ + + create_rda( + object = plt, + topic_label = glue::glue("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.") + } + + plt + +} + +# plot_retrospective(dat) diff --git a/R/save_all_plots.R b/R/save_all_plots.R index 8336bba0..5680be89 100644 --- a/R/save_all_plots.R +++ b/R/save_all_plots.R @@ -118,12 +118,7 @@ save_all_plots <- function( # plottab_function_files <- all_R_files[grepl("plot_|table_", all_R_files)] # # Remove table_afsc_tier function for now # plottab_function_files <- plottab_function_files[!grepl("afsc", plottab_function_files)] - # Helpers, and the composition plots, which take composition data from - # prepare_composition_data() rather than the standard output - helper_functions <- c( - "plot_timeseries", "plot_aa", "plot_obsvpred", "plot_error", "table_afsc_tier", - "plot_composition" - ) + helper_functions <- c("plot_timeseries", "plot_aa", "plot_obsvpred", "plot_error", "plot_retrospective", "table_afsc_tier", "plot_composition") # plottab_functions <- sub("\\.[^\\.]*$", "", plottab_function_files) all_functions <- ls(getNamespace("stockplotr")) diff --git a/inst/WORDLIST b/inst/WORDLIST index b01ecab2..4d89ec26 100644 --- a/inst/WORDLIST +++ b/inst/WORDLIST @@ -85,6 +85,8 @@ lendbase Lifecycle loess McAllister +Mohn's +mohn's mis Modelling MSY diff --git a/man/plot_retrospective.Rd b/man/plot_retrospective.Rd new file mode 100644 index 00000000..4c27b27d --- /dev/null +++ b/man/plot_retrospective.Rd @@ -0,0 +1,113 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/plot_retrospective.R +\name{plot_retrospective} +\alias{plot_retrospective} +\title{Plot retrospective peels} +\usage{ +plot_retrospective( + dat, + end_years = NULL, + quantity = "spawning_biomass", + show_end_year_points = TRUE, + mohns_rho = NULL, + group = "model", + 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{quantity}{String. Assessment quantity to plot (e.g., spawning biomass, +biomass, recruitment, etc.). Should correspond to an existing \verb{plot_*} function. + +Default: "spawning_biomass"} + +\item{show_end_year_points}{Logical. Whether to add points at the terminal year +for each model peel. + +Default: TRUE} + +\item{mohns_rho}{Numeric. Externally calculated value(s) of Mohn's rho. Should be +either a single value or of length \code{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} + +\item{group}{String. Single column that groups the data. + +Default: "model"} + +\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 values of an assessment quantity across different +retrospective peels. +} +\description{ +Plot a given quantity across multiple models with differing +end years, so as to plot retrospective 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{ +plot_retrospective( + dat = ss3_simple, + end_years = 0:-5, + quantity = "spawning_biomass", + show_end_year_points=TRUE +) +plot_retrospective( + dat = ss3_simple, + end_years = 0:-5, + quantity = "spr", + 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, + mohns_rho = c(0.023, 0.01, 1.25, 0.845, 0.068), + interactive=FALSE, + module = "derived_quants" +) +} +\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()}} +} diff --git a/tests/testthat/test-plot_retrospective.R b/tests/testthat/test-plot_retrospective.R new file mode 100644 index 00000000..6cab6312 --- /dev/null +++ b/tests/testthat/test-plot_retrospective.R @@ -0,0 +1,62 @@ +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) + length(unique(layer_data$group)) + } else { + 0 + } + }) +} + +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) +}) + +# test_that("plot_retrospective with FIMS models", { +# data_4_model <- FIMSFrame(FIMS::data_big) +# parameters <- setup_default_parameters(data = data_4_model) + +# retro_fit <- run_fims_retrospective( +# years_to_remove = 0:5, +# data_4_model, +# parameters, +# n_cores = min(parallel::detectCores()-2, length(0:5)) +# ) + +# fims_retro <- retro_fit$estimates |> +# dplyr::rename( +# year = year_i, +# estimate = estimated, +# model=retrospective_peel +# ) |> +# dplyr::mutate( +# uncertainty_label = "se", +# ) + +# plot_retrospective( +# dat = fims_retro, +# end_years = 0:-5, +# quantity="spawning_biomass", +# unit_label="mt", +# module="derived_quants" +# ) + +# }) \ No newline at end of file