R/plotting.R

Defines functions plot_repair_rate plot_heat_injury plot_temperature_scenarios plot_temperature_density plot_tdt_landscape plot_tdt_curve tdt_clip_axis tdt_facet_by_group plot_survival_curves theme_tdt

Documented in plot_heat_injury plot_repair_rate plot_survival_curves plot_tdt_curve plot_tdt_landscape plot_temperature_density plot_temperature_scenarios theme_tdt

# Plotting helpers for the TDT function library. One plot function per
# prediction/extraction output, plus a shared theme. Each function returns a
# ggplot object the caller can extend with `+ <geom>` if needed.

#' Project ggplot theme
#'
#' A minimal classic theme with bold axis titles, used by all plotting
#' helpers in this library. Caller can override with `+ theme(...)`.
#'
#' @param base_size Base font size, passed to `theme_classic()`. Default 13.
#' @return A ggplot2 theme object.
#' @examples
#' library(ggplot2)
#' ggplot(mtcars, aes(mpg, hp)) + geom_point() + theme_tdt()
#' @export
theme_tdt <- function(base_size = 13) {
  ggplot2::theme_classic(base_size = base_size) +
    ggplot2::theme(
      axis.title       = ggplot2::element_text(face = "bold"),
      panel.border     = ggplot2::element_rect(colour = "black",
                                               fill = NA, linewidth = 0.6),
      legend.position  = "right"
    )
}

#' Plot posterior survival curves
#'
#' Plots posterior median ± 95% CrI of survival as a function of duration, one
#' coloured line per assay temperature. Optionally overlays observed survival
#' proportions per replicate.
#'
#' Colour mapping uses the viridis palette by default (yellow at the highest
#' temperature, dark purple at the lowest); the exposure-duration axis is
#' linear by default, with the classical log-time TDT view available via
#' `log_time = TRUE`.
#'
#' @param pred      Output of [predict_survival_curves()].
#' @param observed  Optional standardised data tibble (from [standardize_data()])
#'                  to overlay as points (jittered, transparent).
#' @param log_time  Logical. If `TRUE`, the exposure-duration axis is log10.
#'                  Default `FALSE` (linear).
#' @param palette   Character. Viridis option for the temperature colour scale.
#'                  Default `"viridis"`; pass `NULL` to keep ggplot's default
#'                  hue scale.
#' @param response_label Character. y-axis label for the modelled response.
#'                  Default `"Survival probability"`; set to e.g.
#'                  `"Retained PSII function"` for a continuous-proportion (Beta)
#'                  endpoint where the response is not survival.
#' @param clip_to_observed Logical. If `TRUE` (the default) and `observed` is
#'                  supplied, each temperature/group curve is capped at the
#'                  longest exposure actually observed for that cell — shorter
#'                  durations are still predicted (the curve there is
#'                  well-behaved, rising to the upper asymptote), but the long tail
#'                  is not extrapolated past the data (e.g. designs that test much
#'                  shorter exposures at hotter temperatures). Prediction cells with
#'                  no matching observed temperature/group combination are dropped.
#'                  A no-op when `observed` is not supplied. Set `FALSE` for the
#'                  full grid.
#' @param facet_scales Facet scale behaviour for grouped fits. `"auto"` (default)
#'                  frees the duration (x) axis per group when
#'                  `clip_to_observed = TRUE` and `observed` is supplied, so each
#'                  group fills its own tested range (survival stays shared at
#'                  `[0, 1]`); otherwise fixed. Or pass any `facet_wrap()` scale
#'                  (`"fixed"`, `"free"`, `"free_x"`, `"free_y"`).
#' @return A ggplot object.
#' @examples
#' \dontrun{
#' pred <- predict_survival_curves(wf, temps = c(30, 32, 34, 36))
#' plot_survival_curves(pred, observed = wf$data)
#' plot_survival_curves(pred, log_time = TRUE)  # classical TDT view
#' }
#' @export
plot_survival_curves <- function(pred, observed = NULL,
                                 log_time = FALSE,
                                 palette  = "viridis",
                                 response_label = "Survival probability",
                                 clip_to_observed = TRUE,
                                 facet_scales = c("auto", "fixed", "free",
                                                  "free_x", "free_y")) {
  facet_scales <- match.arg(facet_scales)
  df  <- pred$summary
  std <- c("temp", "duration", "survival_lower", "survival_median", "survival_upper")
  # By default restrict each (group x temperature) curve to its observed duration
  # range so curves are not drawn far beyond the data (e.g. designs that test much
  # shorter exposures at hotter temperatures). A no-op when `observed` is absent.
  if (isTRUE(clip_to_observed) && !is.null(observed)) {
    df <- tdt_clip_axis(df, observed, std, "duration", by_extra = "temp",
                        drop_unmatched = TRUE, side = "upper")
  }
  p <- ggplot2::ggplot(df, ggplot2::aes(x = duration, y = survival_median,
                                        colour = factor(temp),
                                        fill   = factor(temp))) +
    ggplot2::geom_ribbon(ggplot2::aes(ymin = survival_lower,
                                      ymax = survival_upper),
                         alpha = 0.18, colour = NA) +
    ggplot2::geom_line(linewidth = 0.9) +
    ggplot2::coord_cartesian(ylim = c(0, 1)) +
    ggplot2::labs(x = "Exposure duration", y = response_label,
                  colour = "Temperature (\u00b0C)",
                  fill   = "Temperature (\u00b0C)") +
    theme_tdt()

  if (isTRUE(log_time)) p <- p + ggplot2::scale_x_log10()

  if (!is.null(palette)) {
    p <- p +
      ggplot2::scale_colour_viridis_d(option = palette,
                                      end = 0.95, direction = 1) +
      ggplot2::scale_fill_viridis_d(option = palette,
                                    end = 0.95, direction = 1)
  }

  if (!is.null(observed)) {
    observed <- tdt_observed_as_recorded(observed)   # censored readings as recorded
    p <- p + ggplot2::geom_jitter(
      data = observed,
      ggplot2::aes(x = duration, y = survival, colour = factor(temp)),
      width = 0.02, height = 0, alpha = 0.35, size = 0.8,
      inherit.aes = FALSE
    )
  }
  # Grouped fit (per-group curves): facet so groups are not threaded into one line.
  # `auto` frees the duration (x) axis per group when clipping to observed, so
  # each group fills its own tested range; survival (y) stays shared at [0, 1].
  if (identical(facet_scales, "auto")) {
    facet_scales <- if (isTRUE(clip_to_observed) && !is.null(observed)) "free_x" else "fixed"
  }
  tdt_facet_by_group(p, df, c("temp", "duration",
                              "survival_lower", "survival_median", "survival_upper"),
                     scales = facet_scales)
}

