Shinylive Apps for Statistical Computation
    • All Apps

    • Inverse CDF Method for Generating Random Numbers
    • Newton-Raphson for the Cauchy Location Likelihood
    • Safeguarded Newton-Raphson for Logistic Regression
    • Gradient-Based Methods for Minimizing Test Functions
    • Gradient-Based Methods for Fitting a Gaussian Neural Network
    • Gradient-Based Methods for Fitting a Poisson Neural Network
    • Nelder–Mead Method for Derivative-Free Minimization
    • EM Algorithm for a Normal Mixture
    • EM Algorithm for a Bivariate Normal Mixture
    • Conjugate Updating for Bayesian Posteriors
    • Quadrature and Laplace Approximation for the Marginal Likelihood of a Normal Mean
    • Midpoint, Laplace and Laplace-Adapted Midpoint Rules for the Marginal Likelihood of Normal Data
    • Rejection Sampling with a Laplace Envelope for the Normal Distribution
    • Rejection Sampling with a Cauchy Envelope for the Gamma Distribution
    • Adaptive Rejection Sampling for the Truncated Normal Distribution
    • Adaptive Rejection Sampling on log X for the Truncated Gamma Distribution
    • Importance Sampling for a Bimodal Distribution (Failure Example)
    • Importance Sampling with a Normal Proposal for Student-t Probabilities
    • Gibbs Sampling for the Cauchy Model with Unknown Location and Scale
    • MCMC Simulators by Chi Feng (external)

Adaptive Rejection Sampling on log X for the Truncated Gamma Distribution

Author

Longhai Li

Published

November 24, 2026

#| '!! shinylive warning !!': |
#|   shinylive does not work in self-contained HTML documents.
#|   Please set `embed-resources: false` in your metadata.
#| standalone: true
#| viewerHeight: 880
library(shiny)

### renderPlot replacement: Safari 27 (WebKit) cannot hold the call stack of
### shiny::renderPlot in webR ("Maximum call stack size exceeded"), so draw with
### renderImage instead, which nests about 45 fewer R calls
renderPlot <- function(expr, width = "auto", height = "auto", res = 72, ...,
                       env = parent.frame(), quoted = FALSE) {
    func <- shiny::exprToFunction(expr, env, quoted)
    shiny::renderImage({
        info <- shiny::getCurrentOutputInfo()
        w  <- if (is.numeric(width))  width  else info$width()
        h  <- if (is.numeric(height)) height else info$height()
        shiny::req(w > 0, h > 0)
        pr <- shiny::getDefaultReactiveDomain()$clientData$pixelratio
        if (is.null(pr)) pr <- 1
        f   <- tempfile(fileext = ".png")
        dev <- shiny:::startPNG(f, w * pr, h * pr, res = res * pr)
        on.exit(grDevices::dev.off(dev), add = TRUE)
        grDevices::dev.control(displaylist = "enable")
        v <- withVisible(func())
        if (v$visible) print(v$value)
        list(src = f, contentType = "image/png", width = w, height = h,
             coordmap = shiny:::getCoordmap(v$value, w * pr, h * pr, res * pr))
    }, deleteFile = TRUE)
}

### -------------------------------------------------------------------------
### Target. Y = log X with X ~ Gamma(alpha, 1), optionally truncated to
### l < X < u, i.e. a < Y < b with a = log l, b = log u. The density of Y is
### f_X(e^y) e^y, so up to a constant
###     h(y) = log f_Y(y) = alpha * y - exp(y),   h''(y) = -exp(y) < 0,
### which is concave for EVERY alpha > 0, while log f_X is convex when alpha < 1.
### -------------------------------------------------------------------------
U_MAX <- 20                                   # slider value of u that means "no upper limit"

make_target <- function(alpha, l, u) {
    a <- if (l > 0) log(l) else -Inf
    b <- if (u < U_MAX) log(u) else Inf
    list(alpha = alpha, l = l, u = if (is.finite(b)) u else Inf, a = a, b = b,
         h      = function(y) alpha * y - exp(y),
         hprime = function(y) alpha - exp(y),
         mode   = log(alpha))
}

### tangent-line hull on (a, b); a = -Inf and/or b = Inf allowed
build_hull <- function(ys, tg) {
    ys <- sort(unique(ys))
    hy <- tg$h(ys); hpy <- tg$hprime(ys)
    k <- length(ys)
    z <- c(tg$a, numeric(max(k - 1, 0)), tg$b)
    if (k > 1) for (i in 1:(k - 1)) {
        z[i + 1] <- (hy[i + 1] - hy[i] - ys[i + 1] * hpy[i + 1] + ys[i] * hpy[i]) /
            (hpy[i] - hpy[i + 1])
    }
    list(x = ys, hx = hy, hp = hpy, z = z)
}

### three starting points inside (a, b). An infinite end needs a tangent that
### points downhill towards it -- h' > 0 at the leftmost point when a = -Inf,
### h' < 0 at the rightmost when b = Inf -- so that the end piece has finite area;
### a finite end needs nothing, since every piece on a bounded interval is integrable
init_hull <- function(tg) {
    a <- tg$a; b <- tg$b; m <- tg$mode
    ys <- if (is.finite(a) && is.finite(b)) a + (b - a) * c(0.25, 0.5, 0.75)
          else if (is.finite(a)) { R <- max(a, m) + 1; a + (R - a) * c(0.1, 0.5, 1) }
          else if (is.finite(b)) { L <- min(b, m) - 1; b - (b - L) * c(0.1, 0.5, 1) }
          else m + c(-1, 0, 1)
    build_hull(ys, tg)
}

### value of tangent piece j at the two ends of its interval; at an infinite
### end it is -Inf, because the slope there always points downhill (see init_hull)
piece_ends <- function(hull, j) {
    a <- hull$hx[j]; b <- hull$hp[j]; xj <- hull$x[j]
    lo <- hull$z[j]; hi <- hull$z[j + 1]
    c(if (is.infinite(lo)) -Inf else a + b * (lo - xj),
      if (is.infinite(hi)) -Inf else a + b * (hi - xj))
}

