R/plot_profile.R

Defines functions .opt_label .grid_max .free_corner .with_limit .smooth_curve

# ============================================================================
# Drawing code for plot_loglik() and plot_tic(), and the plot() method for
# their results (class "wnpmle_profile"), so that a figure can be redrawn
# without refitting.
#
# Two layouts:
#   "joint" (default): as Figure 2 of Bellach and Kosorok (2026): logarithmic r
#             to the left and Box-Cox rho to the right of zero, relative
#             log-likelihood (-Delta AIC / 2 dashed with open circles,
#             -Delta TIC / 2 solid with filled circles), natural splines through
#             the grid points extended to zero (rho -> 0 is log r = 1, r -> 0 is
#             Box-Cox rho = 1), dotted line at -1.
#   "panels": logarithmic and Box-Cox side by side with a common y-axis.
# ============================================================================

# natural spline through the finite grid points (straight lines if < 4 points)
.smooth_curve <- function(x, y, n = 200) {
  ok <- is.finite(x) & is.finite(y)
  x <- x[ok]; y <- y[ok]
  o <- order(x); x <- x[o]; y <- y[o]
  if (length(x) >= 4 && !anyDuplicated(x))
    stats::spline(x, y, n = n, method = "natural")
  else list(x = x, y = y)
}

# add the limit at zero: value of the other family at parameter 1, if computed
.with_limit <- function(grid, y, other_grid, other_y) {
  k <- which(abs(other_grid - 1) < 1e-8)
  if (length(k) == 1 && is.finite(other_y[k]) && !any(abs(grid) < 1e-8))
    list(x = c(0, grid), y = c(other_y[k], y))
  else list(x = grid, y = y)
}

# corner of a plot region with the fewest curve points, and how many there are
.free_corner <- function(x, y, xlim, ylim) {
  ok <- is.finite(x) & is.finite(y)
  u <- (x[ok] - xlim[1]) / diff(xlim)
  v <- (y[ok] - ylim[1]) / diff(ylim)
  cnt <- c(topleft     = sum(u < 0.5 & v > 0.6),
           topright    = sum(u > 0.5 & v > 0.6),
           bottomleft  = sum(u < 0.5 & v < 0.4),
           bottomright = sum(u > 0.5 & v < 0.4))
  k <- which.min(cnt)
  list(corner = names(cnt)[k], count = cnt[[k]])
}

# x-value and y-value of the grid point with the largest y (NULL if none)
.grid_max <- function(x, y) {
  if (!any(is.finite(y))) return(NULL)
  k <- which.max(y)
  c(x[k], y[k])
}

# label for the optimum, e.g. "r-hat = 1.75"
.opt_label <- function(fam, value) {
  v <- format(round(value, 2))
  if (fam == 1) bquote(hat(r) == .(v)) else bquote(hat(rho) == .(v))
}

