diff --git a/NAMESPACE b/NAMESPACE index c7bad17d..bc973be2 100644 --- a/NAMESPACE +++ b/NAMESPACE @@ -29,6 +29,7 @@ export(plot_fishing_mortality) export(plot_index) export(plot_joint_residuals) export(plot_landings) +export(plot_likelihoods) export(plot_natural_mortality) export(plot_obsvpred) export(plot_recruitment) diff --git a/R/conout_ss3.R b/R/conout_ss3.R index fb3f528b..82c59cf9 100644 --- a/R/conout_ss3.R +++ b/R/conout_ss3.R @@ -192,7 +192,7 @@ conout_ss3 <- function( # ntentionally empty std2 <- c() cha <- c() - info <- c() + info <- c("likelihoods_used", "likelihoods_laplace", "likelihoods_by_fleet") } # Loop for all identified parameters to extract for plotting and use @@ -994,24 +994,43 @@ conout_ss3 <- function( # next #### info #### } else if (parm_sel %in% info) { - # if (parm_sel == "LIKELIHOOD") { - # df1 <- extract[-1, ] - # # make row the header names for first df - # colnames(df1) <- df1[1, ] - # # Remove first row containing column names - # df2 <- df1[-1, ] |> - # dplyr::rename(label = Component) |> - # tidyr::pivot_longer( - # cols = -label, - # names_to = "type", - # values_to = "likelihood" - # ) - # # match to out_new - # df2[setdiff(tolower(names(out_new)), tolower(names(df2)))] <- NA - # # Add to out list - # out_list[[parm_sel]] <- df2 - # } else - if (parm_sel == "DEFINITIONS") { + if (parm_sel %in% c("likelihoods_used", "likelihoods_laplace")) { + df1 <- extract#[-1, ] + # make row the header names for first df + # colnames(df1) <- df1[1, ] + # Remove first row containing column names + df2 <- df1 |> + tibble::rownames_to_column("Component") |> + dplyr::rename(label = Component) |> + tidyr::pivot_longer( + cols = -label, + names_to = "type", + values_to = "estimate" + ) |> + dplyr::mutate(module_name="likelihoods") + # match to out_new + df2[setdiff(tolower(names(out_new)), tolower(names(df2)))] <- NA + + out_list[[parm_sel]] <- df2 + } else if(parm_sel == "likelihoods_by_fleet"){ + df1 <- extract + df2 <- df1 |> + # dplyr::filter(!grepl("use|skip", Label)) |> + dplyr::rename(label=Label) |> + dplyr::select(-ALL) |> + tidyr::pivot_longer( + cols = -label, + names_to = "fleet", + values_to = "estimate" + ) |> + tidyr::separate(col=label, into=c("label", "type"), sep="_(?=lambda|like|N)", remove=FALSE, extra="merge") |> + dplyr::mutate(module_name="likelihoods") + + df2[setdiff(tolower(names(out_new)), tolower(names(df2)))] <- NA + + out_list[[parm_sel]] <- df2 + } #else + else if (parm_sel == "DEFINITIONS") { # Extract start year and end year for iding era start_year <- as.numeric(extract[which(apply(extract, 1, function(row) any(row == "Start_year:"))), 2]) end_year <- as.numeric(extract[which(apply(extract, 1, function(row) any(row == "End_year:"))), 2]) diff --git a/R/plot_likelihoods.R b/R/plot_likelihoods.R new file mode 100644 index 00000000..02eac1a0 --- /dev/null +++ b/R/plot_likelihoods.R @@ -0,0 +1,163 @@ +#' Plot likelihood components +#' +#' Plot likelihood components as a horizontal bar chart. +#' +#' @details The current implementation only supports Stock Synthesis (SS3) models. +#' The `example_data` dataset is not currently compatible. +#' +#' @inheritParams plot_spawning_biomass +#' +#' @param by_fleet Logical, whether to plot fleet specific likelihood +#' components or not +#' +#' Default: FALSE +#' +#' @param summarise_fleets Logical, whether to aggregate fleet specific +#' likelihood components into an additional "total" likelihood when plotting +#' fleet specific likelihoods. Only applied when `by_fleet=TRUE`. +#' +#' Default: FALSE +#' +#' @return A plot showing the value of likelihood components, optionally +#' across fleets. +#' +#' @export +#' +#' @examples +#' \dontrun{ +#' +#' # `example_data` not presently compatible +#' dat <- convert_output(r4ss::SSgetoutput(dir = "path/to/model")) +#' +#' plot_likelhoods( +#' dat, +#' ) +#' plot_likelhoods( +#' dat, +#' by_fleet = TRUE +#' ) +#' plot_likelhoods( +#' dat, +#' by_fleet = TRUE, +#' summarise_fleets = TRUE +#' ) +#' } +plot_likelihoods <- function( + dat, + by_fleet=FALSE, + summarise_fleets=FALSE, + make_rda = FALSE, + figures_dir = getwd(), + interactive = TRUE, + geom="bar", + group=NULL, + facet=NULL, + model=NULL, + ... +){ + check_data(dat) + + likelihood_type <- "values" + if(by_fleet){ + cli::cli_alert_info("Plotting likelihood components by fleet.") + likelihood_type <- "like" + facet <- "fleet" + } + + prepared_data <- filter_data( + dat = dat, + label_name = "", + geom=geom, + era=NULL, + group=group, + facet=facet, + model=model, + module="likelihoods", + scale_amount=1, + interactive=TRUE + ) |> dplyr::filter(!grepl("laplace_obj_fun", label)) + + if(!by_fleet){ + prepared_data <- prepared_data |> + dplyr::filter(is.na(fleet)) + }else{ + prepared_data <- prepared_data |> + dplyr::filter(!is.na(fleet)) + + prepared_data <- prepared_data |> dplyr::group_by(fleet, type, model) |> + dplyr::summarise( + estimate = sum(estimate) + ) |> + dplyr::mutate(label="total") |> + dplyr::bind_rows(prepared_data) + + } + + processing <- process_data( + dat = prepared_data |> dplyr::filter(type==likelihood_type), + group = group, + facet = facet + ) + + plot_data <- processing[[1]] |> dplyr::filter(!is.na(estimate), estimate!=0) + + if(by_fleet && summarise_fleets){ + plot_data <- plot_data |> + dplyr::group_by(model, group_var, label) |> + dplyr::summarise( + fleet="Total", + estimate = sum(estimate) + ) |> dplyr::bind_rows(plot_data) |> + dplyr::mutate( + fleet = factor(fleet, levels=c("Total", unique(dat$fleet))) + ) + } + + group <- processing[[2]] + # if (!is.null(processing[[3]])) facet <- processing[[3]] + + plt <- ggplot2::ggplot(plot_data)+ + ggplot2::geom_col( + ggplot2::aes( + y=label, + x=estimate, + fill=if(length(unique(plot_data$model))>1){ + .data[["model"]] + }else{ + .data[["label"]] + } + ), + position="dodge", stat="identity" + )+ + ggplot2::geom_vline(xintercept=0, linetype="dashed")+ + ggplot2::scale_x_continuous( + limits= ~ c(-max(abs(.x)), max(abs(.x))) + )+ + ggplot2::guides()+ + ggplot2::labs( + y="Likelihood Component", + x="Likelihood Contribution", + fill = if(length(unique(plot_data$model))>1){ + "Model" + }else{ + "Component" + } + )+ + theme_noaa() + + # Check if facet(s) are desired + if (!is.null(facet) & length(facet) > 0) { + facet <- paste("~", paste(facet, collapse = " + ")) + facet_formula <- stats::reformulate(facet) + + plt <- plt + ggplot2::facet_wrap(facet_formula, labeller = function(labels) { + # Clean column names (e.g., "growth_pattern" -> "Growth Pattern") + names(labels) <- tools::toTitleCase(gsub("_", " ", names(labels))) + + # Combine into "Variable: Value" format + lapply(names(labels), function(var) paste0(var, ": ", labels[[var]])) + }) + } + + plt +} \ No newline at end of file diff --git a/man/plot_likelihoods.Rd b/man/plot_likelihoods.Rd new file mode 100644 index 00000000..ff7ecab5 --- /dev/null +++ b/man/plot_likelihoods.Rd @@ -0,0 +1,112 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/plot_likelihoods.R +\name{plot_likelihoods} +\alias{plot_likelihoods} +\title{Plot likelihood components} +\usage{ +plot_likelihoods( + dat, + by_fleet = FALSE, + summarise_fleets = FALSE, + make_rda = FALSE, + figures_dir = getwd(), + interactive = TRUE, + geom = "bar", + group = NULL, + facet = NULL, + model = NULL, + ... +) +} +\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{by_fleet}{Logical, whether to plot fleet specific likelihood +components or not + +Default: FALSE} + +\item{summarise_fleets}{Logical, whether to aggregate fleet specific +likelihood components into an additional "total" likelihood when plotting +fleet specific likelihoods. Only applied when \code{by_fleet=TRUE}. + +Default: 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{interactive}{Logical. TRUE/FALSE; indicate whether the environment is interactive. + +Default: \code{FALSE}} + +\item{geom}{String. Geom used for the plot. + +Default: "line". + +Options: "line", "point", or "area"} + +\item{group}{String. Single column that groups the data. + +Set group = "none" to summarize data over all indexing values. + +Default: NULL +Options: Including, but not limited to: "year", "area", "fleet", "sex", "none", NULL} + +\item{facet}{Character vector. Column name or names used for faceting. + +Default: NULL} + +\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{...}{Arguments called from \link[ggplot2]{geom_line} or \link[ggplot2]{geom_point}} +} +\value{ +A plot showing the value of likelihood components, optionally +across fleets. +} +\description{ +Plot likelihood components as a horizontal bar chart. +} +\details{ +The current implementation only supports Stock Synthesis (SS3) models. +The \code{example_data} dataset is not currently compatible. +} +\examples{ +\dontrun{ + +# `example_data` not presently compatible +dat <- convert_output(r4ss::SSgetoutput(dir = "path/to/model")) + +plot_likelhoods( + dat, +) +plot_likelhoods( + dat, + by_fleet = TRUE +) +plot_likelhoods( + dat, + by_fleet = TRUE, + summarise_fleets = TRUE +) +} +} diff --git a/tests/testthat/test-plot_likelihoods.R b/tests/testthat/test-plot_likelihoods.R new file mode 100644 index 00000000..9887c387 --- /dev/null +++ b/tests/testthat/test-plot_likelihoods.R @@ -0,0 +1,156 @@ +ss3_likelihood_data <- function() { + skip_if_not_installed("r4ss") + models <- c("Simple", "Simple_with_Discard", "Simple_NoCPUE") + outputs <- lapply(stats::setNames(models, models), function(model) { + r4ss::SS_output( + test_path("fixtures", "ss3_models", "models", model), + verbose = FALSE + ) + }) + suppressMessages(convert_output(outputs)) +} + +test_that("plot_likelihoods plots total SS3 likelihoods for one to three models", { + dat <- ss3_likelihood_data() + models <- unique(dat$model) + + for (n_models in seq_along(models)) { + selected <- models[seq_len(n_models)] + p <- suppressMessages(plot_likelihoods( + dat, model = selected, interactive = FALSE + )) + expected <- dat |> + dplyr::mutate(label = tolower(label)) |> + dplyr::filter( + model %in% selected, + module_name == "likelihoods", + type == "values", + is.na(fleet), + !grepl("laplace_obj_fun", label), + !is.na(estimate), + estimate != 0 + ) |> + dplyr::select(model, label, estimate) |> + dplyr::arrange(model, label) + + expect_s3_class(p, "ggplot") + expect_equal( + p$data |> + dplyr::select(model, label, estimate) |> + dplyr::arrange(model, label), + expected + ) + expect_setequal(p$data$model, selected) + expect_equal(sum(p$data$label == "total"), n_models) + expect_true(any(p$data$estimate < 0)) + + built <- ggplot2::ggplot_build(p) + expect_equal(nrow(built$layout$layout), 1) + expect_equal(sort(built$data[[1]]$x), sort(expected$estimate)) + expect_setequal( + built$plot$scales$get_scales("fill")$get_limits(), + if (n_models > 1) selected else unique(expected$label) + ) + } +}) + +test_that("plot_likelihoods preserves SS3 fleet contributions and adds fleet totals", { + dat <- ss3_likelihood_data() + p <- suppressMessages(plot_likelihoods( + dat, model = unique(dat$model), by_fleet = TRUE, interactive = FALSE + )) + expected <- dat |> + dplyr::mutate(label = tolower(label)) |> + dplyr::filter( + module_name == "likelihoods", + type == "like", + !is.na(fleet), + !is.na(estimate), + estimate != 0 + ) |> + dplyr::select(model, fleet, label, estimate) |> + dplyr::arrange(model, fleet, label) + totals <- expected |> + dplyr::group_by(model, fleet) |> + dplyr::summarise(estimate = sum(estimate), .groups = "drop") + + expect_s3_class(p, "ggplot") + expect_equal( + p$data |> + dplyr::ungroup() |> + dplyr::filter(label != "total") |> + dplyr::select(model, fleet, label, estimate) |> + dplyr::arrange(model, fleet, label), + expected + ) + expect_equal( + p$data |> + dplyr::ungroup() |> + dplyr::filter(label == "total") |> + dplyr::select(model, fleet, estimate) |> + dplyr::arrange(model, fleet), + totals + ) + expect_false("Total" %in% p$data$fleet) + + built <- ggplot2::ggplot_build(p) + expect_setequal(built$layout$layout$fleet, expected$fleet) + expect_equal(nrow(built$layout$layout), dplyr::n_distinct(expected$fleet)) + expect_equal( + sort(built$data[[1]]$x), + sort(c(expected$estimate, totals$estimate)) + ) +}) + +test_that("plot_likelihoods summarises SS3 fleets separately for each model", { + dat <- ss3_likelihood_data() + p <- suppressMessages(plot_likelihoods( + dat, model = unique(dat$model), by_fleet = TRUE, + summarise_fleets = TRUE, interactive = FALSE + )) + source <- dat |> + dplyr::mutate(label = tolower(label)) |> + dplyr::filter( + module_name == "likelihoods", + type == "like", + !is.na(fleet), + !is.na(estimate), + estimate != 0 + ) + expected <- source |> + dplyr::group_by(model, label) |> + dplyr::summarise(estimate = sum(estimate), .groups = "drop") + totals <- source |> + dplyr::group_by(model) |> + dplyr::summarise(label = "total", estimate = sum(estimate), .groups = "drop") + expected <- dplyr::bind_rows(expected, totals) |> + dplyr::arrange(model, label) + + expect_s3_class(p, "ggplot") + expect_equal( + p$data |> + dplyr::ungroup() |> + dplyr::filter(fleet == "Total") |> + dplyr::select(model, label, estimate) |> + dplyr::arrange(model, label), + expected + ) + expect_equal( + p$data |> + dplyr::ungroup() |> + dplyr::filter(fleet != "Total", label != "total") |> + dplyr::mutate(fleet = as.character(fleet)) |> + dplyr::select(model, fleet, label, estimate) |> + dplyr::arrange(model, fleet, label), + source |> + dplyr::select(model, fleet, label, estimate) |> + dplyr::arrange(model, fleet, label) + ) + + built <- ggplot2::ggplot_build(p) + expect_equal(as.character(built$layout$layout$fleet[1]), "Total") + expect_setequal(as.character(built$layout$layout$fleet), c("Total", source$fleet)) + expect_equal(nrow(built$data[[1]]), nrow(p$data)) + expect_equal(sort(built$data[[1]]$x), sort(p$data$estimate)) +}) +