### log of the area under exp(tangent piece j), computed in log space
log_piece_area <- function(hull, j) {
    b <- hull$hp[j]; v <- piece_ends(hull, j)
    if (abs(b) < 1e-10) return(v[1] + log(hull$z[j + 1] - hull$z[j]))  # flat piece: bounded
    m <- max(v); d <- min(v)
    m + log1p(-exp(d - m)) - log(abs(b))
}

### one draw from the normalized envelope: choose a piece in proportion to its
### area, then invert that piece's exponential CDF, on the log scale
sample_hull <- function(hull) {
    k <- length(hull$x)
    log_areas <- vapply(seq_len(k), function(j) log_piece_area(hull, j), numeric(1))
    mA <- max(log_areas); areas <- exp(log_areas - mA)
    logA <- mA + log(sum(areas))
    j <- sample.int(k, 1, prob = areas)
    a <- hull$hx[j]; b <- hull$hp[j]; xj <- hull$x[j]
    lo <- hull$z[j]; hi <- hull$z[j + 1]
    U <- runif(1)
    if (abs(b) < 1e-10) {
        y <- lo + U * (hi - lo); logg <- a
    } else {
        v <- piece_ends(hull, j); m <- max(v)
        val_y <- m + log((1 - U) * exp(v[1] - m) + U * exp(v[2] - m))
        y <- xj + (val_y - a) / b; logg <- val_y
    }
    list(y = y, logg = logg, logA = logA)
}

### piecewise-linear hull value (log scale) at a vector of y's
hull_val <- function(hull, ygrid) {
    j <- findInterval(ygrid, hull$z, rightmost.closed = TRUE)
    j <- pmax(1, pmin(j, length(hull$x)))
    hull$hx[j] + hull$hp[j] * (ygrid - hull$x[j])
}

### log P(l < X < u) for X ~ Gamma(alpha, 1), from whichever tail keeps precision
log_ptrunc <- function(l, u, alpha) {
    if (l > qgamma(0.5, alpha)) {
        p1 <- pgamma(l, alpha, lower.tail = FALSE, log.p = TRUE)
        p2 <- pgamma(u, alpha, lower.tail = FALSE, log.p = TRUE)
    } else {
        p1 <- pgamma(u, alpha, log.p = TRUE)
        p2 <- pgamma(l, alpha, log.p = TRUE)
    }
    p1 + log1p(-exp(p2 - p1))
}

### normalized (truncated) densities of Y = log X and of X, zero outside the interval
dlogGamma_tr <- function(y, tg) {
    d <- exp(tg$alpha * y - exp(y) - lgamma(tg$alpha) - log_ptrunc(tg$l, tg$u, tg$alpha))
    ifelse(y >= tg$a & y <= tg$b, d, 0)
}
dGamma_tr <- function(x, tg) {
    d <- exp(dgamma(x, tg$alpha, log = TRUE) - log_ptrunc(tg$l, tg$u, tg$alpha))
    ifelse(x >= tg$l & x <= tg$u, d, 0)
}

### exact means: E(X) = alpha P_{alpha+1}(l, u) / P_alpha(l, u); E(log X) by integration
true_means <- function(tg) {
    lp <- log_ptrunc(tg$l, tg$u, tg$alpha)
    ex <- tg$alpha * exp(log_ptrunc(tg$l, tg$u, tg$alpha + 1) - lp)
    ey <- integrate(function(y) y * exp(tg$alpha * y - exp(y) - lgamma(tg$alpha) - lp),
                    tg$a, tg$b, rel.tol = 1e-10, subdivisions = 1000L)$value
    c(logx = ey, x = ex)
}

### p-quantile of log X under truncation, computed on the log-probability scale.
### For small alpha and l = 0 the lower Gamma quantile underflows to 0, so use the
### left-tail form P(Y < y) ~ e^(alpha y) / Gamma(alpha + 1) instead
q_logx <- function(p, tg) {
    al <- tg$alpha; lP <- log_ptrunc(tg$l, tg$u, al)
    if (tg$l > qgamma(0.5, al)) {               # work with upper tails
        s1 <- pgamma(tg$l, al, lower.tail = FALSE, log.p = TRUE)
        x <- qgamma(s1 + log1p(-p * exp(lP - s1)), al, lower.tail = FALSE, log.p = TRUE)  # log{S(l) - p P(l, u)}
    } else {
        f1 <- pgamma(tg$l, al, log.p = TRUE)
        lt <- if (is.finite(f1)) f1 + log1p(p * exp(lP - f1)) else log(p) + lP   # log{F(l) + p P(l, u)}
        x <- qgamma(lt, al, log.p = TRUE)
    }
    y <- log(x)
    if (!is.finite(y)) y <- (log(p) + lP + lgamma(al + 1)) / al
    y
}

### plotting windows are capped at |value| <= AXIS_MAX
AXIS_MAX <- 15
### plotting window for y: the truncation limits where finite, otherwise the
### 0.1% / 99.9% quantiles of the (truncated) distribution of log X,
### then cut to [-AXIS_MAX, AXIS_MAX]
y_window <- function(tg) c(max(if (is.finite(tg$a)) tg$a else q_logx(0.001, tg), -AXIS_MAX),
                           min(if (is.finite(tg$b)) tg$b else q_logx(0.999, tg),  AXIS_MAX))

trunc_label <- function(tg) {
    if (tg$l == 0 && !is.finite(tg$u)) "" else
        sprintf(" truncated to (%g, %s)", tg$l, if (is.finite(tg$u)) format(tg$u) else "Inf")
}