# Facet a TDT plot by its grouping moderator column(s) when the data carries them
# (a grouped predict_*/extract_* output); a no-op for single-condition data.
tdt_facet_by_group <- function(p, df, standard, scales = "fixed") {
  gcols <- setdiff(names(df), standard)
  if (length(gcols)) {
    p + ggplot2::facet_wrap(stats::reformulate(gcols), scales = scales)
  } else {
    p
  }
}

# Restrict a prediction/summary `df` to the observed data extent along one `axis`
# ("duration" or "temp"), grouping by the moderator columns (`df` minus
# `standard`) plus any `by_extra` columns. Two clip granularities:
#   * by_extra = "temp"  -> per (group x temperature) range (discrete observed
#                           temperatures, e.g. plot_survival_curves durations);
#   * by_extra = character() -> per-group range only (a bounding box; used for
#                           the continuous landscape grid and the TDT-curve
#                           temperature axis, whose grids are not the observed
#                           values themselves).
# Rows in cells with no matching observed data are kept intact by default; set
# `drop_unmatched = TRUE` when the caller needs exact observed cells only.
# `side` controls which end is clipped: "both" (default), "upper" (cap at the
# observed maximum but keep predictions below the observed minimum), or "lower".
# Duration is clipped "upper" only -- extrapolating to shorter exposures is
# well-behaved (the curve rises to the upper asymptote), but extrapolating past
# the longest tested exposure is not shown.
# Base R (no tidy-eval) so it is dependency-light and robust.
tdt_clip_axis <- function(df, observed, standard, axis, by_extra = character(),
                          drop_unmatched = FALSE,
                          side = c("both", "upper", "lower")) {
  side <- match.arg(side)
  if (!(axis %in% names(observed)) || !(axis %in% names(df))) return(df)
  gcols <- setdiff(names(df), standard)
  key   <- intersect(c(gcols, by_extra), names(observed))
  ov    <- observed[is.finite(observed[[axis]]), , drop = FALSE]
  if (nrow(ov) == 0L) return(df)
  if (length(key)) {
    mkid <- function(d) do.call(paste, c(lapply(key, function(k) as.character(d[[k]])),
                                         list(sep = "\r")))
    oid <- mkid(ov)
    lo  <- tapply(ov[[axis]], oid, min)
    hi  <- tapply(ov[[axis]], oid, max)
    did <- mkid(df)
    dlo <- lo[did]; dhi <- hi[did]
  } else {
    dlo <- rep(min(ov[[axis]]), nrow(df))
    dhi <- rep(max(ov[[axis]]), nrow(df))
  }
  within <- switch(side,
    both  = df[[axis]] >= dlo & df[[axis]] <= dhi,
    upper = df[[axis]] <= dhi,   # cap the observed maximum; keep shorter values
    lower = df[[axis]] >= dlo)
  keep <- if (isTRUE(drop_unmatched)) !is.na(dlo) & within else is.na(dlo) | within
  df[keep, , drop = FALSE]
}