.draw_profile <- function(r_grid, rho_grid, ll_log, ll_BC,
                          tic_log = NULL, tic_BC = NULL,
                          layout = c("panels", "joint"), relative = TRUE,
                          mark_points = TRUE, legend = TRUE, main_label = "AIC") {
  layout  <- match.arg(layout)
  has_tic <- !is.null(tic_log)

  # main curve: TIC-corrected log-likelihood if available, else log-likelihood
  m_log <- if (has_tic) tic_log else ll_log
  m_BC  <- if (has_tic) tic_BC  else ll_BC
  s_log <- ll_log; s_BC <- ll_BC
  if (relative) {                       # each criterion relative to its own optimum
    mx <- max(c(m_log, m_BC), na.rm = TRUE); m_log <- m_log - mx; m_BC <- m_BC - mx
    mx <- max(c(s_log, s_BC), na.rm = TRUE); s_log <- s_log - mx; s_BC <- s_BC - mx
  }
  main_log <- .with_limit(r_grid,   m_log, rho_grid, m_BC)
  main_BC  <- .with_limit(rho_grid, m_BC,  r_grid,   m_log)
  sec_log  <- if (has_tic) .with_limit(r_grid,   s_log, rho_grid, s_BC)
  sec_BC   <- if (has_tic) .with_limit(rho_grid, s_BC,  r_grid,   s_log)

  col_main <- "black"; col_sec <- "grey60"; col_ref <- "grey70"
  ylim <- range(c(main_log$y, main_BC$y, sec_log$y, sec_BC$y, if (relative) c(0, -1)),
                finite = TRUE)
  ylim <- ylim + c(-0.04, 0.10) * diff(ylim)
  ylab <- if (relative) "Log-likelihood (relative)" else "Log-likelihood"
  leg_txt <- c(if (has_tic) c("TIC", "AIC") else main_label, "Optimum")
  leg_col <- c(if (has_tic) c(col_main, col_sec) else col_main, "black")
  leg_lwd <- c(if (has_tic) c(2, 1.5) else 2, NA)
  leg_pch <- c(if (has_tic) c(NA, NA) else NA, 17)
  leg_lty <- c(if (has_tic) c(1, 1) else 1, NA)
  i_r1   <- which(abs(r_grid   - 1) < 1e-8)
  i_rho1 <- which(abs(rho_grid - 1) < 1e-8)
  y_r1   <- if (length(i_r1)   == 1) m_log[i_r1]  else NA
  y_rho1 <- if (length(i_rho1) == 1) m_BC[i_rho1] else NA
  # one marker for the overall optimum over both families (grid points only)
  o_log <- .grid_max(r_grid, m_log); o_BC <- .grid_max(rho_grid, m_BC)
  best_fam <- if (!is.null(o_log) && (is.null(o_BC) || o_log[2] >= o_BC[2])) 1 else
              if (!is.null(o_BC)) 2 else 0
  y_opt <- if (best_fam == 1) o_log[2] else if (best_fam == 2) o_BC[2] else NA

  # thin horizontal reference lines: optimum, -1 rule (relative scale),
  # and the levels of r = 1 and rho = 1
  ref_lines <- function() {
    if (is.finite(y_opt)) abline(h = y_opt, lty = 3, lwd = 0.7, col = col_ref)
    if (relative) abline(h = -1, lty = 3, lwd = 0.9, col = "grey45")
    if (mark_points) {
      if (is.finite(y_r1))   abline(h = y_r1,   lty = 3, lwd = 0.7, col = col_ref)
      if (is.finite(y_rho1)) abline(h = y_rho1, lty = 3, lwd = 0.7, col = col_ref)
    }
  }
  draw_legend <- function(corner)
    graphics::legend(corner, inset = 0.02, bty = "n", cex = 0.8, bg = "white",
                     legend = leg_txt, col = leg_col, lwd = leg_lwd,
                     lty = leg_lty, pch = leg_pch, seg.len = 2.5)

  if (layout == "panels") {
    oldpar <- par(mfrow = c(1, 2), oma = c(0, 4.2, 0, 0.8), mgp = c(2.4, 0.7, 0),
                  tcl = -0.3)
    on.exit(par(oldpar), add = TRUE)
    fam <- list(
      list(main = main_log, sec = sec_log, title = "Logarithmic transformation",
           xlab = "r", x1 = 1, y1 = y_r1, pch1 = 16, lab1 = "r = 1",
           opt = if (best_fam == 1) o_log),
      list(main = main_BC, sec = sec_BC, title = "Box-Cox transformation",
           xlab = expression(rho), x1 = 1, y1 = y_rho1, pch1 = 1,
           lab1 = expression(rho == 1), opt = if (best_fam == 2) o_BC))
    # legend: the emptiest corner of either panel
    for (j in 1:2) {
      f  <- fam[[j]]
      fam[[j]]$xlim <- c(0, max(f$main$x, na.rm = TRUE))
      s1 <- .smooth_curve(f$main$x, f$main$y)
      s2 <- if (has_tic) .smooth_curve(f$sec$x, f$sec$y)
      fc <- .free_corner(c(s1$x, s2$x), c(s1$y, s2$y), fam[[j]]$xlim, ylim)
      fam[[j]]$corner <- fc$corner; fam[[j]]$crowd <- fc$count
    }
    j_leg <- if (fam[[2]]$crowd < fam[[1]]$crowd) 2 else 1
    for (j in 1:2) {
      f <- fam[[j]]
      par(mar = if (j == 1) c(4, 0, 2.5, 0.4) else c(4, 0.4, 2.5, 0))
      plot(NA, xlim = f$xlim, ylim = ylim, xlab = f$xlab, ylab = "", yaxt = "n",
           main = f$title, font.main = 1, cex.main = 1, xaxs = "i")
      if (j == 1) {                      # y-axis in the outer margin, left panel only
        axis(2, outer = TRUE)
        mtext(ylab, side = 2, line = 2.4, outer = TRUE)
      }
      ref_lines()
      if (has_tic) lines(.smooth_curve(f$sec$x, f$sec$y), col = col_sec, lwd = 1.5)
      lines(.smooth_curve(f$main$x, f$main$y), col = col_main, lwd = 2)
      if (mark_points && is.finite(f$y1)) {
        points(f$x1, f$y1, pch = f$pch1, cex = if (f$pch1 == 1) 1.4 else 1)
        text(f$x1, f$y1, labels = f$lab1, pos = if (j == 1) 3 else 4,
             offset = 0.8, xpd = NA)
      }
      if (!is.null(f$opt)) {
        points(f$opt[1], f$opt[2], pch = 17, cex = 1.2)
        text(f$opt[1], f$opt[2], labels = .opt_label(j, f$opt[1]), pos = 3,
             offset = 0.7, xpd = NA)
      }
      if (legend && j == j_leg) draw_legend(f$corner)
    }
    return(invisible(NULL))
  }

  # ---- joint layout: as Figure 2 of Bellach and Kosorok (2026) ----
  # logarithmic r to the left (pmax -> 0), Box-Cox rho to the right (0 -> pmax);
  # AIC dashed with open circles, TIC solid with filled circles; points at
  # r = 1 (= rho = 0) and rho = 1 (= r = 0); dotted line at -1
  pmax <- max(c(r_grid, rho_grid), na.rm = TRUE)
  yA_log <- if (has_tic) s_log else m_log;  yA_BC <- if (has_tic) s_BC else m_BC
  yT_log <- if (has_tic) m_log else NULL;   yT_BC <- if (has_tic) m_BC else NULL
  k_po <- i_r1; k_gl <- i_rho1
  ylo  <- min(-6, floor(min(c(yA_log, yA_BC, yT_log, yT_BC), na.rm = TRUE)))
  xlim <- c(-(pmax + 0.4), pmax + 0.2)
  plot(NA, xlim = xlim, ylim = c(ylo, 0), xaxt = "n",
       xlab = "Transformation parameter", ylab = "Log-likelihood (relative)")
  step <- .axis_step(pmax)
  tk   <- seq(-floor(pmax / step + 1e-8) * step, floor(pmax / step + 1e-8) * step, by = step)
  axis(1, at = tk, labels = abs(round(tk, 2)))
  mtext("Logarithmic, r", side = 3, line = 0.3, at = -pmax / 2, cex = 1)
  mtext(expression("Box-Cox, " * rho), side = 3, line = 0.3, at = pmax / 2, cex = 1)
  abline(v = 0, lty = 3, col = "grey70")
  abline(h = -1, lty = 3, col = "grey50")
  curve2 <- function(xg, y, y0, sgn, lty) {      # natural spline, extended to 0
    xx <- c(sgn * xg, if (is.finite(y0)) 0)
    yy <- c(y, if (is.finite(y0)) y0)
    ok <- is.finite(xx) & is.finite(yy); xx <- xx[ok]; yy <- yy[ok]
    o  <- order(xx); xx <- xx[o]; yy <- yy[o]
    if (length(xx) >= 4 && !anyDuplicated(xx))
      lines(stats::spline(xx, yy, n = 300, method = "natural"), lwd = 2, lty = lty)
    else lines(xx, yy, lwd = 2, lty = lty)
  }
  at1 <- function(y, k) if (length(k) == 1) y[k] else NA
  curve2(r_grid,   yA_log, at1(yA_BC, k_gl), -1, 2)
  curve2(rho_grid, yA_BC,  at1(yA_log, k_po), 1, 2)
  if (has_tic) {
    curve2(r_grid,   yT_log, at1(yT_BC, k_gl), -1, 1)
    curve2(rho_grid, yT_BC,  at1(yT_log, k_po), 1, 1)
  }
  if (mark_points) {
    pts <- function(xp, yA, yT) {                 # hollow = AIC, filled = TIC
      if (is.finite(yA)) points(xp, yA, pch = 1,  cex = 1.2)
      if (has_tic && is.finite(yT)) points(xp, yT, pch = 19, cex = 1.2)
    }
    po_A <- at1(yA_log, k_po); po_T <- if (has_tic) at1(yT_log, k_po) else NA
    gl_A <- at1(yA_BC,  k_gl); gl_T <- if (has_tic) at1(yT_BC,  k_gl) else NA
    pts(-1, po_A, po_T); pts(0, gl_A, gl_T); pts(0, po_A, po_T); pts(1, gl_A, gl_T)
    lab_y <- function(yT, yA) if (has_tic && is.finite(yT)) yT else yA
    if (is.finite(po_A)) {
      text(-1, lab_y(po_T, po_A), expression(r == 1), pos = 2, offset = 0.5, cex = 0.85)
      text( 0, po_A, expression(rho == 0), pos = 4, offset = 0.9, cex = 0.85)
    }
    if (is.finite(gl_A)) {
      text( 0, lab_y(gl_T, gl_A), expression(r == 0), pos = 2, offset = 0.6, cex = 0.85)
      text( 1, lab_y(gl_T, gl_A), expression(rho == 1), pos = 4, offset = 0.6, cex = 0.85)
    }
  }
  if (legend) {
    if (has_tic)
      graphics::legend("bottomleft", c("AIC", "TIC"), lty = c(2, 1), pch = c(1, 19),
                       lwd = 2, seg.len = 4, bty = "n", inset = 0.01)
    else
      graphics::legend("bottomleft", main_label, lty = 2, pch = 1,
                       lwd = 2, seg.len = 4, bty = "n", inset = 0.01)
  }
  invisible(NULL)
}