### the three panels: log f_Y with its hull, the histogram of Y, and the histogram of X = e^Y
draw_panels <- function(tg, hull, y, target_n, done, last_y, last_accept) {
    alpha <- tg$alpha
    yw <- y_window(tg)
    yg <- seq(yw[1], yw[2], length.out = 500)
    hull_log <- hull_val(hull, yg); target_log <- tg$h(yg)

    par(mfrow = c(3, 1), mar = c(4, 4.5, 4, 1), cex = 0.95)   # mfrow alone would shrink text to 0.66

    ## 1: log f_Y and the hull on the y scale
    plot(yg, hull_log, type = "l", lwd = 2, col = "steelblue",
         ylim = range(c(hull_log, target_log)), xlab = "y = log x",
         ylab = "log density of Y (unnorm.)")
    title(sprintf("log f_Y(y) = %g y - e^y  vs. hull  (%d tangent points)",
                  alpha, length(hull$x)), line = 2.4)
    abline(v = c(tg$a, tg$b)[is.finite(c(tg$a, tg$b))], col = "darkorange", lty = 2, lwd = 2)
    lines(yg, target_log, lwd = 2, col = "firebrick")
    inside <- hull$x >= yw[1] & hull$x <= yw[2]
    points(hull$x[inside], hull$hx[inside], pch = 19, col = "gray20", cex = 0.9)
    zz <- hull$z[is.finite(hull$z)]
    abline(v = zz[zz >= yw[1] & zz <= yw[2]], col = adjustcolor("gray40", 0.4), lty = 3)
    if (!is.null(last_y) && last_y >= yw[1] && last_y <= yw[2]) {
        points(last_y, tg$h(last_y), pch = if (last_accept) 19 else 4,
               col = if (last_accept) "forestgreen" else "black", cex = 1.6, lwd = 2)
    }
    ## legend in the top margin, between the title and the plot, so it never covers the curves
    legend(x = mean(par("usr")[1:2]), y = par("usr")[4], xjust = 0.5, yjust = 0, xpd = NA,
           horiz = TRUE, bty = "n", cex = 0.85,
           lwd = c(2, 2, 2, NA, NA), lty = c(1, 1, 2, NA, NA), pch = c(NA, NA, NA, 19, 4),
           col = c("steelblue", "firebrick", "darkorange", "forestgreen", "black"),
           legend = c("log hull", "log target", "truncation limits", "last: accepted", "last: rejected"))

    ## 2: histogram of Y against its density
    fy <- dlogGamma_tr(yg, tg)
    if (length(y) == 0) {
        plot(yg, fy, type = "l", lwd = 3, col = "firebrick", xlab = "y = log x", ylab = "density",
             main = "Y = log X: no samples yet")
    } else {
        ### 40 bins across the window, extended to cover every draw so that the
        ### densities stay correct; the view is then cropped to the window
        wy <- diff(yw) / 40
        by <- seq(yw[1] - wy * ceiling(max(0, yw[1] - min(y)) / wy),
                  yw[2] + wy * ceiling(max(0, max(y) - yw[2]) / wy), by = wy)
        hy <- hist(y, breaks = by, plot = FALSE)
        plot(hy, freq = FALSE, xlim = yw, col = "steelblue", border = "white",
             ylim = c(0, max(hy$density, fy) * 1.1), xlab = "y = log x",
             main = sprintf("Y = log X: %d / %d draws%s", length(y), target_n,
                            if (done) "  (done)" else ""))
        lines(yg, fy, lwd = 3, col = "firebrick")
    }
    legend("topleft", bty = "n", lwd = 3, col = "firebrick", legend = "true (truncated) density of log X")

    ## 3: histogram of X = e^Y against the Gamma density
    xmin <- tg$l
    xmax <- if (is.finite(tg$u)) tg$u else exp(q_logx(0.995, tg))
    if (xmin < AXIS_MAX) xmax <- min(xmax, AXIS_MAX)        # cap at AXIS_MAX unless l is beyond it
    xg <- seq(xmin + (xmax - xmin) / 1000, xmax - (xmax - xmin) / 1000, length.out = 500)
    fx <- dGamma_tr(xg, tg)
    cap <- max(fx[xg >= xmin + (xmax - xmin) / 40])        # density at 0 is infinite when alpha < 1
    if (length(y) == 0) {
        plot(xg, fx, type = "l", lwd = 3, col = "firebrick", xlim = c(xmin, xmax),
             ylim = c(0, cap * 1.2), xlab = "x", ylab = "density",
             main = "X = exp(Y): no samples yet")
    } else {
        x <- exp(y)
        wx <- (xmax - xmin) / 40
        hx <- hist(x, breaks = seq(xmin, xmin + wx * ceiling((max(xmax, max(x)) - xmin) / wx), by = wx),
                   plot = FALSE)
        plot(hx, freq = FALSE, col = "darkseagreen", border = "white", xlim = c(xmin, xmax),
             ylim = c(0, max(hx$density, cap) * 1.1), xlab = "x",
             main = sprintf("X = exp(Y) ~ Gamma(%g, 1)%s", alpha, trunc_label(tg)))
        lines(xg, fx, lwd = 3, col = "firebrick")
    }
    legend("topright", bty = "n", lwd = 3, col = "firebrick", legend = "true (truncated) Gamma density")
}

ui <- fluidPage(
    sidebarLayout(
        sidebarPanel(width = 4,
            sliderInput("alpha", "shape α (rate 1)", min = 0.05, max = 5, value = 0.3, step = 0.05),
            sliderInput("lim", "truncation (l, u) for X; u = 20 means ∞",
                        min = 0, max = U_MAX, value = c(0, U_MAX), step = 0.1),
            numericInput("n", "sample size", value = 1000, min = 10, step = 100),
            ### symbol-only buttons; the title attribute gives each a hover tooltip
            tags$style(".ctl-btn { font-size: 18px; padding: 2px 0; }"),
            fluidRow(
                column(3, tagAppendAttributes(actionButton("play_pause", "▶", width = "100%",
                                                           class = "ctl-btn"), title = "Play / Pause")),
                column(3, tagAppendAttributes(actionButton("next_step", "↷", width = "100%",
                                                           class = "ctl-btn"), title = "Next candidate")),
                column(3, tagAppendAttributes(actionButton("finish", "⏭", width = "100%",
                                                           class = "ctl-btn"), title = "Finish: run to the sample size")),
                column(3, tagAppendAttributes(actionButton("restart", "↺", width = "100%",
                                                           class = "ctl-btn"), title = "Restart"))),
            helpText("ARS runs on Y = log X, whose log density α y − e^y is concave for every ",
                     "α > 0; each accepted Y is returned as X = e^Y. Rejected candidates (black x) ",
                     "become new tangent points. Changing a setting restarts the run."),
            tags$style("#tab td, #tab th { white-space: nowrap; }"),
            h5("Run summary"),
            tableOutput("tab"),
            textOutput("status")),
        mainPanel(width = 8,
            plotOutput("panels", height = "760px"))
    )
)