#' Plot a posterior LT_x curve
#'
#' Plots posterior median +/- 95% CrI of the duration to reach `target_surv`
#' across temperature. By default, returns a two-panel figure: a linear-time
#' panel (the absolute time to reach the target) alongside a `log10`-time
#' panel (the classical TDT view where the relationship is near-linear with
#' slope `-1/z`). Both panels share posterior draws.
#'
#' Grouped output from [derive_tdt_curve()] with `by = ...` is faceted
#' automatically so each moderator level gets its own TDT curve panel.
#'
#' Internal y-axis behaviour: if the 95% credible interval of the LT_x curve
#' extends above 48 hours (converted to `ltx$output_time_unit`), both panels'
#' y-axes are clamped to 48 hours so the readable part of the curve isn't
#' compressed by an extreme upper tail at cool temperatures. If the data
#' already stay below 48 hours, no limits are applied and `ggplot2` chooses
#' a data-driven range. To override it, append `+ ggplot2::coord_cartesian(ylim
#' = ...)` to a single-panel plot (`panels = "linear"` or `"log"`). For the
#' two-panel default, use patchwork's `&` so the limits reach both panels, with
#' a positive lower limit because one axis is logarithmic.
#'
#' @param ltx           Output of [derive_tdt_curve()].
#' @param panels        One of `"both"` (default), `"linear"`, or `"log"`.
#' @param colour        Line/ribbon colour. Default `"#146C7C"`.
#' @param observed      Optional standardised data tibble (from
#'                      [standardize_data()]). Only used, together with
#'                      `clip_to_observed`, to trim the temperature axis.
#' @param clip_to_observed Logical. If `TRUE` (the default) and `observed` is
#'                      supplied, each group's curve is drawn only over its
#'                      observed assay-temperature range (the temperature grid is
#'                      chosen by [derive_tdt_curve()], so this only trims a grid
#'                      drawn wider than the data). A no-op without `observed`.
#' @return A ggplot object (single panel) or patchwork composition (two panels).
#' @examples
#' \dontrun{
#' ltx <- derive_tdt_curve(wf, temp_grid = seq(29, 37, by = 0.5))
#' plot_tdt_curve(ltx)                  # two-panel default
#' plot_tdt_curve(ltx, panels = "log")  # classical TDT view only
#'
#' # Override the internal 48-h cap on one panel by appending a coord_cartesian:
#' plot_tdt_curve(ltx, panels = "linear") +
#'   ggplot2::coord_cartesian(ylim = c(0, 240))
#' # ... or on both panels with patchwork's `&` (the log axis needs a lower
#' # limit above 0):
#' plot_tdt_curve(ltx) & ggplot2::coord_cartesian(ylim = c(1, 240))
#' }
#' @export
plot_tdt_curve <- function(ltx,
                           panels = c("both", "linear", "log"),
                           colour = "#146C7C",
                           observed = NULL,
                           clip_to_observed = TRUE) {
  panels <- match.arg(panels)
  df <- ltx$summary
  # By default restrict each group's curve to its observed assay-temperature
  # range (the temperature grid is user-supplied to derive_tdt_curve(), so this
  # only trims a grid drawn wider than the data). A no-op without `observed`.
  if (isTRUE(clip_to_observed) && !is.null(observed)) {
    df <- tdt_clip_axis(df, observed,
                        c("target_surv", "temp", "duration_lower",
                          "duration_median", "duration_upper"), "temp")
  }

  target_raw <- unique(df$target_surv)
  target_mode <- ltx$target_mode %||% NA_character_
  is_relative <- identical(target_mode, "relative") ||
    (length(target_raw) == 1L && is.character(target_raw) &&
       target_raw == "(low+up)/2")
  target_lab <- if (is_relative) {
    "relative survival"
  } else {
    # Try the legacy numeric path first; fall back to the raw label if the
    # column carries an "p=X.XXX" string from resolve_target_surv().
    num <- ltx$target_prob %||% suppressWarnings(as.numeric(target_raw))
    if (!is.finite(num) && length(target_raw) == 1L &&
        is.character(target_raw) && grepl("^p=", target_raw)) {
      num <- suppressWarnings(as.numeric(sub("^p=", "", target_raw)))
    }
    if (length(num) == 1L && is.finite(num)) {
      paste0(round(100 * num), "% absolute survival")
    } else if (identical(target_mode, "absolute")) {
      "absolute survival"
    } else {
      paste0("survival = ", target_raw)
    }
  }
  unit_label <- if (is.null(ltx$output_time_unit)) "min" else ltx$output_time_unit

  # Convert the hard internal 48-hour ceiling to the ltx output unit. If the
  # unit can't be recognised, fall through with no cap (apply_cap stays
  # FALSE).
  hours_factor <- switch(
    tolower(as.character(unit_label)),
    "min" = 60, "minute" = 60, "minutes" = 60,
    "h" = 1, "hr" = 1, "hour" = 1, "hours" = 1,
    "s" = 3600, "sec" = 3600, "second" = 3600, "seconds" = 3600,
    "d" = 1/24, "day" = 1/24, "days" = 1/24,
    NA_real_
  )
  cap       <- if (is.na(hours_factor)) NA_real_ else 48 * hours_factor
  data_max  <- max(df$duration_upper, na.rm = TRUE)
  apply_cap <- is.finite(cap) && data_max > cap

  base <- ggplot2::ggplot(df,
                          ggplot2::aes(x = temp, y = duration_median)) +
    ggplot2::geom_ribbon(ggplot2::aes(ymin = duration_lower,
                                      ymax = duration_upper),
                         fill = colour, alpha = 0.2) +
    ggplot2::geom_line(colour = colour, linewidth = 1) +
    ggplot2::labs(x = "Assay temperature (\u00b0C)") +
    theme_tdt()

  p_lin <- base +
    ggplot2::labs(y = paste0("Time to ", target_lab, " (", unit_label, ")"))
  if (apply_cap) {
    p_lin <- p_lin + ggplot2::coord_cartesian(ylim = c(0, cap))
  }

  p_log <- base +
    ggplot2::scale_y_log10() +
    ggplot2::labs(y = paste0("log10 time to ", target_lab,
                             " (", unit_label, ")"))
  if (apply_cap) {
    p_log <- p_log + ggplot2::coord_cartesian(ylim = c(NA, cap))
  }

  standard_cols <- c("target_surv", "temp", "duration_lower",
                     "duration_median", "duration_upper")
  p_lin <- tdt_facet_by_group(p_lin, df, standard_cols)
  p_log <- tdt_facet_by_group(p_log, df, standard_cols)

  if (panels == "linear") return(p_lin)
  if (panels == "log")    return(p_log)
  if (requireNamespace("patchwork", quietly = TRUE)) {
    patchwork::wrap_plots(p_lin, p_log, ncol = 2)
  } else {
    list(linear = p_lin, log = p_log)
  }
}

