## Clear environment rm(list = ls()) ## Load packages library(tidyverse) library(pracma) # trapezoidal integration (Q4.4) ## Set working directory setwd("~/SP/A2") ## Additional functions that are useful for type checking # Check if argument is scalar is.scalar <- function(x) is.atomic(x) && length(x) == 1L && !is.character(x) && Im(x) == 0 # Check if argument is string is.string <- function(x) is.character(x) && length(x) == 1 # Check if argument is integer check.integer <- function(x) is.scalar(x) && round(x) == x ## Reading data load("burlington.RData") ## ls() ## see contents of ## ## burlington object ## -------------------------------------------------- ## -------------------------------------------------- ## ;; ## --------------------------------------------- ## Q1: -- add your code below ## --------------------------------------------- ## ;; ## Data for Q1 data <- list(lsat = c(576, 635, 558, 578, 666, 580, 555, 661, 651, 605, 653, 575,545, 572, 594), gpa = c(3.39, 3.30, 2.81, 3.03, 3.55, 3.07, 3.00, 3.43, 3.36, 3.13, 3.12, 2.74, 2.76, 2.88, 2.96), n = 15) ## 1.1 bootstrap.ci <- function(theta.star, theta = NULL, method = "basic", conf.level = 0.95) { # Determines the bootstrap confidence interval of parameter # theta using the basic bootstrap interval method or the # percentile interval method. # # Args: # theta.star: Sequence of statistic computed from resampling (numeric). # theta: Statistic computed from sample. (scalar) # Only required if method = "basic". # method: Whether to use "basic" bootstrap interval or # "percentile" interval methods (string). # conf.level: Confidence level (0, 1) (scalar). # # Returns: # Confidence interval (numeric). # Argument checking stopifnot(is.numeric(theta.star), is.string(method), is.scalar(conf.level), conf.level > 0, conf.level < 1) alpha.half = (1 - conf.level) / 2 if (method == "basic") { stopifnot(is.scalar(theta)) ci <- 2 * theta - quantile(theta.star, c(1 - alpha.half, alpha.half)) } else if (method == "percentile") { ci <- quantile(theta.star, c(alpha.half, 1 - alpha.half)) } else { stop("Invalid method. Use 'basic' or 'percentile'.") } names(ci) <- c("lower", "upper") return(ci) } CI.cor <- function(x1, x2, R = 10000, conf.level = 0.95) { # Computes the 95% bootstrap confidence intervals for the # correlation parameter using the basic bootstrap interval # method and the percentile interval method. # # Args: # x1: Sequence of observations from variable 1 (numeric). # x2: Sequence of bservations from variable 2 (numeric). # R: Number of bootstrap replicates (positive integer) # conf.level: Confidence level (0, 1) (scalar). # 0.95 (95%) by default. # # Returns: # Confidence intervals on the correlation between x1 and x2. # Matrix 2x2, where first row corresponds to the the basic # bootstrap interval and the second to the percentile # interval method. # # Notes: # Check bootstrap.ci. # Argument checking stopifnot(is.numeric(x1), is.numeric(x2), check.integer(R), R > 0, is.scalar(conf.level), conf.level > 0, conf.level < 1) n <- length(x1) # sample size stopifnot(n == length(x2)) # Store variables columnwise X <- cbind(x1 = x1, x2 = x2) # Compute correlation for bootstrap samples rho.star <- sapply(1:R, function(a) X[sample(n, n, replace = TRUE), ] %>% cor %>% .[1, 2]) # Compute correlation for the sample rho <- cor(X)[1, 2] # Compute confidence intervals using both methods rho.ci.basic <- bootstrap.ci(rho.star, rho, method = "basic", conf.level = conf.level) rho.ci.percentile <- bootstrap.ci(rho.star, method = "percentile", conf.level = conf.level) return(rbind(basic = rho.ci.basic, percentile = rho.ci.percentile)) } # Apply function to score data set.seed(13) score.ci.cor <- CI.cor(data$lsat, data$gpa) score.ci.cor ## 1.2 CI.var.ratio <- function(x1, x2, R = 10000, conf.level = 0.95) { # Computes the 95% bootstrap confidence intervals for the # variance ratio, i.e. var(x1)/var(x2), using the basic # bootstrap interval method and the percentile interval # method. # # Args: # x1: Sequence of observations from variable 1 (numeric). # x2: Sequence of observations from variable 2 (numeric). # R: Number of bootstrap replicates (positive integer) # conf.level: Confidence level (0, 1) (scalar). # 0.95 (95%) by default. # # Returns: # Confidence intervals on the variance ratio between x1 and # x2. Matrix 2x2, where first row corresponds to the basic # bootstrap interval and the second to the percentile # interval method. # # Notes: # Check bootstrap.ci. # Argument checking stopifnot(is.numeric(x1), is.numeric(x2), check.integer(R), R > 0, is.scalar(conf.level), conf.level > 0, conf.level < 1) n <- length(x1) # sample size stopifnot(n == length(x2)) # Store variables columnwise X <- cbind(x1 = x1, x2 = x2) # Compute variance for bootstrap samples var.star <- sapply(1:R, function(a) X[sample(n, n, replace = TRUE), ] %>% apply(2, var)) # Compute the variance ratio for bootsrap samples rvar.star <- var.star[1, ] / var.star[2, ] # Compute the variance ratio for the sample rvar <- apply(X, 2, var) # compute variance first (columnwise) rvar <- rvar[1] / rvar[2] # Compute confidence intervals using both methods rvar.ci.basic <- bootstrap.ci(rvar.star, rvar, method = "basic", conf.level = conf.level) rvar.ci.percentile <- bootstrap.ci(rvar.star, method = "percentile", conf.level = conf.level) return(rbind(basic = rvar.ci.basic, percentile = rvar.ci.percentile)) } # Apply function to score data set.seed(13) score.ci.var.ratio <- CI.var.ratio(data$lsat, data$gpa) score.ci.var.ratio ## ;; ## ------------------------------------------- ## Q2: -- add your code below ## ------------------------------------------- ## ;; # Fit generalized Pareto distribution by maximum likelihood fit.gpd <- function(x, thresh, tol.xi.limit = 5e-2, ...) { llik.gpd <- function(par, x, thresh, tol.xi.limit = 5e-2) { y <- x[x>thresh] sigma <- exp(par[1]) xi <- par[2] n <- length(y) if(abs(xi)<=tol.xi.limit) { llik <- n*log(sigma) + sum((y-thresh)/sigma) return(llik) } par.log.max <- log( pmax( 1+xi*(y-thresh)/sigma, 0 ) ) llik <- -n*log( sigma )-(1+( 1/xi ))*sum( par.log.max ) llik <- -ifelse( llik > -Inf, llik, -1e40 ) return(llik) } fit <- optim(par = c(0, 0), fn = llik.gpd, x=x, thresh=thresh, control=list( maxit=10000, ... )) sigmahat <- exp( fit$par[1] ) xihat <- fit$par[2] return(c(sigmahat, xihat)) } fit.gpd(x=burlington$Precipitation, thresh=quantile(burlington$Precipitation,0.8)) ## 2.1 rgpd <- function(n, thresh, sigma, xi, tol.xi.limit = 5e-2) { # Draws samples from generalized Pareto distribution using # Inverse Transform Sampling. # # Args: # n: Number of samples (positive integer) # thresh: Threshold, location parameter (scalar). # sigma: Scale parameter (positive scalar). # xi: Shape parameter (scalar). # tol.xi.limit: Tolerance factor for xi (positive scalar). # # Returns: # Samples from generalized Pareto. # Argument checking stopifnot(check.integer(n), n > 0, is.scalar(thresh), is.scalar(sigma), sigma > 0, is.scalar(xi), is.scalar(tol.xi.limit), tol.xi.limit > 0) # Draw uniform samples u <- runif(n) if (abs(xi) < tol.xi.limit) { # limit case: xi -> 0 x <- thresh - sigma * log(u) } else { x <- thresh + sigma / xi * (u ^ -xi - 1) } return(x) } parboot.gpd <- function(x, thresh, R = 1000) { # Performs parametric bootstrap (generalized Pareto). # # Args: # x: Sequence of raw observations (numeric). # thresh: Value at which observations become excesses (scalar). # R: Bootstrap size (positive integer). # # Returns: # Named list with # - mle: Vector containing maximum likelihood (ML) estimates of # parameters sigma, xi, pu. # - distn: Matrix Rx3 with the corresponding bootstrap distribution. # - bias: Vector containing the corresponding estimated bias. # - se: Vector containing the corresponding standard error. # Argument checking stopifnot(is.numeric(x), is.scalar(thresh), check.integer(R), R > 0) res = list() n <- length(x) # Obtain ML estimates par.hat <- fit.gpd(x, thresh) pu.hat <- sum(x > thresh) / n res$mle <- c(par.hat, pu.hat) names(res$mle) <- c("sigma", "xi", "pu") # Simulate number of exceedances from Binomial(n, puhat) - R times nu.star <- rbinom(R, n, pu.hat) pu.star <- nu.star / n # Simulate from the fitted generalized Pareto model samples.gpd <- lapply(nu.star, rgpd, thresh = thresh, sigma = par.hat[1], xi = par.hat[2]) # Determine bootstrap distribution, corresponding bias and standard error res$distn <- sapply(samples.gpd, fit.gpd, thresh = thresh) %>% t %>% cbind(., pu.star) colnames(res$distn) <- c("sigma", "xi", "pu") res$bias <- apply(res$distn, 2, mean) - res$mle res$se <- apply(res$distn, 2, sd) return(res) } set.seed(13) x <- burlington$Precipitation res.par <- parboot.gpd(x, quantile(x, 0.9)) ## 2.2 npboot.gpd <- function(x, thresh, R = 1000) { # Performs non-parametric bootstrap (generalized Pareto). # # Args: # x: Sequence of raw observations (numeric). # thresh: Value at which observations become excesses (scalar). # R: Bootstrap size (positive integer). # # Returns: # Named list with # - mle: Vector containing maximum likelihood (ML) estimates of # parameters sigma, xi, pu. # - distn: Matrix Rx3 with the corresponding bootstrap distribution. # - bias: Vector containing the corresponding estimated bias. # - se: Vector containing the corresponding standard error. # Argument checking stopifnot(is.numeric(x), is.scalar(thresh), check.integer(R), R > 0) res = list() n <- length(x) # Obtain ML estimates par.hat <- fit.gpd(x, thresh) pu.hat <- sum(x > thresh) / n res$mle <- c(par.hat, pu.hat) names(res$mle) <- c("sigma", "xi", "pu") # Simulate from empirical distribution samples <- matrix(sample(x, size = n * R, replace = TRUE), nrow = R, ncol = n) pu.star <- apply(samples, 1, function (z) sum(z > thresh)) / n # Determine bootstrap distribution, corresponding bias and standard error res$distn <- apply(samples, 1, fit.gpd, thresh = thresh) %>% t %>% cbind(., pu.star) colnames(res$distn) <- c("sigma", "xi", "pu") res$bias <- apply(res$distn, 2, mean) - res$mle res$se <- apply(res$distn, 2, sd) return(res) } set.seed(13) x <- burlington$Precipitation res.npar<- npboot.gpd(x, quantile(x, 0.9)) ## 2.3 CI.ret.levels <- function(x, thresh = NULL, T = c(100, 500, 1000, 10000), R = 10000, bmethod = "par", conf.level = 0.95) { # Determines confidence intervals of return levels using the # generalized Pareto model via bootstrap (percentile method). # # Args: # x: Sequence of raw observations (numeric). # thresh: Value at which observations become excesses (scalar). # Use 90% empirical quantile by default. # T: Sequence of return periods (numeric). # R: Bootstrap size (positive integer). # bmethod: Whether to use parametric ("par") or non-parametric ("npar") # bootstrapping (string). # conf.level: Confidence level (0, 1) (scalar). # 0.95 (95%) by default. # # Returns: # Named list with # - dist: Matrix Rxlength(T) with the bootstrap distribution of return # levels (1 column per return period). # - ci: Matrix 2xlength(T) with the corresponding confidence intervals # estimated using the percentile method. # # Notes: # Check parboot.gpd, npboot.gpd and bootstrap.ci. # Argument checking stopifnot(is.numeric(x), is.numeric(T), check.integer(R), R > 0, is.string(bmethod), is.scalar(conf.level), conf.level > 0, conf.level < 1) if (is.null(thresh)) { thresh <- quantile(x, 0.9) } stopifnot(is.scalar(thresh)) # Bootstrap distribution (parametric or non-parametric) if (bmethod == "par") { distn <- parboot.gpd(x, thresh, R)$distn } else if (bmethod == "npar") { distn <- npboot.gpd(x, thresh, R)$distn } else { stop("Invalid bootstrap method. Use 'par' or 'npar'.") } # Define auxiliary function : compute return level estimate given parameter # vector p (sigma, xi, pu) for all periods T (fixed) and thresh (fixed) ret.level <- function(p) thresh + p[1] / p[2] * ((T * p[3]) ^ p[2] - 1) # Apply aux. function to get distribution over return levels dist.ret.level <- apply(distn, 1, ret.level) ci.ret.level <- apply(dist.ret.level, 1, bootstrap.ci, method = "percentile", conf.level = conf.level) colnames(ci.ret.level) <- T rownames(dist.ret.level) <- T return(list(dist = t(dist.ret.level), ci = ci.ret.level)) } set.seed(13) x <- burlington$Precipitation res.par.ret.level <- CI.ret.levels(x, R=1000, bmethod = "par") res.npar.ret.level <- CI.ret.levels(x, bmethod = "npar") ## ;; ## ------------------------------------------- ## Q3: -- add your code below ;; ## ------------------------------------------- ## ;; pumps <- list(t = c(94.3, 15.7, 62.9, 126, 5.24, 31.4, 1.05, 1.05, 2.1, 10.5), x = c(5, 1, 5, 14, 3, 19, 1, 1, 4, 22), n = 10) ## 3.1 # See pdf for answer. ## 3.2 mcmc.pumps <- function(x, t, nburn = 10000, ndraw = 100000, gamma = 0.01, delta = 0.01, lambda = 1, update.var = 1) { # Samples from the posterior distribution given by the hierarchical model with # Poisson likelihood, Gamma prior on theta_i|alpha,beta, # Exponential hyperprior on alpha and Gamma hyperprior on beta. # log alpha is updated via random walk Metropolis. # # Args: # x: Sequence of observed failures (numeric). # t: Sequence of operation times (numeric). # nburn: Number of initial samples to discard (positive integer). # ndraw: Number of iterations, after nburn (positive integer). # gamma: Hyperparameter 1 (Gamma: shape) of beta (positive scalar). # delta: Hyperparameter 2 (Gamma: rate) of beta (positive scalar). # lambda: Hyperparameter (Exponential: rate) of alpha (positive scalar). # update.var: Variance of normal increments in Metropolis (positive scalar). # # Returns: # Named list with: # - draws: Matrix (n+2) x ndraw containing the posterior samples # (theta, beta, alpha). # - accept.ratio: Probability of accepting the (log) alpha proposals. # # Notes: # log(.) is a monotonic function, hence # p(log.alpha | ...) = p(alpha | ...) * | d log.alpha / d alpha | ^ -1 # p(log.alpha | ...) = p(alpha | ...) * alpha # log p(log.alpha | ...) = log p(alpha | ...) + log.alpha # Argument checking stopifnot(is.numeric(x), is.numeric(t), length(x) == length(t), check.integer(nburn), check.integer(ndraw), nburn >= 0, ndraw > 0) stopifnot(is.scalar(gamma), gamma > 0, is.scalar(delta), delta > 0, is.scalar(lambda), lambda > 0, is.scalar(update.var), update.var > 0) n <- length(x) # number of pumps # Initialize matrix that will hold the samples from the posterior draws <- matrix(nrow = ndraw, ncol = n + 2) # theta (n), beta, alpha # Other initializations: counters, parameters accept.alpha <- 0 iter <- -nburn beta <- rgamma(1, gamma, delta) # draw from hyperprior alpha <- rexp(1, lambda) # draw from hyperprior log.alpha <- log(alpha) update.std <- sqrt(update.var) while(iter < ndraw) { iter <- iter + 1 # Update theta theta <- rgamma(n, alpha + x, beta + t) # Update beta beta <- rgamma(1, gamma + n * alpha, delta + sum(theta)) # Update alpha log.alpha.prop <- rnorm(1, log.alpha, update.std) # log.alpha proposal ap <- exp(log.alpha.prop) da <- ap - alpha log.aratio <- n * (da * log(beta) - log(gamma(ap)) + log(gamma(alpha))) + da * (sum(log(theta)) - lambda) + log.alpha.prop - log.alpha u <- runif(1, 0, 1) if(log(u) <= log.aratio) { # if proposal is accepted accept.alpha <- accept.alpha + 1 log.alpha <- log.alpha.prop alpha <- exp(log.alpha) } if(iter > 0) { # if not burn-in samples draws[iter, 1:n] <- theta draws[iter, n + 1] <- beta draws[iter, n + 2] <- alpha # store alpha, not log.alpha } } return(list(draws = draws, accept.ratio = accept.alpha / (nburn + ndraw))) } set.seed(13) res.mcmc.pumps <- mcmc.pumps(pumps$x, pumps$t) res.mcmc.pumps$accept.ratio apply(res.mcmc.pumps$draws, 2, mean) # posterior mean estimates ## 3.3 predictive.pumps <- function(t.star, x, t, ..., grid = NULL) { # Estimates the predictive distribution of failures using the same model as # in mcmc.pumps. The integral is approximated via Monte Carlo. # # Args: # t.star: Sequence of future operation times (numeric). # x: Sequence of observed failures (numeric). # t: Sequence of observed operation times (numeric). # grid: Sequence of locations where predictive densities will be evaluated # (numeric). Optional. # additional arguments are passed to mcmc.pumps # # Returns: # Named list with: # - grid: Sequence of locations where predictive densities have # been evaluated. # - dist: Matrix length(grid) x length(x) containing the predictive # densities. # # Notes: # Check mcmc.pumps. # Argument checking stopifnot(is.numeric(t.star), is.numeric(x), is.numeric(t), length(t.star) == length(x), length(x) == length(t)) n <- length(x) # number of pumps # Get samples from posterior theta pi.theta <- mcmc.pumps(x, t, ...)$draws[, 1:n] # ndraw x n # Determine corresponding rates (Poisson likelihood) pi.lambda <- t(apply(pi.theta, 1, function(z) z * t.star)) # Specify grid of locations, if not provided if (is.null(grid)) { grid <- 0:(5 * ceil(max(x * t.star / t))) } stopifnot(is.numeric(grid)) # Compute likelihood: list of matrices, each evaluated at a given point vlik <- sapply(grid, function(z) dpois(z, pi.lambda), simplify = FALSE) # Estimate predictive densities dist <- t(sapply(vlik, function(z) apply(z, 2, mean))) return(list(grid = grid, dist = dist, pi.lambda = pi.lambda)) } set.seed(13) res.pumps.pred <- predictive.pumps(2 * pumps$t, pumps$x, pumps$t, nburn = 1000, ndraw = 10000) #plot(res.pumps.pred$grid, res.pumps.pred$dist[, 1], type = 'l') ## ;; ## ------------------------------------------- ## Q4: -- add your code below;; ## ------------------------------------------- ## ;; ## 4.1 mcmc.t <- function(x, nu = 10, nburn = 1000, ndraw = 10000, update.var = 1) { # Samples from the posterior distribution (mu) using random walk Metropolis. # # Args: # x: Sequence of observed values, iid t-distribution (numeric). # nu: Degrees of freedom in t-distribution (positive scalar). # nburn: Number of initial samples to discard (positive integer). # ndraw: Number of iterations, after nburn (positive integer). # update.var: Variance of normal increments in Metropolis (positive scalar). # # Returns: # Named list with: # - draws: Sequence containing the posterior samples from mu. # - accept.ratio: Probability of accepting the mu proposals. # # Argument checking stopifnot(is.numeric(x), is.scalar(nu), nu > 0, check.integer(nburn), nburn >= 0, check.integer(ndraw), ndraw > 0, is.scalar(update.var), update.var > 0) # Initialize vector that will hold posterior samples of mu (location) draws <- numeric(ndraw) # Other initializations: counters, parameters accept <- 0 iter <- -nburn mu <- rnorm(1) # draw from prior (standard normal) update.std <- sqrt(update.var) while(iter < ndraw) { iter <- iter + 1 # Update mu mu.prop <- rnorm(1, mu, update.std) A <- sapply(c(mu.prop, mu), function(z) sum(log(1 + 1 / nu * (x - z) ^ 2))) log.aratio <- 0.5 * ((nu + 1) * diff(A) - (mu.prop ^ 2 - mu ^ 2)) # diff in this case computes A[2] - A[1], hence the missing # minus sign in the first term u <- runif(1, 0, 1) if(log(u) <= log.aratio) { # if proposal is accepted accept <- accept + 1 mu <- mu.prop } if(iter > 0) { # if not burn-in samples draws[iter] <- mu } } return(list(draws = draws, accept.ratio = accept / (nburn + ndraw))) } # Checking answer set.seed(13) nu = 10 n <- 1000 ndraw <- 10000 mu <- 3 x <- rt(n, df = nu) + mu res.mcmc.t <- mcmc.t(x, nburn = 0, ndraw = ndraw, nu = nu, update.var = 0.01) res.mcmc.t$accept.ratio plot(res.mcmc.t$draws, type = "l") nburn <- 1000 mean(res.mcmc.t$draws[(nburn+1):ndraw]) ## 4.2 mcmc.gibbs <- function(x, nu = 10, nburn = 1000, ndraw = 10000) { # Samples from the posterior distribution (mu) using Gibbs. # # Args: # x: Sequence of observed values, iid t-distribution (numeric). # nu: Degrees of freedom in t-distribution (positive scalar). # nburn: Number of initial samples to discard (positive integer). # ndraw: Number of iterations, after nburn (positive integer). # # Returns: # Named list with: # - draws: Sequence containing the posterior samples from mu. # Argument checking stopifnot(is.numeric(x), is.scalar(nu), nu > 0, check.integer(nburn), nburn >= 0, check.integer(ndraw), ndraw > 0) # Initialize vector that will hold posterior samples of mu (location) draws <- numeric(ndraw) # Other initializations: counters, parameters accept <- 0 iter <- -nburn mu <- rnorm(1) # draw from prior (standard normal) n <- length(x) while(iter < ndraw) { iter <- iter + 1 # Update z z <- rgamma(n, 0.5 * (nu + 1), 0.5 * (nu + (x - mu) ^ 2)) # Update mu sumz = sum(z) mu <- rnorm(1, z %*% x / (1 + sumz), (1 + sumz) ^ -0.5) if(iter > 0) { # if not burn-in samples draws[iter] <- mu } } return(list(draws = draws)) } # Checking answer set.seed(13) nu = 10 n <- 1000 ndraw <- 10000 mu <- 3 x <- rt(n, df = nu) + mu res.mcmc.gibbs <- mcmc.gibbs(x, nburn = 0, ndraw = ndraw, nu = nu) plot(res.mcmc.gibbs$draws, type = "l") nburn <- 1000 mean(res.mcmc.gibbs$draws[(nburn+1):ndraw]) ## 4.3 predictive.t <- function(x, nu = 10, ..., grid = NULL, method = "gibbs") { # Estimates the predictive density of a future t-distributed observable. # This density is found by Monte Carlo integration. # # Args: # x: Sequence of observed values, iid t-distribution (numeric). # nu: Degrees of freedom in t-distribution (positive scalar). # grid: Sequence of locations where predictive density will be evaluated # (numeric). Optional. # method: Whether to approximate the posterior mu using Gibbs ("gibbs") # or Metropolis ("metropolis") (string). # additional arguments are passed to mcmc.t or mcmc.gibbs depending # on the method that has been selected. # # Returns: # Named list with: # - grid: Sequence of locations where predictive density has # been evaluated. # - dist: Numeric containing the predictive density. # # Notes: # Check mcmc.t and mcmc.gibbs. # Argument checking stopifnot(is.numeric(x), is.scalar(nu), nu > 0, is.string(method)) # Determine which method to use if (method == "metropolis") { f = mcmc.t } else if (method == "gibbs") { f = mcmc.gibbs } else { stop("Invalid method. Use 'metropolis' or 'gibbs'.") } # Get samples from posterior pi.mu <- f(x, ..., nu = nu)$draws # Determine grid of locations, if not provided if (is.null(grid)) { grid = mean(pi.mu) + seq(-10, 10, len = 10000) } stopifnot(is.numeric(grid)) # Estimate predictive density (student-t likelihood) # 1/N * sum_i f(x.star | pi.mu[i]), for all x.star in grid dist <- sapply(grid, function(z) mean(dt(z - pi.mu, df = nu))) return(list(grid = grid, dist = dist)) } # Checking answer set.seed(13) nu <- 10 n <- 1000 mu <- 3 method <- "gibbs" # "metropolis" or "gibbs" x <- rt(n, df = nu) + mu res.predictive.t <- predictive.t(x, nu = nu, method = method) plot(res.predictive.t$grid, res.predictive.t$dist, type = "l") ## 4.4 predictive.quantile <- function(x, nu = 10, ..., p = 0.95) { # Computes the pth quantiles of the predictive distribution, # approximated by predictive.t. # # Args: # x: Sequence of observed values, iid t-distribution (numeric). # nu: Degrees of freedom in t-distribution (positive scalar). # p: Sequence (or single value) indicating the probabilities with # values in (0, 1) (numeric). # additional arguments are passed to predictive.t. # # Returns: # Numeric containing the quantile(s). # # Notes: # Check predictive.t and pracma::cumtrapz. # Argument checking stopifnot(is.numeric(x), is.scalar(nu), nu > 0, is.numeric(p), p > 0, p < 1) # Estimate predictive density pred <- predictive.t(x, ..., nu = 10) # Estimate quantiles cdf <- cumtrapz(pred$grid, pred$dist) # approximate using trapezoidal rule idx <- sapply(p, function(z) max(which(cdf <= z))) return(pred$grid[idx]) } # Checking answer: creating 95% predictive interval set.seed(13) nu <- 10 n <- 1000 mu <- 3 x <- rt(n, df = nu) + mu # 95% predictive interval pred.interval <- predictive.quantile(x, nu = nu, p = c(0.025, 0.975)) pred.interval ## ------------------------------------------------