server <- function(input, output, session) {

    rv <- reactiveValues(tg = NULL, hull = NULL, y = numeric(0), tries = 0, target_n = 1000,
                         done = FALSE, playing = FALSE, last_y = NULL, last_accept = NA)

    valid_pos <- function(v, default) if (!is.null(v) && !is.na(v) && v > 0) v else default

    reset_run <- function() {
        alpha <- valid_pos(input$alpha, 0.3)
        lim <- if (!is.null(input$lim)) input$lim else c(0, U_MAX)
        if (lim[2] - lim[1] < 0.05) lim[2] <- lim[1] + 0.05   # guard against an empty interval
        rv$tg <- make_target(alpha, lim[1], lim[2])
        rv$hull <- init_hull(rv$tg)
        rv$y <- numeric(0); rv$tries <- 0
        rv$target_n <- max(10, round(valid_pos(input$n, 1000)))
        rv$done <- FALSE; rv$playing <- FALSE
        rv$last_y <- NULL; rv$last_accept <- NA
        updateActionButton(session, "play_pause", label = "▶")
    }
    isolate(reset_run())

    ### one ARS step on Y; works on plain values so Finish can loop without
    ### touching the reactive values on every iteration
    ars_step <- function(tg, hull) {
        d <- sample_hull(hull)
        accept <- log(runif(1)) < tg$h(d$y) - d$logg
        if (!accept) hull <- build_hull(c(hull$x, d$y), tg)
        list(y = d$y, accept = accept, hull = hull)
    }

    finish_check <- function() {
        if (length(rv$y) >= rv$target_n) {
            rv$done <- TRUE; rv$playing <- FALSE
            updateActionButton(session, "play_pause", label = "▶")
        }
    }

    do_step <- function() {
        if (rv$done) return(invisible(NULL))
        s <- ars_step(rv$tg, rv$hull)
        rv$tries <- rv$tries + 1
        rv$hull <- s$hull
        rv$last_y <- s$y; rv$last_accept <- s$accept
        if (s$accept) rv$y <- c(rv$y, s$y)
        finish_check()
    }

    observeEvent(list(input$alpha, input$lim, input$n), { reset_run() }, ignoreInit = TRUE)
    observeEvent(input$restart, { reset_run() })

    observeEvent(input$play_pause, {
        if (rv$done) return()
        rv$playing <- !rv$playing
        updateActionButton(session, "play_pause",
                           label = if (rv$playing) "⏸" else "▶")
    })

    observeEvent(input$next_step, {
        rv$playing <- FALSE
        updateActionButton(session, "play_pause", label = "▶")
        do_step()
    })

    observeEvent(input$finish, {
        if (rv$done) return()
        tg <- rv$tg; hull <- rv$hull; y <- rv$y; tries <- rv$tries
        need <- rv$target_n - length(y)
        acc <- numeric(need); n_acc <- 0; last <- NULL
        while (n_acc < need) {
            s <- ars_step(tg, hull); tries <- tries + 1; hull <- s$hull; last <- s
            if (s$accept) { n_acc <- n_acc + 1; acc[n_acc] <- s$y }
        }
        rv$hull <- hull; rv$y <- c(y, acc); rv$tries <- tries
        rv$last_y <- last$y; rv$last_accept <- last$accept
        finish_check()
    })

    ### auto-advance one step every 120 ms while playing
    observe({
        if (isTRUE(rv$playing) && !rv$done) {
            invalidateLater(120, session)
            isolate(do_step())
        }
    })

    output$tab <- renderTable({
        y <- rv$y; tm <- true_means(rv$tg)
        est <- function(v) {
            if (length(v) < 2) return(c("-", "-", "-"))
            m <- mean(v); se <- sd(v) / sqrt(length(v))
            sprintf("%.4f", c(m, m - 1.96 * se, m + 1.96 * se))
        }
        ey <- est(y); ex <- est(exp(y))
        data.frame(
            ` ` = c("true", "sample mean", "95% CI lower", "95% CI upper"),
            `E(log X)` = c(sprintf("%.4f", tm[["logx"]]), ey),
            `E(X)`     = c(sprintf("%.4f", tm[["x"]]), ex),
            check.names = FALSE)
    }, striped = TRUE, align = "lll", width = "100%")

    output$status <- renderText({
        n <- length(rv$y)
        sprintf("%d / %d accepted, %d proposals, acceptance %s, %d tangent points",
                n, rv$target_n, rv$tries,
                if (rv$tries > 0) sprintf("%.1f%%", 100 * n / rv$tries) else "-",
                length(rv$hull$x))
    })

    output$panels <- renderPlot({
        draw_panels(rv$tg, rv$hull, rv$y, rv$target_n, rv$done, rv$last_y, rv$last_accept)
    })

}

shinyApp(ui, server)

About the app

Shows how to use adaptive rejection sampling (ARS) for a Gamma distribution whose log density is not concave, optionally truncated to an interval. For \(X\sim\text{Gamma}(\alpha,1)\), \[ \log f_X(x) = (\alpha-1)\log x - x + \text{const}, \qquad \frac{d^2}{dx^2}\log f_X(x) = -\frac{\alpha-1}{x^2}, \] which is convex when \(\alpha<1\), so ARS cannot be run on \(x\) directly: tangent lines would lie below \(\log f_X\) instead of above it. (A rate \(\beta\ne1\) only rescales: if \(X\sim\text{Gamma}(\alpha,1)\) then \(X/\beta\sim\text{Gamma}(\alpha,\beta)\).)

