Skip to content

Instantly share code, notes, and snippets.

@eliardocosta
Last active December 2, 2020 19:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save eliardocosta/85781d93cbaae35411eed74372c7c2d4 to your computer and use it in GitHub Desktop.
Save eliardocosta/85781d93cbaae35411eed74372c7c2d4 to your computer and use it in GitHub Desktop.
The R codes to implement the illustrative example in Costa, Paulino & Singer (2020).

Description

These are the R codes to implement the illustrative example in Costa, Paulino & Singer (2020, submitted).

License

The MIT License (MIT)

Copyright (c) 2020 Eliardo G. Costa, Carlos Daniel Paulino & Julio M. Singer

Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
# Bayesian sample size NB/gamma model
bss.dt.nbgam <- function(lf, lam0, theta0, phi, w, c, rho = NULL, gam = NULL,
nrep = 1E1, lrep = 1E2, npost, ns,
plot = TRUE, burnin, thin, path, case, ...) {
cl <- match.call()
#ns <- c(1, seq(5, nmax, by = nlag))
risk <- numeric()
out.accept <- numeric()
if (lf == 1) {
for (n in ns) {
accept <- numeric()
for (i in 1:nrep) {
loss <- numeric()
for (j in 1:lrep) {
lam <- stats::rgamma(1, shape = theta0, rate = theta0/lam0)
x <- stats::rnbinom(n, mu = w*lam, size = phi)
lampos <- rlam.nbgam(N = npost, x = x, phi = phi, lam0 = lam0,
theta0 = theta0, w = w, burnin = burnin,
thin = thin)
if (n == 5 && j == 1) {
graph_name <- paste(path, "diag", case, ".pdf", sep = "")
pdf(graph_name)
par(mfrow = c(2, 1))
plot.ts(lampos$lam)
acf(lampos$lam)
dev.off()
par(mfrow = c(1, 1))
}
qs <- quantile(lampos$lam, probs = c(rho/2, 1 - rho/2))
loss <- append(loss, sum(lampos$lam[which(lampos$lam > qs[2])])/npost - sum(lampos$lam[which(lampos$lam < qs[1])])/npost + c*n)
accept <- append(accept, lampos$accept)
}
risk <- append(risk, mean(loss))
}
out.accept <- append(out.accept, mean(accept))
}
} else if (lf == 2){
for (n in ns) {
accept <- numeric()
for (i in 1:nrep) {
loss <- numeric()
for (j in 1:lrep) {
lam <- stats::rgamma(1, shape = theta0, rate = theta0/lam0)
x <- stats::rnbinom(n, mu = w*lam, size = phi)
lampos <- rlam.nbgam(N = npost, x = x, phi = phi, lam0 = lam0,
theta0 = theta0, w = w, burnin = burnin,
thin = thin)
if (n == 5 && j == 1) {
graph_name <- paste(path, "diag", case, ".pdf", sep = "")
pdf(graph_name)
par(mfrow = c(2, 1))
plot.ts(lampos$lam)
acf(lampos$lam)
dev.off()
par(mfrow = c(1, 1))
}
varpos <- var(lampos$lam)
loss <- append(loss, 2*sqrt(gam*varpos) + c*n)
accept <- append(accept, lampos$accept)
}
risk <- append(risk, mean(loss))
}
out.accept <- append(out.accept, mean(accept))
}
}
Y <- log(risk - c*rep(ns, each = nrep))
mod <- stats::lm(Y ~ I(log(rep(ns + 1, each = nrep))))
E <- as.numeric(exp(mod$coef[1]))
G <- as.numeric(-mod$coef[2])
nmin <- ceiling((E*G/c)^(1/(G + 1))-1)
risk.mean <- apply(matrix(risk, nrep, length(ns)), 2, mean)
#ns.mod <- rep(ns, each = nrep)
if (plot == TRUE) {
graph_name <- paste(path, "case", case, ".pdf", sep = "")
pdf(graph_name)
plot(rep(ns, each = nrep), risk, xlim = c(0, max(ns) + 1),
ylim = c(0, max(risk) + 0.5),
xlab = "n", ylab = "TC(n)")
curve <- function(x) {c*x + E/(1 + x)^G}
plot(function(x)curve(x), 0, max(ns) + 1, col = "blue",
add = TRUE)
graphics::abline(v = nmin, col = "red")
# graphics::abline(v = ns[which.min(risk.mean)], col = "yellow")
dev.off()
}
# Output
cat("\nCall:\n")
print(cl)
cat("\nSample size:\n")
cat("n = ", nmin, " by fitting (red line)\n")
cat("---------------\n")
cat("n = ", ns[which.min(risk.mean)], " by inspection (yellow line)\n")
cat("---------------\n")
cat("accept = ", mean(out.accept), "\n")
}
# Computing the optimal sample size - illustrative example
source("https://gist.githubusercontent.com/eliardocosta/85781d93cbaae35411eed74372c7c2d4/raw/bad359ccf8690bc0e2aadc790609200914d63d9a/bss.dt.nbgam.R")
path <- getwd()
gam <- 1
w <- 1
phi <- 8
c <- 0.01
lam0 <- 10
eps <- 2 # prior var = eps^2 = 4
theta0 <- (lam0/eps)^2; theta0
case <- 1
ns <- c(1, 3, seq(5, 200, by = 2))
bss.dt.nbgam(lf = 2, lam0 = lam0, theta0 = theta0, phi = phi,
w = w, c = c, gam = gam, plot = TRUE,
nrep = 3, lrep = 1E2, ns = ns, npost = 9E2,
path = path, case = case, burnin = 1E2, thin = 10)
# NEGATIVE BINOMIAL/GAMMA MODEL
# COVERAGE COMPUTED EXAMPLE
# GAMMA = 1 AND W = 1
rm(list = ls())
library(xtable)
library(LearnBayes)
source("https://gist.githubusercontent.com/eliardocosta/85781d93cbaae35411eed74372c7c2d4/raw/9e0703312f1d83f69f91d7685829533e3ffc90a4/logp.nbgam.R")
source("https://gist.githubusercontent.com/eliardocosta/85781d93cbaae35411eed74372c7c2d4/raw/9e0703312f1d83f69f91d7685829533e3ffc90a4/rlam.nbgam.R")
gam <- 1
w <- 1
phi <- 8
lam0 <- 10
eps <- 2 # prior var = eps^2 = 4
theta0 <- (lam0/eps)^2; theta0
#----------------------------------------------------------
#-- LAMBDA = 7
#---------------
# c = 0.01
# SIMULATING THE COUNTS
seed <- 123456
n <- 51 # Table 2
lamR <- 7 # real concentration
set.seed(seed)
counts <- rnbinom(n, mu = w*lamR, size = phi); counts
sum(counts) # 319
hist(counts, prob = TRUE)
print(xtable(matrix(c(counts, NA), 4, 13, byrow = TRUE),
digits = 0), include.rownames = FALSE,
include.colnames = FALSE)
x <- counts
set.seed(seed)
lampos1 <- rlam.nbgam(N = 1E4, x = x, phi = phi,
lam0 = lam0, theta0 = theta0,
w = w, burnin = 1E3, thin = 10)
round(lampos1$accept, 2) # acceptance rate ~ 0.48
par(mfrow = c(2, 1))
plot.ts(lampos1$lam, xlab = "iteration", ylab = "") # traceplot
acf(lampos1$lam, main = "") # ACF
medpos <- mean(lampos1$lam)
varpos <- var(lampos1$lam)
a <- medpos - sqrt(varpos/gam); round(a, 2) # 6.10
b <- medpos + sqrt(varpos/gam); round(b, 2) # 7.05
# coverage probability ~ 0.68
count <- 0
for (k in 1:length(lampos1$lam)) {
if (lampos1$lam[k] >= a && lampos1$lam[k] <= b) count <- count + 1
}
count/length(lampos1$lam) # cov. probability
#----------------------------------------------------------
#-- LAMBDA = 10
#---------------
# c = 0.01
# SIMULATING THE COUNTS
seed <- 123456
n <- 51 # Table 2
lamR <- 10 # real concentration
set.seed(seed)
counts <- rnbinom(n, mu = w*lamR, size = phi); counts
sum(counts) # 523
par(mfrow = c(1, 1))
hist(counts, prob = TRUE)
print(xtable(matrix(c(counts, NA), 4, 13, byrow = TRUE),
digits = 0), include.rownames = FALSE,
include.colnames = FALSE)
x <- counts
set.seed(seed)
lampos2 <- rlam.nbgam(N = 1E4, x = x, phi = phi,
lam0 = lam0, theta0 = theta0,
w = w, burnin = 1E3, thin = 10)
round(lampos2$accept, 2) # acceptance rate ~ 0.58
par(mfrow = c(2, 1))
plot.ts(lampos2$lam, xlab = "iteration", ylab = "") # traceplot
acf(lampos2$lam, main = "") # ACF
medpos <- mean(lampos2$lam)
varpos <- var(lampos2$lam)
a <- medpos - sqrt(varpos/gam); round(a, 2) # 9.61
b <- medpos + sqrt(varpos/gam); round(b, 2) # 10.89
# coverage probability ~ 0.68
count <- 0
for (k in 1:length(lampos2$lam)) {
if (lampos2$lam[k] >= a && lampos2$lam[k] <= b) count <- count + 1
}
count/length(lampos2$lam) # cov. probability
#----------------------------------------------------------
#-- LAMBDA = 13
#---------------
# c = 0.01
# SIMULATING THE COUNTS
seed <- 123456
n <- 51 # Table 2
lamR <- 13 # real concentration
set.seed(seed)
counts <- rnbinom(n, mu = w*lamR, size = phi); counts
sum(counts) # 641
par(mfrow = c(1, 1))
hist(counts, prob = TRUE)
print(xtable(matrix(c(counts, NA), 4, 13, byrow = TRUE),
digits = 0), include.rownames = FALSE,
include.colnames = FALSE)
x <- counts
set.seed(seed)
lampos3 <- rlam.nbgam(N = 1E4, x = x, phi = phi,
lam0 = lam0, theta0 = theta0,
w = w, burnin = 1E3, thin = 10)
round(lampos3$accept, 2) # acceptance rate ~ 0.62
par(mfrow = c(2, 1))
plot.ts(lampos3$lam, xlab = "iteration", ylab = "") # traceplot
acf(lampos3$lam, main = "") # ACF
medpos <- mean(lampos3$lam)
varpos <- var(lampos3$lam)
a <- medpos - sqrt(varpos/gam); round(a, 2) # 11.58
b <- medpos + sqrt(varpos/gam); round(b, 2) # 13.04
# coverage probability ~ 0.68
count <- 0
for (k in 1:length(lampos3$lam)) {
if (lampos3$lam[k] >= a && lampos3$lam[k] <= b) count <- count + 1
}
count/length(lampos3$lam) # cov. probability
# log-posterior NB/gamma
logp.nbgam <- function(lam, lam0, theta0, x, phi, w) {
n <- length(x)
sn <- sum(x)
if (lam > 0) {
out <- (theta0 + sn - 1)*log(lam) - (sn + n*phi)*log(1 + w*lam/phi) - theta0*lam/lam0
} else {
out <- -Inf
}
return(out)
}
# sampling from the posterior
rlam.nbgam <- function(N, x, phi, lam0, theta0, w, burnin, thin,
scale = 1, varcov = diag(1)) {
varcov <- varcov
prop <- list(var = varcov, scale = scale) # parametros da dist. proposta
start <- mean(x) # valores iniciais
sam.post <- rwmetrop(logp.nbgam, prop, start, m = burnin + N*thin,
lam0 = lam0, theta0 = theta0, x = x, phi = phi, w = w)
lam <- as.vector(sam.post$par[burnin + (1:N)*thin,])
out <- list(lam = lam, accept = sam.post$accept)
return(out)
}
#rlam.nbgam(N = 1E3, x = x, phi = 1, lam0 = 10, theta0 = 2, w = 1, thin = 10)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment