diff --git a/NAMESPACE b/NAMESPACE index 055c2f9f..1b0f8777 100644 --- a/NAMESPACE +++ b/NAMESPACE @@ -31,6 +31,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_bam.R b/R/conout_bam.R index 8d03dc15..76f9209d 100644 --- a/R/conout_bam.R +++ b/R/conout_bam.R @@ -275,19 +275,24 @@ conout_bam <- function( module_name = names(extract) ) } - if (any(grepl(paste(fleet_names, collapse = "|"), df$label))) { + if (any(grepl(paste(fleet_names, collapse = "|"), tolower(df$label)))) { df <- df |> dplyr::mutate( fleet = dplyr::case_when( - grepl(paste(fleet_names, collapse = "|"), label) ~ stringr::str_extract(label, paste(fleet_names, collapse = "|")), + grepl(paste(fleet_names, collapse = "|"), tolower(label)) ~ stringr::str_extract(tolower(label), paste(fleet_names, collapse = "|")), TRUE ~ NA ), label = dplyr::case_when( is.na(fleet) ~ label, - TRUE ~ stringr::str_replace(label, paste(".", fleet_names, sep = "", collapse = "|"), "") + TRUE ~ stringr::str_replace(tolower(label), paste(".", fleet_names, sep = "", collapse = "|"), "") ) ) } + + if(names(extract) == "like"){ + df <- df|> dplyr::rename(likelihood = estimate) + } + df[setdiff(tolower(names(out_new)), tolower(names(df)))] <- NA out_list[[names(extract)]] <- df } diff --git a/R/conout_rceattle.R b/R/conout_rceattle.R index 006b1e8b..795d479b 100644 --- a/R/conout_rceattle.R +++ b/R/conout_rceattle.R @@ -404,6 +404,7 @@ conout_rceattle <- function( # Rceattle stores sex 1 as females, or both sexes when nsex = 1. sex_names <- if (nsex == 1) NA_character_ else c("female", "male") quantities_list <- list() + likelihoods_list <- list() if ("sel_at_age" %in% names(extract[[1]])) { sel <- extract[[1]][["sel_at_age"]][, seq_len(nsex), seq_along(ages), , drop = FALSE] @@ -438,6 +439,31 @@ conout_rceattle <- function( quantities_list[["m_at_age"]] <- df_m } + if("jnll_comp" %in% names(extract[[1]])) { + jnll_comp_fleet <- extract[[1]][["jnll_comp"]] + jnll_comp_fleet_df <- jnll_comp_fleet |> + as.data.frame() |> + tibble::rownames_to_column(var = "label") |> + tidyr::pivot_longer(cols=2:dplyr::last_col(), names_to="fleet", values_to="likelihood") + + # jnll_comp_df <- jnll_comp_fleet_df |> + # dplyr::group_by(label) |> + # dplyr::summarise(estimate = sum(estimate), .groups = "drop") |> + # dplyr::mutate(type = "values") + + jnll_comp_fleet_df[setdiff(tolower(names(out_new)), tolower(names(jnll_comp_fleet_df)))] <- NA + # jnll_comp_df[setdiff(tolower(names(out_new)), tolower(names(jnll_comp_df)))] <- NA + + likelihoods_list[["jnll_comp_fleet"]] <- jnll_comp_fleet_df + # likelihoods_list[["jnll_comp"]] <- jnll_comp_df + + # jnll_df <- data.frame(label="Total data", estimate=sum(jnll_comp_df$estimate), type="values") + # jnll_df[setdiff(tolower(names(out_new)), tolower(names(jnll_df)))] <- NA +# + # likelihoods_list[["jnll"]] <- jnll_df + + } + if (length(quantities_list) > 0) { out_list[[names(extract)]] <- Reduce(rbind, quantities_list) |> dplyr::mutate( @@ -445,7 +471,14 @@ conout_rceattle <- function( age = as.character(age) ) } - } else if (is.list(extract[[1]])) { # indicates vector and list + + if (length(likelihoods_list) > 0) { + out_list[["likelihoods"]] <- Reduce(rbind, likelihoods_list) |> + dplyr::mutate( + module_name = "likelihoods" + ) + } + }else if (is.list(extract[[1]])) { # indicates vector and list ##### remaining lmnts #### if (any(vapply(extract[[1]], is.matrix, FUN.VALUE = logical(1)))) { ############################################################## diff --git a/R/conout_ss3.R b/R/conout_ss3.R index 01bf08a9..c21f48a3 100644 --- a/R/conout_ss3.R +++ b/R/conout_ss3.R @@ -194,7 +194,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 @@ -1043,24 +1043,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|lambda", Label)) |> + dplyr::rename(label=Label) |> + dplyr::select(-ALL) |> + tidyr::pivot_longer( + cols = -label, + names_to = "fleet", + values_to = "likelihood" + ) |> + 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/convert_output.R b/R/convert_output.R index 1b59fab3..9fc9362a 100644 --- a/R/convert_output.R +++ b/R/convert_output.R @@ -228,6 +228,7 @@ convert_output <- function( } } + model <- models[i] # Recognize model through file extension if (is.character(file) && tolower(stringr::str_extract(file, "\\.([^.]+)$")) == ".rds") { file <- readRDS(file) diff --git a/R/data.R b/R/data.R index fe275547..618457ba 100644 --- a/R/data.R +++ b/R/data.R @@ -76,6 +76,7 @@ #' \item{bio_pattern}{Indexing column of data} #' \item{settlement}{Indexing column of data} #' \item{morph}{Indexing column of data} +#' \item{beg_mid}{Whether a time series value refers to the beginning or middle of the season} #' \item{type}{Indexing column of data} #' \item{factor}{Indexing column of data} #' \item{part}{Indexing column of data} @@ -86,7 +87,8 @@ #' \item{length_bins}{Length bins for composition or other length based data} #' \item{count}{Indexing column of data} #' \item{block}{Indexing column of data} -#' \item{model}{Indexing column of data} +#' \item{unit}{Units of the estimate when reported by the model} +#' \item{model}{Name of the model the row belongs to, assigned by convert_output()} #' } #' #' @keywords datasets @@ -111,7 +113,7 @@ #' #' @usage data(vermilion_snapper) #' -#' @format A tibble (\code{tbl_df}, \code{tbl}, \code{data.frame}) with 35,881 rows and 35 variables: +#' @format A tibble (\code{tbl_df}, \code{tbl}, \code{data.frame}) with 686,991 rows and 36 variables: #' \describe{ #' \item{label}{Standard name for estimate or value name} #' \item{estimate}{Actual value of the label} @@ -136,6 +138,7 @@ #' \item{bio_pattern}{Indexing column of data} #' \item{settlement}{Indexing column of data} #' \item{morph}{Indexing column of data} +#' \item{beg_mid}{Whether a time series value refers to the beginning or middle of the season} #' \item{type}{Indexing column of data} #' \item{factor}{Indexing column of data} #' \item{part}{Indexing column of data} @@ -146,6 +149,8 @@ #' \item{length_bins}{Length bins for composition or other length based data} #' \item{count}{Indexing column of data} #' \item{block}{Indexing column of data} +#' \item{unit}{Units of the estimate when reported by the model} +#' \item{model}{Name of the model the row belongs to, assigned by convert_output()} #' } #' #' @keywords datasets diff --git a/R/plot_biomass.R b/R/plot_biomass.R index 6ef3fb16..4b1cbd66 100644 --- a/R/plot_biomass.R +++ b/R/plot_biomass.R @@ -132,8 +132,8 @@ plot_biomass <- function( # TODO: check and add into process_data step to summarize when theres >1 label processing <- process_data( prepared_data, - group, - facet + group = group, + facet = facet ) # variable <- processing[[1]] diff --git a/R/plot_likelihoods.R b/R/plot_likelihoods.R new file mode 100644 index 00000000..a64f05d3 --- /dev/null +++ b/R/plot_likelihoods.R @@ -0,0 +1,231 @@ +#' Plot likelihood components as a horizontal bar chart +#' +#' Plot likelihood components as a horizontal bar chart. +#' +#' @details 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 +#' +#' @param remove_zeros Logical, whether to remove likelihood components that +#' are 0. This simplifies the plots by removing likelihood components that +#' are not contributing to the likelihood. +#' +#' Default: TRUE +#' +#' @param show_values Logical, whether to display the likelihood values on the bars. +#' +#' 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_likelihoods( +#' dat, +#' ) +#' plot_likelihoods( +#' dat, +#' by_fleet = TRUE, +#' show_values = TRUE +#' ) +#' plot_likelihoods( +#' dat, +#' by_fleet = TRUE, +#' summarise_fleets = TRUE, +#' ) +#' } +plot_likelihoods <- function( + dat, + by_fleet=FALSE, + summarise_fleets=FALSE, + remove_zeros = TRUE, + show_values = FALSE, + group=NULL, + facet=NULL, + model=NULL, + interactive = TRUE, + make_rda = FALSE, + figures_dir = getwd(), + ... +){ + check_data(dat) + + if(by_fleet){ + cli::cli_alert_info("Plotting likelihood components by fleet.") + facet <- "fleet" + group_by <- c("model", "fleet") + }else{ + group_by <- c("model") + } + + bam_throw_away <- c("w\\.", "^w_", "*_weight", "lk_total", "lk_unwgt_data", "gradient_max") + + # This is specifically for FIMS which stores likelihood data without + # a specific likelihood module. + if("likelihoods" %notin% unique(dat$module_name)){ + dat <- dat |> dplyr::mutate( + module_name = dplyr::case_when( + !is.na(likelihood) ~ "likelihood", + TRUE ~ module_name + ) + ) + } + + prepared_data <- filter_data( + dat = dat, + label_name = "", + geom="bar", + era=NULL, + group=group, + facet=facet, + model=model, + module="like", + scale_amount=1, + interactive=TRUE + ) |> dplyr::filter( + !grepl("laplace_obj_fun", label), # get ride of SS3 lapalce objective function component + !grepl(paste(bam_throw_away, collapse="|"), label) # get rid of weird BAM components + ) + + + if(!by_fleet){ + fleetagg_likelihood <- prepared_data |> + dplyr::group_by(label, model) |> + dplyr::summarise(likelihood=sum(likelihood)) |> + dplyr::ungroup() |> + dplyr::mutate( + fleet = "None" + ) + }else{ + fleetagg_likelihood <- prepared_data |> + dplyr::group_by(label, fleet, model) |> + dplyr::summarise(likelihood=sum(likelihood)) |> + dplyr::ungroup() + } + + total_likelihood_data <- fleetagg_likelihood |> + dplyr::group_by(dplyr::across(dplyr::all_of(group_by))) |> + dplyr::summarise( + likelihood = sum(likelihood, na.rm=TRUE) + ) |> + dplyr::mutate( + label="total", + ) |> + dplyr::bind_rows(fleetagg_likelihood) |> + # This ensures that likelihood components that are not directly + # attributed to a fleet get a human readable name ("None") + dplyr::mutate( + fleet = dplyr::case_when( + is.na(fleet) ~ "None", + TRUE ~ fleet + ) + ) + + # get all of the columns back + total_likelihood_data[setdiff(tolower(names(prepared_data)), tolower(names(total_likelihood_data)))] <- NA + # prepared_data <- total_likelihood_data + + processing <- process_data( + dat = total_likelihood_data, + value_column = "likelihood", + group = NULL, + facet = facet + ) + + plot_data <- processing[[1]] |> dplyr::filter(!is.na(likelihood)) + if(remove_zeros) + plot_data <- plot_data |> dplyr::filter(likelihood != 0) + + if(by_fleet && summarise_fleets){ + plot_data <- plot_data |> + dplyr::group_by(model, group_var, label) |> + dplyr::summarise( + fleet="Total", + likelihood = sum(likelihood) + ) |> 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=likelihood, + fill=if(length(unique(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))*1.2, max(abs(.x))*1.2), + expand = ggplot2::expansion(mult = 0.15), + labels = scales::label_wrap(width = 15) + )+ + ggplot2::guides()+ + ggplot2::labs( + y="Likelihood Component", + x="Likelihood Contribution", + fill = if(length(unique(plot_data$model))>1){ + "Model" + }else{ + "Component" + } + )+ + theme_noaa() + + if(show_values){ + + plt <- plt + ggplot2::geom_text( + ggplot2::aes( + y=label, + x=(60*sign(likelihood))+(likelihood), + label=prettyNum(round(likelihood, 2), big.mark=","), + hjust = ifelse(likelihood < 0, 1, 0) + ) + ) + + } + + # 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 +} diff --git a/R/process_data.R b/R/process_data.R index 5fcee3f6..d898e6c4 100644 --- a/R/process_data.R +++ b/R/process_data.R @@ -6,6 +6,12 @@ #' #' @param dat Data frame. Pre-filtered data from \link[stockplotr]{filter_data} following a #' long format data. +#' @param value_column String. The name of the column containing the values +#' to be processed. For most data, this will be "estimate", but is "likelihood" +#' for likelihood data, +#' +#' Default: "estimate" +#' #' @param group String. Indexing variable of the data. #' To remove any groups and summarize data across all factors, set #' group = "none". Setting group = NULL will keep any grouping @@ -50,6 +56,7 @@ #' } process_data <- function( dat, + value_column = "estimate", group = NULL, facet = NULL, lbs = FALSE @@ -97,7 +104,7 @@ process_data <- function( if (length(index_variables) > 0) { data <- data |> dplyr::select(tidyselect::all_of(c( - "label", "estimate", # "uncertainty", "uncertainty_label", + "label", value_column, # "uncertainty", "uncertainty_label", "estimate_upper", "estimate_lower", # need to maintain columns made from prep data "model", "group_var", @@ -140,7 +147,7 @@ process_data <- function( tidyr::pivot_wider( id_cols = tidyselect::any_of(c("label", "year", "age", "model")), names_from = tidyselect::any_of(group), - values_from = estimate, + values_from = !!rlang::sym(value_column), values_fn = list ) } @@ -241,11 +248,11 @@ process_data <- function( # pivot data for 1st indexed data and check if all the same if (length(index_variables) > 0) { pivot_data <- data |> - dplyr::select(tidyselect::any_of(c("year", "age", "estimate", index_variables))) |> + dplyr::select(tidyselect::any_of(c("year", "age", value_column, index_variables))) |> tidyr::pivot_wider( id_cols = c(year), names_from = tidyselect::any_of(index_variables), - values_from = estimate + values_from = !!rlang::sym(value_column) ) |> suppressWarnings() column_data <- pivot_data[-1] @@ -253,11 +260,11 @@ process_data <- function( } else { # Look at group_var and identify if there is a needed grouping or can just plot one year pivot_data <- data |> - dplyr::select(tidyselect::any_of(c("year", "age", "estimate", "group_var"))) |> + dplyr::select(tidyselect::any_of(c("year", "age", value_column, "group_var"))) |> tidyr::pivot_wider( id_cols = if ("year" %in% colnames(data)) "year" else NULL, names_from = group_var, - values_from = estimate + values_from = !!rlang::sym(value_column) ) |> suppressWarnings() # if (ncol(pivot_data) > 1) column_data <- pivot_data[-1] else column_data <- pivot_data diff --git a/R/utils_plot.R b/R/utils_plot.R index 2879ebe8..f08da54a 100644 --- a/R/utils_plot.R +++ b/R/utils_plot.R @@ -1264,7 +1264,7 @@ filter_interactive <- function( column_value <- available_names[1] } selected <- if (default_all && "all" %in% column_value) available_names else column_value - plot_dat <- dat |> dplyr::filter(.data[[column_name]] %in% selected) + plot_dat <- dat |> dplyr::filter(grepl(paste0(selected, collapse = "|"), .data[[column_name]])) } else { cli::cli_alert_warning("Multiple {pretty_columns[column_name]}s found in data. \n") @@ -1306,7 +1306,7 @@ filter_interactive <- function( if (length(selected) > 0) { plot_dat <- dat |> dplyr::filter( - .data[[column_name]] %in% selected + grepl(paste0(selected, collapse = "|"), .data[[column_name]]) ) } } diff --git a/data-raw/DATASET_BAM.R b/data-raw/DATASET_BAM.R index e3976ee7..3b107c54 100644 --- a/data-raw/DATASET_BAM.R +++ b/data-raw/DATASET_BAM.R @@ -5,7 +5,8 @@ EX_REPORT_PATH <- file.path("inst", "extdata", "VermilionSnapper.rdat") pak::local_install(".") # Convert output vermilion_snapper <- stockplotr::convert_output(EX_REPORT_PATH) -# vermilion_snapper <- subset(vermilion_snapper, year > 1980) +# Keep NA-year rows (e.g. likelihood components) alongside recent years +vermilion_snapper <- subset(vermilion_snapper, is.na(year) | year > 1980) # Save object as rda into raw_data usethis::use_data(vermilion_snapper, overwrite = TRUE) # Overwrite as compressed data diff --git a/data/cod.rda b/data/cod.rda index a9cb57db..0e8a7619 100644 Binary files a/data/cod.rda and b/data/cod.rda differ diff --git a/data/ss3_simple.rda b/data/ss3_simple.rda index 6fab0187..e2ae4a2d 100644 Binary files a/data/ss3_simple.rda and b/data/ss3_simple.rda differ diff --git a/data/vermilion_snapper.rda b/data/vermilion_snapper.rda index 29278ec8..5aec6542 100644 Binary files a/data/vermilion_snapper.rda and b/data/vermilion_snapper.rda differ diff --git a/man/cod.Rd b/man/cod.Rd index 931ff7dc..db168280 100644 --- a/man/cod.Rd +++ b/man/cod.Rd @@ -30,6 +30,7 @@ A tibble (\code{tbl_df}, \code{tbl}, \code{data.frame}) with 589,809 rows and 36 \item{bio_pattern}{Indexing column of data} \item{settlement}{Indexing column of data} \item{morph}{Indexing column of data} +\item{beg_mid}{Whether a time series value refers to the beginning or middle of the season} \item{type}{Indexing column of data} \item{factor}{Indexing column of data} \item{part}{Indexing column of data} @@ -40,7 +41,8 @@ A tibble (\code{tbl_df}, \code{tbl}, \code{data.frame}) with 589,809 rows and 36 \item{length_bins}{Length bins for composition or other length based data} \item{count}{Indexing column of data} \item{block}{Indexing column of data} -\item{model}{Indexing column of data} +\item{unit}{Units of the estimate when reported by the model} +\item{model}{Name of the model the row belongs to, assigned by convert_output()} } } \source{ diff --git a/man/plot_likelihoods.Rd b/man/plot_likelihoods.Rd new file mode 100644 index 00000000..be3414b4 --- /dev/null +++ b/man/plot_likelihoods.Rd @@ -0,0 +1,114 @@ +% 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 as a horizontal bar chart} +\usage{ +plot_likelihoods( + dat, + by_fleet = FALSE, + summarise_fleets = FALSE, + remove_zeros = TRUE, + show_values = FALSE, + group = NULL, + facet = NULL, + model = NULL, + 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{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{remove_zeros}{Logical, whether to remove likelihood components that +are 0. This simplifies the plots by removing likelihood components that +are not contributing to the likelihood. + +Default: TRUE} + +\item{show_values}{Logical, whether to display the likelihood values on the bars. + +Default: FALSE} + +\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: "all" (all models). Set to NULL for interactive selection when available.} + +\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 the value of likelihood components, optionally +across fleets. +} +\description{ +Plot likelihood components as a horizontal bar chart. +} +\details{ +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_likelihoods( + dat, +) +plot_likelihoods( + dat, + by_fleet = TRUE, + show_values = TRUE +) +plot_likelihoods( + dat, + by_fleet = TRUE, + summarise_fleets = TRUE, +) +} +} diff --git a/man/process_data.Rd b/man/process_data.Rd index efe357eb..6a0d75ee 100644 --- a/man/process_data.Rd +++ b/man/process_data.Rd @@ -4,12 +4,24 @@ \alias{process_data} \title{Processing for figures} \usage{ -process_data(dat, group = NULL, facet = NULL, lbs = FALSE) +process_data( + dat, + value_column = "estimate", + group = NULL, + facet = NULL, + lbs = FALSE +) } \arguments{ \item{dat}{Data frame. Pre-filtered data from \link[stockplotr]{filter_data} following a long format data.} +\item{value_column}{String. The name of the column containing the values +to be processed. For most data, this will be "estimate", but is "likelihood" +for likelihood data, + +Default: "estimate"} + \item{group}{String. Indexing variable of the data. To remove any groups and summarize data across all factors, set group = "none". Setting group = NULL will keep any grouping diff --git a/man/vermilion_snapper.Rd b/man/vermilion_snapper.Rd index 69fe7c7a..521533cc 100644 --- a/man/vermilion_snapper.Rd +++ b/man/vermilion_snapper.Rd @@ -5,7 +5,7 @@ \alias{vermilion_snapper} \title{SEDAR 55 South Atlantic Vermilion Snapper} \format{ -A tibble (\code{tbl_df}, \code{tbl}, \code{data.frame}) with 35,881 rows and 35 variables: +A tibble (\code{tbl_df}, \code{tbl}, \code{data.frame}) with 686,991 rows and 36 variables: \describe{ \item{label}{Standard name for estimate or value name} \item{estimate}{Actual value of the label} @@ -30,6 +30,7 @@ A tibble (\code{tbl_df}, \code{tbl}, \code{data.frame}) with 35,881 rows and 35 \item{bio_pattern}{Indexing column of data} \item{settlement}{Indexing column of data} \item{morph}{Indexing column of data} +\item{beg_mid}{Whether a time series value refers to the beginning or middle of the season} \item{type}{Indexing column of data} \item{factor}{Indexing column of data} \item{part}{Indexing column of data} @@ -40,6 +41,8 @@ A tibble (\code{tbl_df}, \code{tbl}, \code{data.frame}) with 35,881 rows and 35 \item{length_bins}{Length bins for composition or other length based data} \item{count}{Indexing column of data} \item{block}{Indexing column of data} +\item{unit}{Units of the estimate when reported by the model} +\item{model}{Name of the model the row belongs to, assigned by convert_output()} } } \usage{ diff --git a/tests/testthat/test-plot-age-to-length.R b/tests/testthat/test-plot-age-to-length.R index d18f4357..c3b5542d 100644 --- a/tests/testthat/test-plot-age-to-length.R +++ b/tests/testthat/test-plot-age-to-length.R @@ -19,7 +19,7 @@ test_that("plot_age_to_length_conversion generates plots without errors", { ) ) - expect_no_error( + expect_no_error( plot_age_to_length_conversion( stockplotr::ss3_simple |> dplyr::filter(age < 10), diff --git a/tests/testthat/test-plot_discard.R b/tests/testthat/test-plot_discard.R index e7ffe7be..e31fdc4d 100644 --- a/tests/testthat/test-plot_discard.R +++ b/tests/testthat/test-plot_discard.R @@ -23,27 +23,27 @@ test_that("plot_discard plots the fit to the observed discards", { test_that("plot_discard options change the plot", { dat <- stockplotr::vermilion_snapper - p <- suppressMessages(plot_discard(dat, interactive = FALSE, module = "t.series")) - expect_length(discard_layers(p, geom = "GeomPoint"), 1) - ribbon <- discard_layers(p, geom = "GeomRibbon")[[1]]$data + p <- suppressMessages(plot_discard(dat, module="t.series", interactive = FALSE)) + expect_length(discard_layers(p, "GeomPoint"), 1) + ribbon <- discard_layers(p, "GeomRibbon")[[1]]$data expect_true(all(ribbon$estimate_lower < ribbon$estimate)) # The predicted discards of vermilion_snapper are within 0.2% of the # observed discards: only the observed discards, as lines expect_message( - p <- plot_discard(dat, tolerance = 0.01, interactive = FALSE, module = "t.series"), + p <- plot_discard(dat, module="t.series", tolerance = 0.01, interactive = FALSE), "differ by less than" ) expect_length(discard_layers(p, geom = "GeomPoint"), 0) - p <- suppressMessages(plot_discard(dat, interval = NULL, interactive = FALSE, module = "t.series")) - expect_equal(nrow(discard_layers(p, geom = "GeomRibbon")[[1]]$data), 0) + p <- suppressMessages(plot_discard(dat, module="t.series", interval = NULL, interactive = FALSE)) + expect_equal(nrow(discard_layers(p, "GeomRibbon")[[1]]$data), 0) - p <- suppressMessages(plot_discard(dat, facet = "fleet", interactive = FALSE, module = "t.series")) + p <- suppressMessages(plot_discard(dat, module="t.series", facet = "fleet", interactive = FALSE)) expect_s3_class(p$facet, "FacetWrap") - p <- suppressMessages(plot_discard(dat, geom = "bar", interactive = FALSE, module = "t.series")) - expect_length(discard_layers(p, geom = "GeomCol"), 1) + p <- suppressMessages(plot_discard(dat, module="t.series", geom = "bar", interactive = FALSE)) + expect_length(discard_layers(p, "GeomCol"), 1) expect_error(plot_discard(dat, tolerance = -1, interactive = FALSE, module = "t.series"), "tolerance") }) diff --git a/tests/testthat/test-plot_likelihoods.R b/tests/testthat/test-plot_likelihoods.R new file mode 100644 index 00000000..9fbfe204 --- /dev/null +++ b/tests/testthat/test-plot_likelihoods.R @@ -0,0 +1,266 @@ +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)) +} + +# Packaged datasets with likelihood output: `ss3_simple` (SS3), `pollock` +# (Rceattle), and `vermilion_snapper` (BAM). All three report fleet-specific +# likelihood components in the standardized convert_output() format, under a +# module whose name contains "like". +packaged_likelihood_cases <- function() { + list( + ss3_simple = list(dat = stockplotr::ss3_simple), + cod = list(dat = stockplotr::cod), + vermilion_snapper = list(dat = stockplotr::vermilion_snapper), + # fims = list(dat=dat_fims) + fims = list( + dat = convert_output( + readRDS(test_path("fixtures", "fims_output", "fims_estimates.rds")), + models = "fims" + ) + ) + ) +} + +# Replicate the label cleaning of filter_data() and the label filters that +# plot_likelihoods() applies across all of its plotting modes. +likelihood_source <- function(dat) { + bam_throw_away <- c( + "w\\.", "^w_", "*_weight", "lk_total", "lk_unwgt_data", "gradient_max" + ) + + # This is specifically for FIMS which stores likelihood data without + # a specific likelihood module. + if("likelihoods" %notin% unique(dat$module_name)){ + dat <- dat |> dplyr::mutate( + module_name = dplyr::case_when( + !is.na(likelihood) ~ "likelihood", + TRUE ~ module_name + ) + ) + } + + dat |> + dplyr::mutate(label = tolower(gsub(" ", "_", label))) |> + dplyr::filter( + grepl("like", module_name), + !grepl("laplace_obj_fun", label), + !grepl(paste(bam_throw_away, collapse = "|"), label) + ) +} + +# Non-zero likelihood components as plot_likelihoods() plots them, with +# components that are not attributed to a fleet assigned to fleet "None". +expected_components <- function(source, by_fleet=FALSE) { + + if(!by_fleet){ + prepared_data3 <- source |> + # dplyr::distinct(label, fleet, likelihood, model) |> + dplyr::group_by(label, model) |> + dplyr::summarise(likelihood=sum(likelihood)) |> + dplyr::ungroup() |> + dplyr::mutate( + fleet = "None" + ) + }else{ + prepared_data3 <- source |> + # dplyr::distinct(label, fleet, likelihood, model) |> + dplyr::group_by(label, fleet, model) |> + dplyr::summarise(likelihood=sum(likelihood)) |> + dplyr::ungroup() + } + + prepared_data3 |> + dplyr::mutate(fleet = dplyr::coalesce(fleet, "None")) |> + dplyr::filter(!is.na(likelihood), likelihood != 0) |> + dplyr::select(model, fleet, label, likelihood) +} + +# The "total" rows appended by plot_likelihoods(): components summed per +# model, or per model and fleet when by_fleet = TRUE. +expected_totals <- function(source, by_fleet = FALSE) { + group_by <- if (by_fleet) c("model", "fleet") else "model" + source |> + dplyr::mutate(fleet = dplyr::coalesce(fleet, "None")) |> + dplyr::group_by(dplyr::across(dplyr::all_of(group_by))) |> + dplyr::summarise(likelihood = sum(likelihood, na.rm = TRUE), .groups = "drop") |> + dplyr::mutate(label = "total", fleet = if (by_fleet) fleet else "None") |> + dplyr::filter(!is.na(likelihood), likelihood != 0) |> + dplyr::select(model, fleet, label, likelihood) +} + +sorted_plot_data <- function(p, by_fleet = FALSE) { + + if(!by_fleet){ + p$data <- p$data |> + dplyr::mutate(fleet = "None") + } + + p$data |> + dplyr::ungroup() |> + dplyr::select(model, fleet, label, likelihood) |> + dplyr::arrange(model, fleet, label, likelihood) +} + +test_that("plot_likelihoods plots total likelihood components from the packaged datasets", { + dats <- packaged_likelihood_cases() + for (case in dats) { + p <- suppressMessages(plot_likelihoods(case$dat, interactive = FALSE)) + source <- likelihood_source(case$dat) + expected <- dplyr::bind_rows( + expected_components(source), + expected_totals(source) + ) |> + dplyr::group_by(model, fleet, label) |> + dplyr::summarise(likelihood = sum(likelihood, na.rm = TRUE), .groups = "drop") |> + dplyr::arrange(model, fleet, label, likelihood) + + expect_s3_class(p, "ggplot") + expect_gt(nrow(expected), 1) + expect_equal(sorted_plot_data(p), expected) + expect_equal( + p$data$likelihood[p$data$label == "total"], + sum(source$likelihood, na.rm = TRUE) + ) + + built <- ggplot2::ggplot_build(p) + expect_equal(nrow(built$layout$layout), 1) + expect_equal(sort(built$data[[1]]$x), sort(expected$likelihood)) + # A single model maps the fill to the likelihood component + expect_setequal( + built$plot$scales$get_scales("fill")$get_limits(), + unique(expected$label) + ) + } +}) + +test_that("plot_likelihoods facets fleet likelihood contributions from the packaged datasets", { + for (case in packaged_likelihood_cases()) { + p <- suppressMessages(plot_likelihoods( + case$dat, by_fleet = TRUE, interactive = FALSE + )) + source <- likelihood_source(case$dat) + components <- expected_components(source, by_fleet = TRUE) + totals <- expected_totals(source, by_fleet = TRUE) + expected <- dplyr::bind_rows(components, totals) |> + dplyr::group_by(model, fleet, label) |> + dplyr::summarise(likelihood = sum(likelihood, na.rm = TRUE), .groups = "drop") |> + dplyr::arrange(model, fleet, label, likelihood) + + expect_s3_class(p, "ggplot") + expect_gt(nrow(components), 0) + expect_equal(sorted_plot_data(p, by_fleet = TRUE), expected) + expect_equal(sum(p$data$label == "total"), nrow(totals)) + + 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(expected$likelihood)) + } +}) + +test_that("plot_likelihoods summarises packaged dataset fleets into a Total facet", { + for (case in packaged_likelihood_cases()) { + p <- suppressMessages(plot_likelihoods( + case$dat, by_fleet = TRUE, summarise_fleets = TRUE, interactive = FALSE + )) + source <- likelihood_source(case$dat) + per_fleet <- dplyr::bind_rows( + expected_components(source, by_fleet = TRUE), + expected_totals(source, by_fleet = TRUE) + ) + total_facet <- per_fleet |> + dplyr::group_by(model, label) |> + dplyr::summarise(likelihood = sum(likelihood), .groups = "drop") |> + dplyr::mutate(fleet = "Total") + + plot_data <- p$data |> dplyr::ungroup() + expect_s3_class(p, "ggplot") + expect_s3_class(plot_data$fleet, "factor") + expect_equal(levels(plot_data$fleet)[1], "Total") + expect_equal( + plot_data |> + dplyr::filter(fleet == "Total") |> + dplyr::mutate(fleet = as.character(fleet)) |> + dplyr::select(model, label, likelihood, fleet) |> + dplyr::arrange(model, label), + total_facet |> dplyr::arrange(model, label) + ) + # The per-fleet contributions are preserved alongside the Total facet. + # Fleets absent from the original data ("None") are dropped to NA by the + # fleet factor levels. + expect_equal( + plot_data |> + dplyr::filter(fleet != "Total" | is.na(fleet)) |> + dplyr::select(model, fleet, label, likelihood) |> + dplyr::arrange(model, fleet, label, likelihood), + per_fleet |> + dplyr::mutate( + fleet = factor(fleet, levels = c("Total", unique(case$dat$fleet))) + ) |> + dplyr::select(model, fleet, label, likelihood) |> + dplyr::group_by(model, fleet, label) |> + dplyr::summarise(likelihood = sum(likelihood, na.rm = TRUE), .groups = "drop") |> + dplyr::arrange(model, fleet, label, likelihood) + ) + + built <- ggplot2::ggplot_build(p) + expect_equal(as.character(built$layout$layout$fleet[1]), "Total") + expect_equal(nrow(built$layout$layout), dplyr::n_distinct(plot_data$fleet)) + } +}) + +test_that("plot_likelihoods compares likelihood components across multiple SS3 models", { + dat <- ss3_likelihood_data() + models <- unique(dat$model) + expect_length(models, 3) + source <- likelihood_source(dat) + + # Model selection is pattern based, so "Simple" selects all three fixture + # models + p <- suppressMessages(plot_likelihoods( + dat, model = "Simple", interactive = FALSE + )) + totals <- expected_totals(source) + expected <- dplyr::bind_rows(expected_components(source), totals) |> + dplyr::arrange(model, fleet, label, likelihood) + + expect_s3_class(p, "ggplot") + expect_setequal(p$data$model, models) + expect_equal(sum(p$data$label == "total"), length(models)) + expect_equal(sorted_plot_data(p), expected) + + built <- ggplot2::ggplot_build(p) + expect_equal(nrow(built$layout$layout), 1) + expect_equal(sort(built$data[[1]]$x), sort(expected$likelihood)) + # Multiple models map the fill to the model instead of the component + expect_setequal(built$plot$scales$get_scales("fill")$get_limits(), models) + + p_fleet <- suppressMessages(plot_likelihoods( + dat, model = "Simple", by_fleet = TRUE, interactive = FALSE + )) + fleet_totals <- expected_totals(source, by_fleet = TRUE) + expected_fleet <- dplyr::bind_rows( + expected_components(source, by_fleet=TRUE), + fleet_totals + ) |> + dplyr::arrange(model, fleet, label, likelihood) + + expect_s3_class(p_fleet, "ggplot") + expect_equal(sorted_plot_data(p_fleet, by_fleet=TRUE), expected_fleet) + expect_equal(sum(p_fleet$data$label == "total"), nrow(fleet_totals)) + + built_fleet <- ggplot2::ggplot_build(p_fleet) + expect_setequal(built_fleet$layout$layout$fleet, expected_fleet$fleet) + expect_equal( + nrow(built_fleet$layout$layout), + dplyr::n_distinct(expected_fleet$fleet) + ) +}) diff --git a/tests/testthat/test-plot_retrospective.R b/tests/testthat/test-plot_retrospective.R index 7cbba1c8..245c6636 100644 --- a/tests/testthat/test-plot_retrospective.R +++ b/tests/testthat/test-plot_retrospective.R @@ -23,7 +23,8 @@ test_that("plot_retrospective with SS3 models", { retro <- plot_retrospective( dat = dat, end_years = 0:5, - module = "derived_quants" + module = "derived_quants", + interactive = FALSE ) built <- ggplot2::ggplot_build(retro)