Sampling on the log scale. Let \(Y=\log X\). Its density is \(f_Y(y)=f_X(e^y)\,e^y\), the factor \(e^y\) being the Jacobian of \(x=e^y\), so \[ h(y) = \log f_Y(y) = \alpha y - e^{y} + \text{const}, \qquad h'(y) = \alpha-e^{y}, \qquad h''(y) = -e^{y} < 0 . \] This is strictly concave for every \(\alpha>0\): the troublesome term \((\alpha-1)\log x\) has become the linear term \(\alpha y\). The app runs ARS on \(y\) and returns each accepted draw as \(X=e^{Y}\), which has exactly the (truncated) Gamma distribution.

Truncation. Restricting \(X\) to \((l,u)\) restricts \(Y\) to \((\log l,\log u)\), and a concave function stays concave on a sub-interval, so ARS applies unchanged with the hull built on that interval. The slider sets \(l\) and \(u\); \(l=0\) means no lower limit, and \(u=20\) means no upper limit.

The hull. Where an end of the interval is infinite, the outermost piece of the envelope is infinite too, and it has finite area only if its tangent slopes down towards that end. The starting tangent points are chosen to guarantee this: with no truncation they are the mode \(y^*=\log\alpha\) and \(y^*\pm1\), so \(h'>0\) at the leftmost point and \(h'<0\) at the rightmost; with one finite end, the points run from near that end to one unit beyond the mode on the open side; with both ends finite they are at the quarter points, since every piece on a bounded interval is integrable. Without a lower limit, the left tail of \(Y\) is exactly linear on the log scale, with slope \(\alpha\), so the hull fits it almost perfectly; for small \(\alpha\) this tail is very long, which is the log-scale picture of the Gamma density piling up near \(x=0\).

Panels. Top: \(h(y)\) (red) and the current hull (blue) on the window shown, which is the truncation interval where it is finite and otherwise runs to the 0.1% or 99.9% quantile of \(Y\), cut to \([-15, 15]\) (the \(x\)-axis of the bottom panel is likewise cut at \(15\)); it also shows the tangent points, the breakpoints between hull pieces (dotted), the truncation limits (orange) and the most recent candidate, accepted (green dot) or rejected (black x, which becomes a new tangent point). Middle: the histogram of the accepted \(Y\) against the density of \(\log X\), \(f_Y(y)=e^{\alpha y-e^y}/\{\Gamma(\alpha)\,P(l<X<u)\}\) on \((\log l,\log u)\). Bottom: the histogram of \(X=e^Y\) against the truncated Gamma density. For \(\alpha<1\) and \(l=0\) the density is infinite at \(0\) and most of the draws fall in the first bin, while the same draws are spread out and easy to compare on the log scale.

Run summary (in the sidebar, below the controls). The sample means of \(\log X\) and \(X\) with 95% intervals, against their exact values: \(E(X\mid l<X<u)=\alpha\,P_{\alpha+1}(l,u)/P_{\alpha}(l,u)\), where \(P_a(l,u)\) is the probability of \((l,u)\) under \(\text{Gamma}(a,1)\), and \(E(\log X\mid l<X<u)\) by numerical integration (it equals the digamma function \(\psi(\alpha)\) without truncation). The status line gives the acceptance rate, which approaches 100% as tangent points accumulate.

Controls. Shape \(\alpha\) (0.05 to 5), the truncation interval, and the target sample size; changing any of them restarts the run. The buttons are ▶ (play, which turns into ⏸ to pause) to advance automatically, ↷ to advance one candidate, ⏭ to run to the target sample size at once, and ↺ to restart; hovering over a button shows its name.

NoteR source for this app
library(shiny)

### renderPlot replacement: Safari 27 (WebKit) cannot hold the call stack of
### shiny::renderPlot in webR ("Maximum call stack size exceeded"), so draw with
### renderImage instead, which nests about 45 fewer R calls
renderPlot <- function(expr, width = "auto", height = "auto", res = 72, ...,
                       env = parent.frame(), quoted = FALSE) {
    func <- shiny::exprToFunction(expr, env, quoted)
    shiny::renderImage({
        info <- shiny::getCurrentOutputInfo()
        w  <- if (is.numeric(width))  width  else info$width()
        h  <- if (is.numeric(height)) height else info$height()
        shiny::req(w > 0, h > 0)
        pr <- shiny::getDefaultReactiveDomain()$clientData$pixelratio
        if (is.null(pr)) pr <- 1
        f   <- tempfile(fileext = ".png")
        dev <- shiny:::startPNG(f, w * pr, h * pr, res = res * pr)
        on.exit(grDevices::dev.off(dev), add = TRUE)
        grDevices::dev.control(displaylist = "enable")
        v <- withVisible(func())
        if (v$visible) print(v$value)
        list(src = f, contentType = "image/png", width = w, height = h,
             coordmap = shiny:::getCoordmap(v$value, w * pr, h * pr, res * pr))
    }, deleteFile = TRUE)
}

### -------------------------------------------------------------------------
### Target. Y = log X with X ~ Gamma(alpha, 1), optionally truncated to
### l < X < u, i.e. a < Y < b with a = log l, b = log u. The density of Y is
### f_X(e^y) e^y, so up to a constant
###     h(y) = log f_Y(y) = alpha * y - exp(y),   h''(y) = -exp(y) < 0,
### which is concave for EVERY alpha > 0, while log f_X is convex when alpha < 1.
### -------------------------------------------------------------------------
U_MAX <- 20                                   # slider value of u that means "no upper limit"

make_target <- function(alpha, l, u) {
    a <- if (l > 0) log(l) else -Inf
    b <- if (u < U_MAX) log(u) else Inf
    list(alpha = alpha, l = l, u = if (is.finite(b)) u else Inf, a = a, b = b,
         h      = function(y) alpha * y - exp(y),
         hprime = function(y) alpha - exp(y),
         mode   = log(alpha))
}

### tangent-line hull on (a, b); a = -Inf and/or b = Inf allowed
build_hull <- function(ys, tg) {
    ys <- sort(unique(ys))
    hy <- tg$h(ys); hpy <- tg$hprime(ys)
    k <- length(ys)
    z <- c(tg$a, numeric(max(k - 1, 0)), tg$b)
    if (k > 1) for (i in 1:(k - 1)) {
        z[i + 1] <- (hy[i + 1] - hy[i] - ys[i + 1] * hpy[i + 1] + ys[i] * hpy[i]) /
            (hpy[i] - hpy[i + 1])
    }
    list(x = ys, hx = hy, hp = hpy, z = z)
}

### three starting points inside (a, b). An infinite end needs a tangent that
### points downhill towards it -- h' > 0 at the leftmost point when a = -Inf,
### h' < 0 at the rightmost when b = Inf -- so that the end piece has finite area;
### a finite end needs nothing, since every piece on a bounded interval is integrable
init_hull <- function(tg) {
    a <- tg$a; b <- tg$b; m <- tg$mode
    ys <- if (is.finite(a) && is.finite(b)) a + (b - a) * c(0.25, 0.5, 0.75)
          else if (is.finite(a)) { R <- max(a, m) + 1; a + (R - a) * c(0.1, 0.5, 1) }
          else if (is.finite(b)) { L <- min(b, m) - 1; b - (b - L) * c(0.1, 0.5, 1) }
          else m + c(-1, 0, 1)
    build_hull(ys, tg)
}

### value of tangent piece j at the two ends of its interval; at an infinite
### end it is -Inf, because the slope there always points downhill (see init_hull)
piece_ends <- function(hull, j) {
    a <- hull$hx[j]; b <- hull$hp[j]; xj <- hull$x[j]
    lo <- hull$z[j]; hi <- hull$z[j + 1]
    c(if (is.infinite(lo)) -Inf else a + b * (lo - xj),
      if (is.infinite(hi)) -Inf else a + b * (hi - xj))
}

### log of the area under exp(tangent piece j), computed in log space
log_piece_area <- function(hull, j) {
    b <- hull$hp[j]; v <- piece_ends(hull, j)
    if (abs(b) < 1e-10) return(v[1] + log(hull$z[j + 1] - hull$z[j]))  # flat piece: bounded
    m <- max(v); d <- min(v)
    m + log1p(-exp(d - m)) - log(abs(b))
}

### one draw from the normalized envelope: choose a piece in proportion to its
### area, then invert that piece's exponential CDF, on the log scale
sample_hull <- function(hull) {
    k <- length(hull$x)
    log_areas <- vapply(seq_len(k), function(j) log_piece_area(hull, j), numeric(1))
    mA <- max(log_areas); areas <- exp(log_areas - mA)
    logA <- mA + log(sum(areas))
    j <- sample.int(k, 1, prob = areas)
    a <- hull$hx[j]; b <- hull$hp[j]; xj <- hull$x[j]
    lo <- hull$z[j]; hi <- hull$z[j + 1]
    U <- runif(1)
    if (abs(b) < 1e-10) {
        y <- lo + U * (hi - lo); logg <- a
    } else {
        v <- piece_ends(hull, j); m <- max(v)
        val_y <- m + log((1 - U) * exp(v[1] - m) + U * exp(v[2] - m))
        y <- xj + (val_y - a) / b; logg <- val_y
    }
    list(y = y, logg = logg, logA = logA)
}

### piecewise-linear hull value (log scale) at a vector of y's
hull_val <- function(hull, ygrid) {
    j <- findInterval(ygrid, hull$z, rightmost.closed = TRUE)
    j <- pmax(1, pmin(j, length(hull$x)))
    hull$hx[j] + hull$hp[j] * (ygrid - hull$x[j])
}

### log P(l < X < u) for X ~ Gamma(alpha, 1), from whichever tail keeps precision
log_ptrunc <- function(l, u, alpha) {
    if (l > qgamma(0.5, alpha)) {
        p1 <- pgamma(l, alpha, lower.tail = FALSE, log.p = TRUE)
        p2 <- pgamma(u, alpha, lower.tail = FALSE, log.p = TRUE)
    } else {
        p1 <- pgamma(u, alpha, log.p = TRUE)
        p2 <- pgamma(l, alpha, log.p = TRUE)
    }
    p1 + log1p(-exp(p2 - p1))
}

### normalized (truncated) densities of Y = log X and of X, zero outside the interval
dlogGamma_tr <- function(y, tg) {
    d <- exp(tg$alpha * y - exp(y) - lgamma(tg$alpha) - log_ptrunc(tg$l, tg$u, tg$alpha))
    ifelse(y >= tg$a & y <= tg$b, d, 0)
}
dGamma_tr <- function(x, tg) {
    d <- exp(dgamma(x, tg$alpha, log = TRUE) - log_ptrunc(tg$l, tg$u, tg$alpha))
    ifelse(x >= tg$l & x <= tg$u, d, 0)
}

### exact means: E(X) = alpha P_{alpha+1}(l, u) / P_alpha(l, u); E(log X) by integration
true_means <- function(tg) {
    lp <- log_ptrunc(tg$l, tg$u, tg$alpha)
    ex <- tg$alpha * exp(log_ptrunc(tg$l, tg$u, tg$alpha + 1) - lp)
    ey <- integrate(function(y) y * exp(tg$alpha * y - exp(y) - lgamma(tg$alpha) - lp),
                    tg$a, tg$b, rel.tol = 1e-10, subdivisions = 1000L)$value
    c(logx = ey, x = ex)
}

### p-quantile of log X under truncation, computed on the log-probability scale.
### For small alpha and l = 0 the lower Gamma quantile underflows to 0, so use the
### left-tail form P(Y < y) ~ e^(alpha y) / Gamma(alpha + 1) instead
q_logx <- function(p, tg) {
    al <- tg$alpha; lP <- log_ptrunc(tg$l, tg$u, al)
    if (tg$l > qgamma(0.5, al)) {               # work with upper tails
        s1 <- pgamma(tg$l, al, lower.tail = FALSE, log.p = TRUE)
        x <- qgamma(s1 + log1p(-p * exp(lP - s1)), al, lower.tail = FALSE, log.p = TRUE)  # log{S(l) - p P(l, u)}
    } else {
        f1 <- pgamma(tg$l, al, log.p = TRUE)
        lt <- if (is.finite(f1)) f1 + log1p(p * exp(lP - f1)) else log(p) + lP   # log{F(l) + p P(l, u)}
        x <- qgamma(lt, al, log.p = TRUE)
    }
    y <- log(x)
    if (!is.finite(y)) y <- (log(p) + lP + lgamma(al + 1)) / al
    y
}

### plotting windows are capped at |value| <= AXIS_MAX
AXIS_MAX <- 15
### plotting window for y: the truncation limits where finite, otherwise the
### 0.1% / 99.9% quantiles of the (truncated) distribution of log X,
### then cut to [-AXIS_MAX, AXIS_MAX]
y_window <- function(tg) c(max(if (is.finite(tg$a)) tg$a else q_logx(0.001, tg), -AXIS_MAX),
                           min(if (is.finite(tg$b)) tg$b else q_logx(0.999, tg),  AXIS_MAX))

trunc_label <- function(tg) {
    if (tg$l == 0 && !is.finite(tg$u)) "" else
        sprintf(" truncated to (%g, %s)", tg$l, if (is.finite(tg$u)) format(tg$u) else "Inf")
}

### the three panels: log f_Y with its hull, the histogram of Y, and the histogram of X = e^Y
draw_panels <- function(tg, hull, y, target_n, done, last_y, last_accept) {
    alpha <- tg$alpha
    yw <- y_window(tg)
    yg <- seq(yw[1], yw[2], length.out = 500)
    hull_log <- hull_val(hull, yg); target_log <- tg$h(yg)

    par(mfrow = c(3, 1), mar = c(4, 4.5, 4, 1), cex = 0.95)   # mfrow alone would shrink text to 0.66

    ## 1: log f_Y and the hull on the y scale
    plot(yg, hull_log, type = "l", lwd = 2, col = "steelblue",
         ylim = range(c(hull_log, target_log)), xlab = "y = log x",
         ylab = "log density of Y (unnorm.)")
    title(sprintf("log f_Y(y) = %g y - e^y  vs. hull  (%d tangent points)",
                  alpha, length(hull$x)), line = 2.4)
    abline(v = c(tg$a, tg$b)[is.finite(c(tg$a, tg$b))], col = "darkorange", lty = 2, lwd = 2)
    lines(yg, target_log, lwd = 2, col = "firebrick")
    inside <- hull$x >= yw[1] & hull$x <= yw[2]
    points(hull$x[inside], hull$hx[inside], pch = 19, col = "gray20", cex = 0.9)
    zz <- hull$z[is.finite(hull$z)]
    abline(v = zz[zz >= yw[1] & zz <= yw[2]], col = adjustcolor("gray40", 0.4), lty = 3)
    if (!is.null(last_y) && last_y >= yw[1] && last_y <= yw[2]) {
        points(last_y, tg$h(last_y), pch = if (last_accept) 19 else 4,
               col = if (last_accept) "forestgreen" else "black", cex = 1.6, lwd = 2)
    }
    ## legend in the top margin, between the title and the plot, so it never covers the curves
    legend(x = mean(par("usr")[1:2]), y = par("usr")[4], xjust = 0.5, yjust = 0, xpd = NA,
           horiz = TRUE, bty = "n", cex = 0.85,
           lwd = c(2, 2, 2, NA, NA), lty = c(1, 1, 2, NA, NA), pch = c(NA, NA, NA, 19, 4),
           col = c("steelblue", "firebrick", "darkorange", "forestgreen", "black"),
           legend = c("log hull", "log target", "truncation limits", "last: accepted", "last: rejected"))

    ## 2: histogram of Y against its density
    fy <- dlogGamma_tr(yg, tg)
    if (length(y) == 0) {
        plot(yg, fy, type = "l", lwd = 3, col = "firebrick", xlab = "y = log x", ylab = "density",
             main = "Y = log X: no samples yet")
    } else {
        ### 40 bins across the window, extended to cover every draw so that the
        ### densities stay correct; the view is then cropped to the window
        wy <- diff(yw) / 40
        by <- seq(yw[1] - wy * ceiling(max(0, yw[1] - min(y)) / wy),
                  yw[2] + wy * ceiling(max(0, max(y) - yw[2]) / wy), by = wy)
        hy <- hist(y, breaks = by, plot = FALSE)
        plot(hy, freq = FALSE, xlim = yw, col = "steelblue", border = "white",
             ylim = c(0, max(hy$density, fy) * 1.1), xlab = "y = log x",
             main = sprintf("Y = log X: %d / %d draws%s", length(y), target_n,
                            if (done) "  (done)" else ""))
        lines(yg, fy, lwd = 3, col = "firebrick")
    }
    legend("topleft", bty = "n", lwd = 3, col = "firebrick", legend = "true (truncated) density of log X")

    ## 3: histogram of X = e^Y against the Gamma density
    xmin <- tg$l
    xmax <- if (is.finite(tg$u)) tg$u else exp(q_logx(0.995, tg))
    if (xmin < AXIS_MAX) xmax <- min(xmax, AXIS_MAX)        # cap at AXIS_MAX unless l is beyond it
    xg <- seq(xmin + (xmax - xmin) / 1000, xmax - (xmax - xmin) / 1000, length.out = 500)
    fx <- dGamma_tr(xg, tg)
    cap <- max(fx[xg >= xmin + (xmax - xmin) / 40])        # density at 0 is infinite when alpha < 1
    if (length(y) == 0) {
        plot(xg, fx, type = "l", lwd = 3, col = "firebrick", xlim = c(xmin, xmax),
             ylim = c(0, cap * 1.2), xlab = "x", ylab = "density",
             main = "X = exp(Y): no samples yet")
    } else {
        x <- exp(y)
        wx <- (xmax - xmin) / 40
        hx <- hist(x, breaks = seq(xmin, xmin + wx * ceiling((max(xmax, max(x)) - xmin) / wx), by = wx),
                   plot = FALSE)
        plot(hx, freq = FALSE, col = "darkseagreen", border = "white", xlim = c(xmin, xmax),
             ylim = c(0, max(hx$density, cap) * 1.1), xlab = "x",
             main = sprintf("X = exp(Y) ~ Gamma(%g, 1)%s", alpha, trunc_label(tg)))
        lines(xg, fx, lwd = 3, col = "firebrick")
    }
    legend("topright", bty = "n", lwd = 3, col = "firebrick", legend = "true (truncated) Gamma density")
}

ui <- fluidPage(
    sidebarLayout(
        sidebarPanel(width = 4,
            sliderInput("alpha", "shape α (rate 1)", min = 0.05, max = 5, value = 0.3, step = 0.05),
            sliderInput("lim", "truncation (l, u) for X; u = 20 means ∞",
                        min = 0, max = U_MAX, value = c(0, U_MAX), step = 0.1),
            numericInput("n", "sample size", value = 1000, min = 10, step = 100),
            ### symbol-only buttons; the title attribute gives each a hover tooltip
            tags$style(".ctl-btn { font-size: 18px; padding: 2px 0; }"),
            fluidRow(
                column(3, tagAppendAttributes(actionButton("play_pause", "▶", width = "100%",
                                                           class = "ctl-btn"), title = "Play / Pause")),
                column(3, tagAppendAttributes(actionButton("next_step", "↷", width = "100%",
                                                           class = "ctl-btn"), title = "Next candidate")),
                column(3, tagAppendAttributes(actionButton("finish", "⏭", width = "100%",
                                                           class = "ctl-btn"), title = "Finish: run to the sample size")),
                column(3, tagAppendAttributes(actionButton("restart", "↺", width = "100%",
                                                           class = "ctl-btn"), title = "Restart"))),
            helpText("ARS runs on Y = log X, whose log density α y − e^y is concave for every ",
                     "α > 0; each accepted Y is returned as X = e^Y. Rejected candidates (black x) ",
                     "become new tangent points. Changing a setting restarts the run."),
            tags$style("#tab td, #tab th { white-space: nowrap; }"),
            h5("Run summary"),
            tableOutput("tab"),
            textOutput("status")),
        mainPanel(width = 8,
            plotOutput("panels", height = "760px"))
    )
)

server <- function(input, output, session) {

    rv <- reactiveValues(tg = NULL, hull = NULL, y = numeric(0), tries = 0, target_n = 1000,
                         done = FALSE, playing = FALSE, last_y = NULL, last_accept = NA)

    valid_pos <- function(v, default) if (!is.null(v) && !is.na(v) && v > 0) v else default

    reset_run <- function() {
        alpha <- valid_pos(input$alpha, 0.3)
        lim <- if (!is.null(input$lim)) input$lim else c(0, U_MAX)
        if (lim[2] - lim[1] < 0.05) lim[2] <- lim[1] + 0.05   # guard against an empty interval
        rv$tg <- make_target(alpha, lim[1], lim[2])
        rv$hull <- init_hull(rv$tg)
        rv$y <- numeric(0); rv$tries <- 0
        rv$target_n <- max(10, round(valid_pos(input$n, 1000)))
        rv$done <- FALSE; rv$playing <- FALSE
        rv$last_y <- NULL; rv$last_accept <- NA
        updateActionButton(session, "play_pause", label = "▶")
    }
    isolate(reset_run())

    ### one ARS step on Y; works on plain values so Finish can loop without
    ### touching the reactive values on every iteration
    ars_step <- function(tg, hull) {
        d <- sample_hull(hull)
        accept <- log(runif(1)) < tg$h(d$y) - d$logg
        if (!accept) hull <- build_hull(c(hull$x, d$y), tg)
        list(y = d$y, accept = accept, hull = hull)
    }

    finish_check <- function() {
        if (length(rv$y) >= rv$target_n) {
            rv$done <- TRUE; rv$playing <- FALSE
            updateActionButton(session, "play_pause", label = "▶")
        }
    }

    do_step <- function() {
        if (rv$done) return(invisible(NULL))
        s <- ars_step(rv$tg, rv$hull)
        rv$tries <- rv$tries + 1
        rv$hull <- s$hull
        rv$last_y <- s$y; rv$last_accept <- s$accept
        if (s$accept) rv$y <- c(rv$y, s$y)
        finish_check()
    }

    observeEvent(list(input$alpha, input$lim, input$n), { reset_run() }, ignoreInit = TRUE)
    observeEvent(input$restart, { reset_run() })

    observeEvent(input$play_pause, {
        if (rv$done) return()
        rv$playing <- !rv$playing
        updateActionButton(session, "play_pause",
                           label = if (rv$playing) "⏸" else "▶")
    })

    observeEvent(input$next_step, {
        rv$playing <- FALSE
        updateActionButton(session, "play_pause", label = "▶")
        do_step()
    })

    observeEvent(input$finish, {
        if (rv$done) return()
        tg <- rv$tg; hull <- rv$hull; y <- rv$y; tries <- rv$tries
        need <- rv$target_n - length(y)
        acc <- numeric(need); n_acc <- 0; last <- NULL
        while (n_acc < need) {
            s <- ars_step(tg, hull); tries <- tries + 1; hull <- s$hull; last <- s
            if (s$accept) { n_acc <- n_acc + 1; acc[n_acc] <- s$y }
        }
        rv$hull <- hull; rv$y <- c(y, acc); rv$tries <- tries
        rv$last_y <- last$y; rv$last_accept <- last$accept
        finish_check()
    })

    ### auto-advance one step every 120 ms while playing
    observe({
        if (isTRUE(rv$playing) && !rv$done) {
            invalidateLater(120, session)
            isolate(do_step())
        }
    })

    output$tab <- renderTable({
        y <- rv$y; tm <- true_means(rv$tg)
        est <- function(v) {
            if (length(v) < 2) return(c("-", "-", "-"))
            m <- mean(v); se <- sd(v) / sqrt(length(v))
            sprintf("%.4f", c(m, m - 1.96 * se, m + 1.96 * se))
        }
        ey <- est(y); ex <- est(exp(y))
        data.frame(
            ` ` = c("true", "sample mean", "95% CI lower", "95% CI upper"),
            `E(log X)` = c(sprintf("%.4f", tm[["logx"]]), ey),
            `E(X)`     = c(sprintf("%.4f", tm[["x"]]), ex),
            check.names = FALSE)
    }, striped = TRUE, align = "lll", width = "100%")

    output$status <- renderText({
        n <- length(rv$y)
        sprintf("%d / %d accepted, %d proposals, acceptance %s, %d tangent points",
                n, rv$target_n, rv$tries,
                if (rv$tries > 0) sprintf("%.1f%%", 100 * n / rv$tries) else "-",
                length(rv$hull$x))
    })

    output$panels <- renderPlot({
        draw_panels(rv$tg, rv$hull, rv$y, rv$target_n, rv$done, rv$last_y, rv$last_accept)
    })

}

shinyApp(ui, server)

This app accompanies Rejection Sampling in the book.