#' Plot the TDT survival landscape as a heatmap
#'
#' Exposure-duration axis is linear by default; pass `log_time = TRUE` for the
#' classical log-time TDT presentation.
#'
#' A grouped fit (a moderator on `CTmax`/`z`, e.g. `oxygen` or `species`)
#' produces one heatmap panel per group, mirroring [plot_survival_curves()];
#' a single-condition fit returns the one ungrouped heatmap.
#'
#' @param landscape Output of [derive_tdt_landscape()].
#' @param observed  Optional standardised data tibble to overlay.
#' @param contours  Numeric vector of survival levels to draw contours at.
#'                  Default `c(0.25, 0.5, 0.75)`.
#' @param log_time  Logical. If `TRUE`, exposure-duration y-axis is log10.
#'                  Default `FALSE` (linear).
#' @param clip_to_observed Logical. If `TRUE` (the default) and `observed` is
#'                  supplied, each group's heatmap is restricted to the observed
#'                  temperature range and capped at the longest observed exposure
#'                  (shorter durations are still shown), so the surface is not
#'                  drawn beyond the data; grouped panels use free axes to avoid
#'                  plotting unsupported blank space. A no-op when `observed` is
#'                  not supplied. Set `FALSE` for the full grid.
#' @param facet_scales Facet scale behaviour for grouped landscapes. `"auto"`
#'                  (default) uses free axes when `clip_to_observed = TRUE` and
#'                  `observed` is supplied, otherwise fixed axes. Use `"fixed"`
#'                  to force identical axes across groups, or any `facet_wrap()`
#'                  scale option (`"free"`, `"free_x"`, `"free_y"`).
#' @return A ggplot object.
#' @examples
#' \dontrun{
#' lsp <- derive_tdt_landscape(wf)
#' plot_tdt_landscape(lsp, observed = wf$data)
#' }
#' @export
plot_tdt_landscape <- function(landscape, observed = NULL,
                               contours = c(0.25, 0.5, 0.75),
                               log_time = FALSE,
                               clip_to_observed = TRUE,
                               facet_scales = c("auto", "fixed", "free",
                                                "free_x", "free_y")) {
  facet_scales <- match.arg(facet_scales)
  df  <- landscape$summary
  std <- c("temp", "duration", "survival_lower", "survival_median", "survival_upper")
  # By default restrict each group's heatmap to the observed temperature x
  # duration extent (per-group bounding box; the grid is continuous, so this
  # clips to the observed range). A no-op when `observed` is absent.
  if (isTRUE(clip_to_observed) && !is.null(observed)) {
    df <- tdt_clip_axis(df, observed, std, "temp")
    df <- tdt_clip_axis(df, observed, std, "duration", side = "upper")
  }
  p <- ggplot2::ggplot(df, ggplot2::aes(x = temp, y = duration,
                                        fill = survival_median)) +
    ggplot2::geom_tile() +
    ggplot2::geom_contour(data = df,
                          ggplot2::aes(x = temp, y = duration,
                                       z = survival_median),
                          inherit.aes = FALSE,
                          breaks = contours,
                          colour = "white", alpha = 0.7) +
    ggplot2::scale_fill_viridis_c(limits = c(0, 1), option = "inferno") +
    ggplot2::labs(x = "Temperature (\u00b0C)",
                  y = "Exposure duration",
                  fill = "Survival") +
    theme_tdt()

  if (isTRUE(log_time)) p <- p + ggplot2::scale_y_log10()

  if (!is.null(observed)) {
    observed <- tdt_observed_as_recorded(observed)   # landscape fill as recorded
    p <- p + ggplot2::geom_point(
      data = observed,
      ggplot2::aes(x = temp, y = duration, fill = survival),
      inherit.aes = FALSE, shape = 21, colour = "white",
      size = 2, stroke = 0.2
    )
  }
  # Grouped fit: one heatmap panel per moderator level (as for
  # plot_survival_curves); a no-op when the summary carries no moderator column.
  if (identical(facet_scales, "auto")) {
    facet_scales <- if (isTRUE(clip_to_observed) && !is.null(observed)) {
      "free"
    } else {
      "fixed"
    }
  }
  tdt_facet_by_group(p, df, c("temp", "duration",
                              "survival_lower", "survival_median", "survival_upper"),
                     scales = facet_scales)
}