#' Plot the results of plot_loglik() or plot_tic() again
#'
#' \code{\link{plot_loglik}} and \code{\link{plot_tic}} return their results
#' (invisibly) as an object of class \code{"wnpmle_profile"}. \code{plot()}
#' redraws the figure from these results without refitting any model, e.g.
#' with a different layout or into a PDF file.
#'
#' @param x An object of class \code{"wnpmle_profile"}, returned by
#'   \code{\link{plot_loglik}} or \code{\link{plot_tic}}.
#' @param layout \code{"joint"} (default) or \code{"panels"}; see
#'   \code{\link{plot_loglik}}.
#' @param relative Logical; show each criterion relative to its optimum
#'   (\eqn{-\Delta\mathrm{AIC}/2}, \eqn{-\Delta\mathrm{TIC}/2}; default
#'   \code{TRUE}), or on the log-likelihood scale.
#' @param show_loglik Logical; for results of \code{plot_tic()}, also show
#'   AIC (default \code{TRUE}).
#' @param mark_points,legend,file As in \code{\link{plot_loglik}}.
#' @param width,height Size of the PDF in inches; default 3.6 x 2.8 (with
#'   pointsize 9, as in Bellach and Kosorok, 2026) for \code{layout = "joint"}
#'   and 7 x 4.5 for \code{"panels"}.
#' @param ... Ignored.
#' @return \code{x}, invisibly.
#' @examples
#' \donttest{
#' bdata <- bladder_prep()
#' res <- plot_loglik(Surv(time, status) ~ treat + num + size, data = bdata,
#'                    id = "id", rho_grid = seq(0.2, 1.2, by = 0.2),
#'                    r_grid = seq(0.2, 1.2, by = 0.2))
#' plot(res, layout = "panels")        # redrawn without refitting
#' }
#' @export
plot.wnpmle_profile <- function(x, layout = NULL, relative = TRUE,
                                show_loglik = TRUE, mark_points = TRUE,
                                legend = TRUE, file = NULL, width = NULL,
                                height = NULL, ...) {
  if (is.null(layout)) layout <- "joint"
  if (is.null(width))  width  <- if (layout == "panels") 7 else 3.6
  if (is.null(height)) height <- if (layout == "panels") 4.5 else 2.8
  lg <- x[x$model == "log", ];    bc <- x[x$model == "boxcox", ]
  has_tic <- "penalty" %in% names(x) && show_loglik
  corr <- function(d) d$loglik - (d$penalty - d$p)       # = p - TIC / 2
  if (!is.null(file)) {
    grDevices::pdf(file, width = width, height = height, useDingbats = FALSE,
                   pointsize = if (layout == "joint") 9 else 12)
    on.exit(grDevices::dev.off(), add = TRUE)
  }
  if (layout == "joint") {                       # margins as in the paper figure
    op <- par(mar = c(3.2, 3.2, 1.6, 0.6), mgp = c(2, 0.6, 0))
    on.exit(par(op), add = TRUE)
  }
  if ("penalty" %in% names(x)) {
    .draw_profile(lg$param, bc$param,
                  ll_log  = if (has_tic) lg$loglik else corr(lg),
                  ll_BC   = if (has_tic) bc$loglik else corr(bc),
                  tic_log = if (has_tic) corr(lg),
                  tic_BC  = if (has_tic) corr(bc),
                  layout = layout, relative = relative,
                  mark_points = mark_points, legend = legend, main_label = "TIC")
  } else {
    .draw_profile(lg$param, bc$param, lg$loglik, bc$loglik,
                  layout = layout, relative = relative,
                  mark_points = mark_points, legend = legend)
  }
  if (!is.null(file)) cat("Plot saved to", file, "\n")
  invisible(x)
}

# attach class and attributes to the results of plot_loglik() / plot_tic()
.as_profile <- function(df, layout, type) {
  attr(df, "layout") <- layout
  attr(df, "type")   <- type
  class(df) <- c("wnpmle_profile", "data.frame")
  df
}

Try the wnpmle package in your browser

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

wnpmle documentation built on Dec. 1, 2026, 9:06 a.m.