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)

Gibbs Sampling for the Cauchy Model with Unknown Location and Scale

Author

Longhai Li

Published

November 25, 2026

#| '!! shinylive warning !!': |
#|   shinylive does not work in self-contained HTML documents.
#|   Please set `embed-resources: false` in your metadata.
#| standalone: true
#| viewerHeight: 1100
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)
}

mu_0 <- 0; tau <- 10                                    # prior: mu ~ N(0, 10^2)
a_0 <- 1; b_0 <- 1                                      # prior: sigma^2 ~ Inverse-Gamma(1, 1)

ui <- fluidPage(
    wellPanel(
        tags$strong("Data"),
        fluidRow(
            column(3, sliderInput("n_obs", "number of observations", min = 5, max = 200, value = 30, step = 5)),
            column(3, sliderInput("mu_true", "true location mu", min = -10, max = 10, value = 2, step = 0.5)),
            column(3, sliderInput("sig_true", "true scale sigma", min = 0.2, max = 5, value = 1, step = 0.1)),
            column(3, div(style = "margin-top: 25px;",
                actionButton("new", "New data", width = "100%")))),
        tags$strong("MCMC sampling"),
        fluidRow(
            column(3, sliderInput("N", "number of Gibbs iterations", min = 50, max = 5000, value = 500, step = 50)),
            column(3, sliderInput("mu_init", "starting value of mu", min = -20, max = 20, value = -10, step = 1)),
            column(3, sliderInput("sig_init", "starting value of sigma", min = 0.2, max = 10, value = 6, step = 0.2)),
            column(3,
                checkboxInput("sub", "show each Gibbs step", TRUE),
                tags$style(".ctl-btn { font-size: 16px; padding: 2px 10px; }"),
                div(class = "btn-group", role = "group",
                    tagAppendAttributes(actionButton("play", "▶", class = "ctl-btn btn-sm"), title = "Play / Pause"),
                    tagAppendAttributes(actionButton("next_step", "↷", class = "ctl-btn btn-sm"), title = "Next step"),
                    tagAppendAttributes(actionButton("end", "⏭", class = "ctl-btn btn-sm"), title = "End: run to the last iteration"),
                    tagAppendAttributes(actionButton("restart", "↺", class = "ctl-btn btn-sm"), title = "Restart"))))
    ),
    fluidRow(
        column(7,
            fluidRow(
                column(6, plotOutput("plane", height = "320px")),
                column(6, plotOutput("vplot", height = "320px"))),
            fluidRow(
                column(6, plotOutput("tr_mu", height = "240px")),
                column(6, plotOutput("tr_sg", height = "240px")))),
        column(5,
            tags$style("#tab td, #tab th { white-space: nowrap; font-size: 85%; }"),
            h5("Where the sampler is"),
            textOutput("status"),
            h5("Posterior summaries"),
            tableOutput("tab"))
    )
)

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

    ### data: y_i ~ Cauchy(mu_true, sig_true)
    dat <- reactive({
        set.seed(100 + input$new)
        y <- input$mu_true + input$sig_true * rcauchy(input$n_obs)
        n <- length(y)
        ### exact joint posterior of (mu, sigma) on a grid, for the contours and the exact summaries:
        ### a wide first pass locates the mass, a second pass on the region that holds 99.9% of it refines
        post_grid <- function(mu_g, sg_g) {
            ll <- matrix(0, 200, 200)
            for (yi in y) ll <- ll + outer(mu_g, sg_g, function(m, s) dcauchy(yi, m, s, log = TRUE))
            lp_sigma <- log(2 * sg_g) + a_0 * log(b_0) - lgamma(a_0) - (a_0 + 1) * log(sg_g^2) - b_0 / sg_g^2
            lpost <- ll + dnorm(mu_g, mu_0, tau, log = TRUE) + matrix(lp_sigma, 200, 200, byrow = TRUE)
            p <- exp(lpost - max(lpost)); p / sum(p)
        }
        span <- function(g, marg) {
            cdf <- cumsum(marg); r <- g[c(max(1, which(cdf > 0.0005)[1] - 1), min(length(g), which(cdf > 0.9995)[1] + 1))]
            pad <- 0.2 * diff(r); c(r[1] - pad, r[2] + pad)
        }
        m0 <- median(y); s0 <- max(IQR(y) / 2, 0.5)
        mu_g <- seq(m0 - 8 * s0, m0 + 8 * s0, length.out = 200)
        sg_g <- seq(0.05, 6 * s0 + 2, length.out = 200)
        p <- post_grid(mu_g, sg_g)
        mr <- span(mu_g, rowSums(p)); sr <- span(sg_g, colSums(p))
        mu_g <- seq(mr[1], mr[2], length.out = 200)
        sg_g <- seq(max(sr[1], 0.02), sr[2], length.out = 200)
        p <- post_grid(mu_g, sg_g)
        pm <- rowSums(p); ps <- colSums(p)
        e_mu <- sum(pm * mu_g); e_sg <- sum(ps * sg_g)
        q_of <- function(g, marg) approx(cumsum(marg), g, xout = c(0.025, 0.975), rule = 2)$y
        ### maximum likelihood for Cauchy(mu, sigma) with a Wald interval from the observed information
        ### (the interval for sigma is formed on the log scale and transformed back)
        nll <- function(th) -sum(dcauchy(y, th[1], exp(th[2]), log = TRUE))
        fit <- optim(c(median(y), log(s0)), nll, method = "BFGS", hessian = TRUE)
        se  <- tryCatch(sqrt(diag(solve(fit$hessian))), error = function(e) c(NA, NA))
        mle <- list(mu = fit$par[1], sg = exp(fit$par[2]), se_mu = se[1], se_sg = exp(fit$par[2]) * se[2],
                    ci_mu = fit$par[1] + c(-1, 1) * 1.96 * se[1],
                    ci_sg = exp(fit$par[2] + c(-1, 1) * 1.96 * se[2]))
        list(y = y, n = n, mu_g = mu_g, sg_g = sg_g, post = p, mle = mle,
             q_mu = q_of(mu_g, pm), q_sg = q_of(sg_g, ps),
             exact = c(mean_mu = e_mu, mean_sg = e_sg,
                       sd_mu = sqrt(sum(pm * (mu_g - e_mu)^2)), sd_sg = sqrt(sum(ps * (sg_g - e_sg)^2))))
    })

    rv <- reactiveValues(N = 500, t = 0, phase = 0, mu = NULL, sg = NULL, v = NULL,
                         cur_mu = 0, cur_sg = 1, path = NULL, np = 0, last = "", playing = FALSE)

    reset_run <- function() {
        N <- input$N
        rv$N <- N; rv$t <- 0; rv$phase <- 0
        rv$mu <- c(input$mu_init, rep(NA_real_, N)); rv$sg <- c(input$sig_init, rep(NA_real_, N))
        rv$cur_mu <- input$mu_init; rv$cur_sg <- input$sig_init
        rv$v <- NULL
        rv$path <- matrix(NA_real_, 3 * N + 2, 3)            # columns: mu, sigma, sub-step (0 start, 1 v, 2 mu, 3 sigma)
        rv$path[1, ] <- c(input$mu_init, input$sig_init, 0); rv$np <- 1
        rv$last <- "start"
        rv$playing <- FALSE
        updateActionButton(session, "play", label = "▶")
        set.seed(1000 + input$new)
    }

    add_path <- function(code) {
        rv$np <- rv$np + 1
        rv$path[rv$np, ] <- c(rv$cur_mu, rv$cur_sg, code)
    }

    ### one Gibbs sub-step: (1) the latent variances v_i, (2) mu, (3) sigma
    step_one <- function() {
        d <- dat(); y <- d$y; n <- d$n
        if (rv$t >= rv$N && rv$phase == 0) return(invisible(NULL))
        if (rv$phase == 0) {
            r2 <- (y - rv$cur_mu)^2 / rv$cur_sg^2
            rv$v <- 1 / rgamma(n, shape = 1, rate = (1 + r2) / 2)                 # v_i | mu, sigma, y_i ~ IG(1, (1 + r_i^2)/2)
            rv$phase <- 1; rv$last <- "v_i | mu, sigma"; add_path(1)
        } else if (rv$phase == 1) {
            prec <- 1 / tau^2 + sum(1 / (rv$cur_sg^2 * rv$v))
            mean <- (mu_0 / tau^2 + sum(y / (rv$cur_sg^2 * rv$v))) / prec
            rv$cur_mu <- rnorm(1, mean, 1 / sqrt(prec))                            # mu | v, sigma, y ~ normal
            rv$phase <- 2; rv$last <- "mu | v, sigma"; add_path(2)
        } else {
            rate <- b_0 + sum((y - rv$cur_mu)^2 / (2 * rv$v))
            rv$cur_sg <- sqrt(1 / rgamma(1, shape = a_0 + n / 2, rate = rate))     # sigma^2 | mu, v, y ~ inverse gamma
            rv$phase <- 0; rv$t <- rv$t + 1; rv$last <- "sigma | mu, v"; add_path(3)
            rv$mu[rv$t + 1] <- rv$cur_mu; rv$sg[rv$t + 1] <- rv$cur_sg
        }
    }
    step_iter <- function() {                       # finish the current iteration, or run a whole one
        repeat {
            step_one()
            if (rv$phase == 0 || rv$t >= rv$N) break
        }
    }
    finished <- function() rv$t >= rv$N && rv$phase == 0

    observeEvent(list(input$n_obs, input$mu_true, input$sig_true, input$N, input$mu_init, input$sig_init,
                      input$new, input$restart),
                 { req(input$N, input$mu_init, input$sig_init); reset_run() })

    observeEvent(input$play, {
        if (finished()) return()
        rv$playing <- !rv$playing
        updateActionButton(session, "play", label = if (rv$playing) "⏸" else "▶")
    })
    observeEvent(input$next_step, {
        rv$playing <- FALSE; updateActionButton(session, "play", label = "▶")
        if (isTRUE(input$sub)) step_one() else step_iter()
    })
    observeEvent(input$end, {
        rv$playing <- FALSE; updateActionButton(session, "play", label = "▶")
        while (!finished()) step_iter()
    })
    observe({
        if (isTRUE(rv$playing)) {
            invalidateLater(150, session)
            isolate({
                if (isTRUE(input$sub)) step_one() else step_iter()
                if (finished()) { rv$playing <- FALSE; updateActionButton(session, "play", label = "▶") }
            })
        }
    })

    output$status <- renderText({
        req(rv$mu)
        sprintf("iteration %d / %d; current (mu, sigma) = (%.3f, %.3f)", rv$t, rv$N, rv$cur_mu, rv$cur_sg)
    })

    ### the (mu, sigma) plane: exact posterior contours, the Gibbs draws, and optionally the path of each step
    output$plane <- renderPlot({
        req(rv$mu); d <- dat(); t <- rv$t
        ex <- d$exact                                          # the window is the exact posterior mean +- 3 sd, not the starting value
        xlim <- ex["mean_mu"] + c(-3, 3) * ex["sd_mu"]; ylim <- ex["mean_sg"] + c(-3, 3) * ex["sd_sg"]
        par(mar = c(4, 4, 3, 1))
        cols <- hcl.colors(30, "YlOrRd", rev = TRUE)
        plot(NA, xlim = xlim, ylim = ylim, xlab = expression(mu), ylab = expression(sigma),
             main = "Gibbs draws on the exact posterior")
        rect(par("usr")[1], par("usr")[3], par("usr")[2], par("usr")[4], col = cols[1], border = NA)
        image(d$mu_g, d$sg_g, d$post, col = cols, add = TRUE)
        contour(d$mu_g, d$sg_g, d$post, nlevels = 6, drawlabels = FALSE, add = TRUE, col = "gray40")
        if (t >= 1) points(rv$mu[2:(t + 1)], rv$sg[2:(t + 1)], pch = 19, cex = 0.4, col = adjustcolor("black", 0.45))
        points(input$mu_init, input$sig_init, pch = 17, col = "steelblue", cex = 1.4)
        if (isTRUE(input$sub) && rv$np >= 2) {
            k <- max(2, rv$np - 1):rv$np                                    # the last two sub-steps
            P <- rv$path
            for (j in k) {
                if (P[j, 3] == 2) arrows(P[j - 1, 1], P[j - 1, 2], P[j, 1], P[j, 2], length = 0.08, lwd = 2, col = "darkorange")
                if (P[j, 3] == 3) arrows(P[j - 1, 1], P[j - 1, 2], P[j, 1], P[j, 2], length = 0.08, lwd = 2, col = "steelblue")
                if (P[j, 3] == 1) points(P[j, 1], P[j, 2], pch = 1, cex = 2.2, lwd = 2, col = "forestgreen")
            }
        }
        points(rv$cur_mu, rv$cur_sg, pch = 19, cex = 1.3, col = "red")
        legend("topright", bty = "n", cex = 0.8, pch = c(19, 17, 19), col = c("black", "steelblue", "red"),
               legend = c("draws", "start", "current"))
    })

    ### the augmented variances v_i: outlying observations get large v_i, so they are downweighted
    output$vplot <- renderPlot({
        req(rv$mu); d <- dat(); par(mar = c(4, 4, 3, 1))
        if (is.null(rv$v)) {
            plot(d$y, rep(1, d$n), type = "n", log = "y", xlab = "y", ylab = expression(v[i]),
                 main = expression("latent variances"~v[i]~"(not drawn yet)"))
            rug(d$y)
        } else {
            plot(d$y, rv$v, log = "y", pch = 19, col = adjustcolor("forestgreen", 0.7), xlab = "y",
                 ylab = expression(v[i]), main = expression("latent variances"~v[i]~"(current)"))
            abline(v = rv$cur_mu, col = "red", lty = 2)
            legend("topright", bty = "n", cex = 0.8, lty = 2, col = "red", legend = expression(current~mu))
        }
    })

    trace_plot <- function(x, exact, sd, ylab) {
        par(mar = c(4, 4, 2, 1))
        plot(0:rv$N, x, type = "n", xlab = "iteration", ylab = ylab,
             ylim = exact + c(-3, 3) * sd)                                  # window around the posterior, not the start
        lines(0:rv$t, x[1:(rv$t + 1)], col = "gray30")
        abline(h = exact, col = "red", lty = 2)
    }
    output$tr_mu <- renderPlot({ req(rv$mu); d <- dat(); trace_plot(rv$mu, d$exact["mean_mu"], d$exact["sd_mu"], expression(mu)) })
    output$tr_sg <- renderPlot({ req(rv$mu); d <- dat(); trace_plot(rv$sg, d$exact["mean_sg"], d$exact["sd_sg"], expression(sigma)) })

    output$tab <- renderTable({
        req(rv$mu); d <- dat(); t <- rv$t; m <- d$mle
        burn <- floor(0.2 * t)
        idx <- if (t - burn >= 2) (burn + 2):(t + 1) else integer(0)
        f4  <- function(x) sprintf("%.4f", x)
        ci4 <- function(x) sprintf("(%.4f, %.4f)", x[1], x[2])
        gm <- function(x) if (length(idx)) f4(mean(x[idx])) else "-"
        gs <- function(x) if (length(idx)) f4(sd(x[idx])) else "-"
        gq <- function(x) if (length(idx)) ci4(quantile(x[idx], c(0.025, 0.975))) else "-"
        data.frame(
            ` ` = c("mu: mean / estimate", "mu: sd / SE", "mu: 95% interval",
                    "sigma: mean / estimate", "sigma: sd / SE", "sigma: 95% interval"),
            `Exact posterior` = c(f4(d$exact["mean_mu"]), f4(d$exact["sd_mu"]), ci4(d$q_mu),
                                  f4(d$exact["mean_sg"]), f4(d$exact["sd_sg"]), ci4(d$q_sg)),
            Gibbs = c(gm(rv$mu), gs(rv$mu), gq(rv$mu), gm(rv$sg), gs(rv$sg), gq(rv$sg)),
            MLE = c(f4(m$mu), f4(m$se_mu), ci4(m$ci_mu), f4(m$sg), f4(m$se_sg), ci4(m$ci_sg)),
            check.names = FALSE)
    }, striped = TRUE, align = "lrrr", width = "100%")
}