#' Plot a posterior temperature density (e.g. CTmax or T_crit)
#'
#' Density plot of a per-draw temperature posterior, with a horizontal segment
#' marking the 95% CrI and a point at the median. Useful for visualising
#' [derive_temperature_for_duration()] output.
#'
#' @param temp_post  Output of [derive_temperature_for_duration()]: a list with
#'                   `$draws` (carrying a per-draw `temp` column) and `$summary`.
#' @param truth      Optional numeric scalar: a true value to mark with a
#'                   dashed vertical line.
#' @param x_label    X-axis label. Default `"Temperature (°C)"`.
#' @return A ggplot object.
#' @examples
#' \dontrun{
#' tp <- derive_temperature_for_duration(wf, exposure_duration = 60,
#'                                        temp_grid = seq(36, 44, by = 0.1))
#' plot_temperature_density(tp)
#' }
#' @export
plot_temperature_density <- function(temp_post, truth = NULL,
                                     x_label = "Temperature (\u00b0C)") {
  draws <- temp_post$draws |> dplyr::filter(is.finite(temp))
  d     <- stats::density(draws$temp, na.rm = TRUE)
  y_ci  <- -max(d$y, na.rm = TRUE) * 0.1

  p <- ggplot2::ggplot(draws, ggplot2::aes(x = temp)) +
    ggplot2::geom_density(fill = "#146C7C", alpha = 0.35,
                          colour = "#0E4A55", linewidth = 0.4) +
    ggplot2::geom_segment(
      data = temp_post$summary,
      ggplot2::aes(x = temp_lower, xend = temp_upper,
                   y = y_ci, yend = y_ci),
      linewidth = 1, colour = "#2F2F2F", inherit.aes = FALSE
    ) +
    ggplot2::geom_point(
      data = temp_post$summary,
      ggplot2::aes(x = temp_median, y = y_ci),
      size = 2.5, colour = "#2F2F2F", inherit.aes = FALSE
    ) +
    ggplot2::labs(x = x_label, y = "Posterior density") +
    theme_tdt()

  if (!is.null(truth)) {
    p <- p + ggplot2::geom_vline(xintercept = truth,
                                  linetype = "dashed", colour = "grey40")
  }
  # Grouped fit: facet so each group's posterior gets its own density, not a pool.
  tdt_facet_by_group(p, draws, c(".draw", "temp"))
}