shinyApp(ui, server)

About the app

Shows a Gibbs sampler for the Cauchy model with unknown location and scale, built on data augmentation with a latent variance for each observation, and lets you step through the sampler one conditional update at a time.

The model and the augmentation. The data are \(y_1,\ldots,y_n\overset{iid}{\sim}\text{Cauchy}(\mu,\sigma)\), with the priors \(\mu\sim N(0,10^2)\) and \(\sigma^2\sim\text{Inverse-Gamma}(1,1)\). The Cauchy density has no conjugate form, but it is a scale mixture of normals: if \[y_i\mid\mu,\sigma,v_i\sim N(\mu,\,\sigma^2v_i),\qquad v_i\sim\text{Inverse-Gamma}\big(\tfrac12,\tfrac12\big)\ \text{independently},\] then integrating out \(v_i\) gives \(y_i\sim\text{Cauchy}(\mu,\sigma)\). Treating \(v_1,\ldots,v_n\) as extra unknowns, all the full conditionals are standard distributions.

The full conditionals. Write \(r_i=(y_i-\mu)/\sigma\). Multiplying the augmented likelihood by the priors gives \[v_i\mid\mu,\sigma,y\sim\text{Inverse-Gamma}\Big(1,\ \tfrac{1+r_i^2}{2}\Big),\] \[\mu\mid v,\sigma,y\sim N\Big(\frac{\mu_0/\tau^2+\sum_iy_i/(\sigma^2v_i)}{1/\tau^2+\sum_i1/(\sigma^2v_i)},\ \Big[\frac1{\tau^2}+\sum_i\frac1{\sigma^2v_i}\Big]^{-1}\Big),\] \[\sigma^2\mid\mu,v,y\sim\text{Inverse-Gamma}\Big(a_0+\tfrac n2,\ b_0+\sum_i\frac{(y_i-\mu)^2}{2v_i}\Big),\] with \(\mu_0=0\), \(\tau=10\), \(a_0=b_0=1\). One Gibbs iteration draws \(v\) given \((\mu,\sigma)\), then \(\mu\) given \((v,\sigma)\), then \(\sigma\) given \((\mu,v)\). A large \(r_i\) (an outlier) gives a large \(v_i\), which makes the observation contribute little to the draws of \(\mu\) and \(\sigma\); this is how the sampler reproduces the robustness of the Cauchy model.

The panels.

  • Top left: the exact joint posterior of \((\mu,\sigma)\) computed on a grid (contours and heat) with the Gibbs draws on top. The triangle is the starting value and the red dot the current state. With “show each Gibbs step” ticked, the plot shows the last two sub-steps: a green circle for the \(v\) update (it does not move \((\mu,\sigma)\)), an orange horizontal arrow for the \(\mu\) update and a blue vertical arrow for the \(\sigma\) update, which are the two legs of the staircase of a Gibbs sampler.
  • Top right: the current latent variances \(v_i\) (log scale) against \(y_i\); the outliers far from \(\mu\) have the largest \(v_i\).
  • Bottom: trace plots of \(\mu\) and \(\sigma\), with the exact posterior means (red dashed lines).
  • Table: for \(\mu\) and for \(\sigma\), the posterior mean, standard deviation and 95% credible interval, computed exactly on the grid and from the Gibbs draws so far (after discarding the first 20% as burn-in), next to the maximum likelihood estimate of the Cauchy model, its standard error and its 95% Wald interval. The MLE and its standard error come from the observed information at the maximum, and the interval for \(\sigma\) is formed on the log scale and transformed back so that it stays positive. The prior is weak, so the posterior is centred near the MLE, but the posterior (and the Gibbs draws) account for the uncertainty without the normal approximation: the credible interval for \(\sigma\) is asymmetric, and for small samples the Wald intervals are noticeably different.