#' Plot the three reference temperature scenarios
#'
#' One panel per scenario stacked vertically, with optional horizontal dashed
#' line at the damage threshold `T_c`.
#'
#' @param scens Named list from [make_temperature_scenarios()].
#' @param T_c   Optional damage threshold to mark.
#' @return A ggplot object.
#' @examples
#' scens <- make_temperature_scenarios()
#' plot_temperature_scenarios(scens, T_c = 24)
#' @export
plot_temperature_scenarios <- function(scens, T_c = NULL) {
  df <- dplyr::bind_rows(
    lapply(names(scens), function(nm) {
      x <- scens[[nm]]; x$scenario <- nm; x
    })
  )
  scen_levels <- intersect(
    c("flat", "single_spike", "multi_spike", "diurnal"),
    unique(df$scenario)
  )
  if (length(scen_levels) == 0L) scen_levels <- unique(df$scenario)
  df$scenario <- factor(df$scenario, levels = scen_levels)

  p <- ggplot2::ggplot(df, ggplot2::aes(x = time, y = temp)) +
    ggplot2::geom_line(linewidth = 0.7, colour = "#146C7C") +
    ggplot2::facet_wrap(~ scenario, ncol = 1, scales = "free_x") +
    ggplot2::labs(x = "Time (hours)", y = "Temperature (\u00b0C)") +
    theme_tdt()

  if (!is.null(T_c)) {
    p <- p + ggplot2::geom_hline(yintercept = T_c,
                                  linetype = "dashed",
                                  colour = "grey50")
  }
  p
}

#' Plot HI and survival trajectories from `predict_heat_injury()`
#'
#' Two stacked panels: cumulative heat injury (%) on top, predicted survival
#' fraction on the bottom, both with 95% credible bands.
#'
#' @param hi             Output of [predict_heat_injury()].
#' @param lt50_threshold Numeric. Horizontal dashed line on the HI panel
#'                       marking the LT50 dose threshold. Default 100.
#' @return A ggplot object (combined via `patchwork`).
#' @examples
#' \dontrun{
#' hi <- predict_heat_injury(scens$single_spike, wf)
#' plot_heat_injury(hi)
#' }
#' @export
plot_heat_injury <- function(hi, lt50_threshold = 100) {
  df <- hi$summary

  p_hi <- ggplot2::ggplot(df, ggplot2::aes(x = time, y = hi_median)) +
    ggplot2::geom_ribbon(ggplot2::aes(ymin = hi_lower, ymax = hi_upper),
                         fill = "#C76D37", alpha = 0.2) +
    ggplot2::geom_line(colour = "#C76D37", linewidth = 0.9) +
    ggplot2::geom_hline(yintercept = lt50_threshold,
                         linetype = "dashed", colour = "grey40") +
    ggplot2::labs(x = NULL, y = "Cumulative HI (%)") +
    theme_tdt()

  p_surv <- ggplot2::ggplot(df, ggplot2::aes(x = time, y = surv_median)) +
    ggplot2::geom_ribbon(ggplot2::aes(ymin = surv_lower, ymax = surv_upper),
                         fill = "#146C7C", alpha = 0.2) +
    ggplot2::geom_line(colour = "#146C7C", linewidth = 0.9) +
    ggplot2::coord_cartesian(ylim = c(0, 1)) +
    ggplot2::labs(x = "Time (hours)", y = "Predicted survival") +
    theme_tdt()

  # Grouped fit (per-group trajectories): facet so groups are not threaded together.
  hi_std <- c("time", "temp", "hi_median", "hi_lower", "hi_upper",
              "surv_median", "surv_lower", "surv_upper",
              "mort_median", "mort_lower", "mort_upper")
  p_hi   <- tdt_facet_by_group(p_hi,   df, hi_std)
  p_surv <- tdt_facet_by_group(p_surv, df, hi_std)

  if (requireNamespace("patchwork", quietly = TRUE)) {
    patchwork::wrap_plots(p_hi, p_surv, ncol = 1)
  } else {
    list(hi = p_hi, survival = p_surv)
  }
}

#' Plot a Sharpe-Schoolfield repair TPC
#'
#' @param temp_grid   Numeric vector of temperatures (degC) to evaluate.
#' @param repair_pars Named list of Sharpe-Schoolfield parameters
#'                    (`TA, TAL, TAH, TL, TH, TREF, r_ref`).
#' @return A ggplot object.
#' @examples
#' rp <- list(TA = 14065, TAL = 50000, TAH = 120000,
#'            TL = 10.5 + 273.15, TH = 22.5 + 273.15,
#'            TREF = 17 + 273.15, r_ref = 0.01)
#' plot_repair_rate(seq(5, 30, length.out = 200), rp)
#' @export
plot_repair_rate <- function(temp_grid, repair_pars) {
  rates <- repair_rate_schoolfield(
    temp_celsius = temp_grid,
    TA = repair_pars$TA, TAL = repair_pars$TAL,
    TAH = repair_pars$TAH, TL = repair_pars$TL,
    TH = repair_pars$TH, TREF = repair_pars$TREF,
    r_ref = repair_pars$r_ref
  )
  df <- tibble::tibble(temp = temp_grid, repair_rate = rates)

  ggplot2::ggplot(df, ggplot2::aes(x = temp, y = repair_rate)) +
    ggplot2::geom_line(linewidth = 1, colour = "#4DAC26") +
    ggplot2::labs(x = "Temperature (\u00b0C)",
                  y = "Repair rate (per hour)") +
    theme_tdt()
}

Try the bayesTLS package in your browser

Any scripts or data that you put into this service are public.

bayesTLS documentation built on Nov. 29, 2026, 1:06 a.m.