Controls. The buttons ▶/⏸ (play/pause), ↷ (next), ⏭ (end) and ↺ (restart) advance the sampler automatically, advance it by one step, run it to the last iteration and start the chain again. With “show each Gibbs step” ticked, play and next move one sub-step at a time (update \(v\), then \(\mu\), then \(\sigma\)); with it unticked they move by whole iterations. Changing the data, the number of iterations or the starting values restarts the chain.

What to try. The axes of the plane plot and of the traces are fixed to the exact posterior mean \(\pm3\) posterior standard deviations, so a starting value far from it (the default is \(\mu=-10,\sigma=6\)) is outside the view and the first few staircases enter from the edge. Then set the number of iterations to a few thousand and press End to see the chain mix and the table agree. Add outliers by increasing the sample size (a Cauchy sample always has some) and compare their \(v_i\) with those of the observations near \(\mu\).

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)
}

mu_0 <- 0; tau <- 10                                    # prior: mu ~ N(0, 10^2)
a_0 <- 1; b_0 <- 1                                      # prior: sigma^2 ~ Inverse-Gamma(1, 1)

ui <- fluidPage(
    wellPanel(
        tags$strong("Data"),
        fluidRow(
            column(3, sliderInput("n_obs", "number of observations", min = 5, max = 200, value = 30, step = 5)),
            column(3, sliderInput("mu_true", "true location mu", min = -10, max = 10, value = 2, step = 0.5)),
            column(3, sliderInput("sig_true", "true scale sigma", min = 0.2, max = 5, value = 1, step = 0.1)),
            column(3, div(style = "margin-top: 25px;",
                actionButton("new", "New data", width = "100%")))),
        tags$strong("MCMC sampling"),
        fluidRow(
            column(3, sliderInput("N", "number of Gibbs iterations", min = 50, max = 5000, value = 500, step = 50)),
            column(3, sliderInput("mu_init", "starting value of mu", min = -20, max = 20, value = -10, step = 1)),
            column(3, sliderInput("sig_init", "starting value of sigma", min = 0.2, max = 10, value = 6, step = 0.2)),
            column(3,
                checkboxInput("sub", "show each Gibbs step", TRUE),
                tags$style(".ctl-btn { font-size: 16px; padding: 2px 10px; }"),
                div(class = "btn-group", role = "group",
                    tagAppendAttributes(actionButton("play", "▶", class = "ctl-btn btn-sm"), title = "Play / Pause"),
                    tagAppendAttributes(actionButton("next_step", "↷", class = "ctl-btn btn-sm"), title = "Next step"),
                    tagAppendAttributes(actionButton("end", "⏭", class = "ctl-btn btn-sm"), title = "End: run to the last iteration"),
                    tagAppendAttributes(actionButton("restart", "↺", class = "ctl-btn btn-sm"), title = "Restart"))))
    ),
    fluidRow(
        column(7,
            fluidRow(
                column(6, plotOutput("plane", height = "320px")),
                column(6, plotOutput("vplot", height = "320px"))),
            fluidRow(
                column(6, plotOutput("tr_mu", height = "240px")),
                column(6, plotOutput("tr_sg", height = "240px")))),
        column(5,
            tags$style("#tab td, #tab th { white-space: nowrap; font-size: 85%; }"),
            h5("Where the sampler is"),
            textOutput("status"),
            h5("Posterior summaries"),
            tableOutput("tab"))
    )
)

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

    ### data: y_i ~ Cauchy(mu_true, sig_true)
    dat <- reactive({
        set.seed(100 + input$new)
        y <- input$mu_true + input$sig_true * rcauchy(input$n_obs)
        n <- length(y)
        ### exact joint posterior of (mu, sigma) on a grid, for the contours and the exact summaries:
        ### a wide first pass locates the mass, a second pass on the region that holds 99.9% of it refines
        post_grid <- function(mu_g, sg_g) {
            ll <- matrix(0, 200, 200)
            for (yi in y) ll <- ll + outer(mu_g, sg_g, function(m, s) dcauchy(yi, m, s, log = TRUE))
            lp_sigma <- log(2 * sg_g) + a_0 * log(b_0) - lgamma(a_0) - (a_0 + 1) * log(sg_g^2) - b_0 / sg_g^2
            lpost <- ll + dnorm(mu_g, mu_0, tau, log = TRUE) + matrix(lp_sigma, 200, 200, byrow = TRUE)
            p <- exp(lpost - max(lpost)); p / sum(p)
        }
        span <- function(g, marg) {
            cdf <- cumsum(marg); r <- g[c(max(1, which(cdf > 0.0005)[1] - 1), min(length(g), which(cdf > 0.9995)[1] + 1))]
            pad <- 0.2 * diff(r); c(r[1] - pad, r[2] + pad)
        }
        m0 <- median(y); s0 <- max(IQR(y) / 2, 0.5)
        mu_g <- seq(m0 - 8 * s0, m0 + 8 * s0, length.out = 200)
        sg_g <- seq(0.05, 6 * s0 + 2, length.out = 200)
        p <- post_grid(mu_g, sg_g)
        mr <- span(mu_g, rowSums(p)); sr <- span(sg_g, colSums(p))
        mu_g <- seq(mr[1], mr[2], length.out = 200)
        sg_g <- seq(max(sr[1], 0.02), sr[2], length.out = 200)
        p <- post_grid(mu_g, sg_g)
        pm <- rowSums(p); ps <- colSums(p)
        e_mu <- sum(pm * mu_g); e_sg <- sum(ps * sg_g)
        q_of <- function(g, marg) approx(cumsum(marg), g, xout = c(0.025, 0.975), rule = 2)$y
        ### maximum likelihood for Cauchy(mu, sigma) with a Wald interval from the observed information
        ### (the interval for sigma is formed on the log scale and transformed back)
        nll <- function(th) -sum(dcauchy(y, th[1], exp(th[2]), log = TRUE))
        fit <- optim(c(median(y), log(s0)), nll, method = "BFGS", hessian = TRUE)
        se  <- tryCatch(sqrt(diag(solve(fit$hessian))), error = function(e) c(NA, NA))
        mle <- list(mu = fit$par[1], sg = exp(fit$par[2]), se_mu = se[1], se_sg = exp(fit$par[2]) * se[2],
                    ci_mu = fit$par[1] + c(-1, 1) * 1.96 * se[1],
                    ci_sg = exp(fit$par[2] + c(-1, 1) * 1.96 * se[2]))
        list(y = y, n = n, mu_g = mu_g, sg_g = sg_g, post = p, mle = mle,
             q_mu = q_of(mu_g, pm), q_sg = q_of(sg_g, ps),
             exact = c(mean_mu = e_mu, mean_sg = e_sg,
                       sd_mu = sqrt(sum(pm * (mu_g - e_mu)^2)), sd_sg = sqrt(sum(ps * (sg_g - e_sg)^2))))
    })

    rv <- reactiveValues(N = 500, t = 0, phase = 0, mu = NULL, sg = NULL, v = NULL,
                         cur_mu = 0, cur_sg = 1, path = NULL, np = 0, last = "", playing = FALSE)

    reset_run <- function() {
        N <- input$N
        rv$N <- N; rv$t <- 0; rv$phase <- 0
        rv$mu <- c(input$mu_init, rep(NA_real_, N)); rv$sg <- c(input$sig_init, rep(NA_real_, N))
        rv$cur_mu <- input$mu_init; rv$cur_sg <- input$sig_init
        rv$v <- NULL
        rv$path <- matrix(NA_real_, 3 * N + 2, 3)            # columns: mu, sigma, sub-step (0 start, 1 v, 2 mu, 3 sigma)
        rv$path[1, ] <- c(input$mu_init, input$sig_init, 0); rv$np <- 1
        rv$last <- "start"
        rv$playing <- FALSE
        updateActionButton(session, "play", label = "▶")
        set.seed(1000 + input$new)
    }

    add_path <- function(code) {
        rv$np <- rv$np + 1
        rv$path[rv$np, ] <- c(rv$cur_mu, rv$cur_sg, code)
    }

    ### one Gibbs sub-step: (1) the latent variances v_i, (2) mu, (3) sigma
    step_one <- function() {
        d <- dat(); y <- d$y; n <- d$n
        if (rv$t >= rv$N && rv$phase == 0) return(invisible(NULL))
        if (rv$phase == 0) {
            r2 <- (y - rv$cur_mu)^2 / rv$cur_sg^2
            rv$v <- 1 / rgamma(n, shape = 1, rate = (1 + r2) / 2)                 # v_i | mu, sigma, y_i ~ IG(1, (1 + r_i^2)/2)
            rv$phase <- 1; rv$last <- "v_i | mu, sigma"; add_path(1)
        } else if (rv$phase == 1) {
            prec <- 1 / tau^2 + sum(1 / (rv$cur_sg^2 * rv$v))
            mean <- (mu_0 / tau^2 + sum(y / (rv$cur_sg^2 * rv$v))) / prec
            rv$cur_mu <- rnorm(1, mean, 1 / sqrt(prec))                            # mu | v, sigma, y ~ normal
            rv$phase <- 2; rv$last <- "mu | v, sigma"; add_path(2)
        } else {
            rate <- b_0 + sum((y - rv$cur_mu)^2 / (2 * rv$v))
            rv$cur_sg <- sqrt(1 / rgamma(1, shape = a_0 + n / 2, rate = rate))     # sigma^2 | mu, v, y ~ inverse gamma
            rv$phase <- 0; rv$t <- rv$t + 1; rv$last <- "sigma | mu, v"; add_path(3)
            rv$mu[rv$t + 1] <- rv$cur_mu; rv$sg[rv$t + 1] <- rv$cur_sg
        }
    }
    step_iter <- function() {                       # finish the current iteration, or run a whole one
        repeat {
            step_one()
            if (rv$phase == 0 || rv$t >= rv$N) break
        }
    }
    finished <- function() rv$t >= rv$N && rv$phase == 0

    observeEvent(list(input$n_obs, input$mu_true, input$sig_true, input$N, input$mu_init, input$sig_init,
                      input$new, input$restart),
                 { req(input$N, input$mu_init, input$sig_init); reset_run() })

    observeEvent(input$play, {
        if (finished()) return()
        rv$playing <- !rv$playing
        updateActionButton(session, "play", label = if (rv$playing) "⏸" else "▶")
    })
    observeEvent(input$next_step, {
        rv$playing <- FALSE; updateActionButton(session, "play", label = "▶")
        if (isTRUE(input$sub)) step_one() else step_iter()
    })
    observeEvent(input$end, {
        rv$playing <- FALSE; updateActionButton(session, "play", label = "▶")
        while (!finished()) step_iter()
    })
    observe({
        if (isTRUE(rv$playing)) {
            invalidateLater(150, session)
            isolate({
                if (isTRUE(input$sub)) step_one() else step_iter()
                if (finished()) { rv$playing <- FALSE; updateActionButton(session, "play", label = "▶") }
            })
        }
    })

    output$status <- renderText({
        req(rv$mu)
        sprintf("iteration %d / %d; current (mu, sigma) = (%.3f, %.3f)", rv$t, rv$N, rv$cur_mu, rv$cur_sg)
    })

    ### the (mu, sigma) plane: exact posterior contours, the Gibbs draws, and optionally the path of each step
    output$plane <- renderPlot({
        req(rv$mu); d <- dat(); t <- rv$t
        ex <- d$exact                                          # the window is the exact posterior mean +- 3 sd, not the starting value
        xlim <- ex["mean_mu"] + c(-3, 3) * ex["sd_mu"]; ylim <- ex["mean_sg"] + c(-3, 3) * ex["sd_sg"]
        par(mar = c(4, 4, 3, 1))
        cols <- hcl.colors(30, "YlOrRd", rev = TRUE)
        plot(NA, xlim = xlim, ylim = ylim, xlab = expression(mu), ylab = expression(sigma),
             main = "Gibbs draws on the exact posterior")
        rect(par("usr")[1], par("usr")[3], par("usr")[2], par("usr")[4], col = cols[1], border = NA)
        image(d$mu_g, d$sg_g, d$post, col = cols, add = TRUE)
        contour(d$mu_g, d$sg_g, d$post, nlevels = 6, drawlabels = FALSE, add = TRUE, col = "gray40")
        if (t >= 1) points(rv$mu[2:(t + 1)], rv$sg[2:(t + 1)], pch = 19, cex = 0.4, col = adjustcolor("black", 0.45))
        points(input$mu_init, input$sig_init, pch = 17, col = "steelblue", cex = 1.4)
        if (isTRUE(input$sub) && rv$np >= 2) {
            k <- max(2, rv$np - 1):rv$np                                    # the last two sub-steps
            P <- rv$path
            for (j in k) {
                if (P[j, 3] == 2) arrows(P[j - 1, 1], P[j - 1, 2], P[j, 1], P[j, 2], length = 0.08, lwd = 2, col = "darkorange")
                if (P[j, 3] == 3) arrows(P[j - 1, 1], P[j - 1, 2], P[j, 1], P[j, 2], length = 0.08, lwd = 2, col = "steelblue")
                if (P[j, 3] == 1) points(P[j, 1], P[j, 2], pch = 1, cex = 2.2, lwd = 2, col = "forestgreen")
            }
        }
        points(rv$cur_mu, rv$cur_sg, pch = 19, cex = 1.3, col = "red")
        legend("topright", bty = "n", cex = 0.8, pch = c(19, 17, 19), col = c("black", "steelblue", "red"),
               legend = c("draws", "start", "current"))
    })

    ### the augmented variances v_i: outlying observations get large v_i, so they are downweighted
    output$vplot <- renderPlot({
        req(rv$mu); d <- dat(); par(mar = c(4, 4, 3, 1))
        if (is.null(rv$v)) {
            plot(d$y, rep(1, d$n), type = "n", log = "y", xlab = "y", ylab = expression(v[i]),
                 main = expression("latent variances"~v[i]~"(not drawn yet)"))
            rug(d$y)
        } else {
            plot(d$y, rv$v, log = "y", pch = 19, col = adjustcolor("forestgreen", 0.7), xlab = "y",
                 ylab = expression(v[i]), main = expression("latent variances"~v[i]~"(current)"))
            abline(v = rv$cur_mu, col = "red", lty = 2)
            legend("topright", bty = "n", cex = 0.8, lty = 2, col = "red", legend = expression(current~mu))
        }
    })

    trace_plot <- function(x, exact, sd, ylab) {
        par(mar = c(4, 4, 2, 1))
        plot(0:rv$N, x, type = "n", xlab = "iteration", ylab = ylab,
             ylim = exact + c(-3, 3) * sd)                                  # window around the posterior, not the start
        lines(0:rv$t, x[1:(rv$t + 1)], col = "gray30")
        abline(h = exact, col = "red", lty = 2)
    }
    output$tr_mu <- renderPlot({ req(rv$mu); d <- dat(); trace_plot(rv$mu, d$exact["mean_mu"], d$exact["sd_mu"], expression(mu)) })
    output$tr_sg <- renderPlot({ req(rv$mu); d <- dat(); trace_plot(rv$sg, d$exact["mean_sg"], d$exact["sd_sg"], expression(sigma)) })

    output$tab <- renderTable({
        req(rv$mu); d <- dat(); t <- rv$t; m <- d$mle
        burn <- floor(0.2 * t)
        idx <- if (t - burn >= 2) (burn + 2):(t + 1) else integer(0)
        f4  <- function(x) sprintf("%.4f", x)
        ci4 <- function(x) sprintf("(%.4f, %.4f)", x[1], x[2])
        gm <- function(x) if (length(idx)) f4(mean(x[idx])) else "-"
        gs <- function(x) if (length(idx)) f4(sd(x[idx])) else "-"
        gq <- function(x) if (length(idx)) ci4(quantile(x[idx], c(0.025, 0.975))) else "-"
        data.frame(
            ` ` = c("mu: mean / estimate", "mu: sd / SE", "mu: 95% interval",
                    "sigma: mean / estimate", "sigma: sd / SE", "sigma: 95% interval"),
            `Exact posterior` = c(f4(d$exact["mean_mu"]), f4(d$exact["sd_mu"]), ci4(d$q_mu),
                                  f4(d$exact["mean_sg"]), f4(d$exact["sd_sg"]), ci4(d$q_sg)),
            Gibbs = c(gm(rv$mu), gs(rv$mu), gq(rv$mu), gm(rv$sg), gs(rv$sg), gq(rv$sg)),
            MLE = c(f4(m$mu), f4(m$se_mu), ci4(m$ci_mu), f4(m$sg), f4(m$se_sg), ci4(m$ci_sg)),
            check.names = FALSE)
    }, striped = TRUE, align = "lrrr", width = "100%")
}

shinyApp(ui, server)

This app accompanies Markov Chain Monte Carlo in the book.