################################################### ### chunk number 1: ################################################### library(emdbook) library(plotrix) library(bbmle) library(MASS) library(MCMCpack) library(coda) library(R2WinBUGS) library(Hmisc) source("chapskel.R") ################################################### ### chunk number 2: ################################################### x=c(1,1.5,2,2.5,3,4,5,6,10,15,20) y=c(6,3.2,2,-3,3,2,0,-1,2,4,5) y2 = spline(x,y,n=200) plot(y2$x,y2$y,type="l",xlab="",ylab="",ylim=c(-3,15), axes=FALSE,xlim=c(0,20)) box() axis(side=3,line=-11,at=seq(0,5,by=0.5),labels=rep("",11)) axis(side=3,line=-8,at=seq(0,20,by=5),labels=rep("",5)) axis(side=3,line=-5,at=seq(5,20,by=0.5),labels=rep("",31)) axis(side=3,line=-2,at=seq(0,20,by=1),labels=rep("",21)) mtext(side=3,line=-10,at=0,adj=0,"sampling grid 4") mtext(side=3,line=-7,at=0,adj=0,"sampling grid 3") mtext(side=3,line=-4,at=0,adj=0,"sampling grid 2") mtext(side=3,line=-1,at=0,adj=0,"sampling grid 1") mtext(side=3,line=-12,at=0,adj=0,expression(p[lower])) mtext(side=3,line=-12,at=20,adj=1,expression(p[upper])) mtext(side=3,line=-9,at=12.5,adj=0.5,expression(Delta*p)) yht <- 8.5 arrows(c(11.5,13.5),c(yht,yht),c(10,15),c(yht,yht),length=0.1,angle=20) points(y2$x[which.min(y2$y)],min(y2$y),pch=1) restr <- y2$x>5 xrestr <- y2$x[restr] yrestr <- y2$y[restr] points(xrestr[which.min(yrestr)],min(yrestr),pch=16) #points(x,y) ################################################### ### chunk number 3: ################################################### data(MyxoTiter_sum) myxdat = subset(MyxoTiter_sum,grade==1) ################################################### ### chunk number 4: ################################################### gm = mean(myxdat$titer) cv = var(myxdat$titer)/mean(myxdat$titer) shape0=gm/cv scale0=cv ################################################### ### chunk number 5: ################################################### shapevec = 10:100 scalevec = seq(0.01,0.3,by=0.01) ################################################### ### chunk number 6: ################################################### gammaNLL1 = function(shape,scale) { -sum(dgamma(myxdat$titer,shape=shape,scale=scale,log=TRUE)) } ################################################### ### chunk number 7: ################################################### surf = matrix(nrow=length(shapevec),ncol=length(scalevec)) for (i in 1:length(shapevec)) { for (j in 1:length(scalevec)) { surf[i,j] = gammaNLL1(shapevec[i],scalevec[j]) } } ################################################### ### chunk number 8: ################################################### contour(shapevec,scalevec,log10(surf)) ################################################### ### chunk number 9: eval=FALSE ################################################### ## curve3d(log10(gammaNLL1(x,y)),from=c(10,0.01),to=c(100,0.3),n=c(91,30),sys3d="image") ################################################### ### chunk number 10: eval=FALSE ################################################### ## gridsearch2d(gammaNLL1,v1min=10,v2min=0.01,v1max=100,v2max=0.3,logz=TRUE) ################################################### ### chunk number 11: ################################################### ## run Newton's method on likelihood for ## binomial data data(ReedfrogPred) x = subset(ReedfrogPred,pred=="pred" & density==10 & size=="small") k = x$surv N = 10 binomlik = function(p,x=k) { -sum(dbinom(k,prob=p,size=N,log=TRUE)) } ## D(expression(k*log(p)+(N-k)*log(1-p)),"p") binomlik.deriv = function(p,x=k) { -sum(k/p-(N-k)/(1-p)) } ## D(D(expression(k*log(p)+(N-k)*log(1-p)),"p"),"p") binomlik.deriv2 = function(p,x=k) { -sum(-k/p^2-(N-k)/(1-p)^2) } newton = function(start=0.6,graphics=TRUE, tol=1e-4,maxit=20, dfun=binomlik.deriv, dfun2=binomlik.deriv2, ...) { resmat = matrix(nrow=maxit,ncol=5) i = 1 ## initial values x.guess = start x.dval = dfun(x.guess,...) x.dval2 = dfun2(x.guess,...) while (abs(x.dval)>tol && ih1[1]&xh2[1]&xmedian(qual)) time = (dat$d1+dat$d2)/2 ################################################### ### chunk number 45: ################################################### weiblikfun = function(shape,scale) { -sum(dweibull(time,shape=shape,scale=scale,log=TRUE)) } ################################################### ### chunk number 46: ################################################### w1 <- mle2(weiblikfun,start=list(shape=1,scale=mean(time))) ################################################### ### chunk number 47: ################################################### meanfun = function(shape,scale) { scale*gamma(1+1/shape) } ################################################### ### chunk number 48: ################################################### weiblikfun2 <- function(shape,mu) { scale <- mu/gamma(1+1/shape) -sum(dweibull(time,shape=shape,scale=scale,log=TRUE)) } w2 <- mle2(weiblikfun2,start=list(shape=1,mu=mean(time))) ################################################### ### chunk number 49: ################################################### ## compute the contour surface smat <- curve3d(weiblikfun, from=c(0.5,5), to=c(1.2,25), n=c(40,40),sys3d="none") #%Now let's superimpose on this plot contours that represent #%the mean survival time. #%Calculate the mean values for all combinations #%of shape and scale: #%The \code{outer} command is a quick way to generate matrices, #%but it only works for vectorizable functions. mmat <- outer(smat$x,smat$y,meanfun) ## shortcut ################################################### ### chunk number 50: ################################################### op=par(lwd=2,bty="l",las=1,cex=1.5,mgp=c(2.5,1,0)) alevels = c(0.8,0.9,0.95,0.99) mlevels = seq(6,38,by=4) contour(smat$x,smat$y,smat$z,levels=qchisq(alevels,1)/2-logLik(w1), labels=alevels, xlab="Shape",ylab="Scale",col="darkgray",labcex=1) points(coef(w1)[1],coef(w1)[2]) contour(smat$x,smat$y,mmat,add=TRUE,col=1,levels=mlevels,labcex=1,method="edge") p2 = profile(w2) p2B = p2@profile$mu$par.vals shape <- p2B[,1] mu <- p2B[,2] scale <- mu/gamma(1+1/shape) lines(shape,scale,lty=3) shvals <- approx(p2@profile$mu$z,p2B[,"shape"],xout=c(-1.96,1.96))$y muvals <- approx(p2@profile$mu$z,p2B[,"mu"],xout=c(-1.96,1.96))$y contour(smat$x,smat$y,mmat,add=TRUE,col=1,levels=round(muvals,1),lty=2,drawlabels=FALSE) scvals <- muvals/gamma(1+1/shvals) points(shvals,scvals,pch=3) ################################################### ### chunk number 51: ################################################### meanfun = function(shape,scale) { scale*gamma(1+1/shape) } ################################################### ### chunk number 52: ################################################### weiblikfun2 <- function(shape,mu) { scale <- mu/gamma(1+1/shape) -sum(dweibull(time,shape=shape,scale=scale,log=TRUE)) } ################################################### ### chunk number 53: ################################################### w2 <- mle2(weiblikfun2,start=list(shape=1,mu=mean(time))) confint(w2,quietly=TRUE) ################################################### ### chunk number 54: ################################################### ci.prof <- confint(w2,quietly=TRUE)["mu",] ################################################### ### chunk number 55: eval=FALSE ################################################### ## op=par(lwd=2,bty="l",las=1,cex=1.5,mgp=c(2.5,1,0)) ## source("sqrprofplot.R") ## sqrprofplot(p2,which=2,sqrVal=TRUE,conf=c(0.9,0.95), ## col.conf="gray",plot.confstr=TRUE, ## col.prof="black",col.minval=NA, ## xlab="Mean", ## ylab="Deviance") ################################################### ### chunk number 56: ################################################### weiblikfun3 <- function(shape,scale,target.mu,penalty=1000) { mu <- meanfun(shape,scale) NLL = -sum(dweibull(time,shape=shape,scale=scale,log=TRUE)) pen = penalty*(mu-target.mu)^2 NLL+pen } w3 <- mle2(weiblikfun3,start=list(shape=0.9,scale=13),fixed=list(target.mu=13)) ##profile(w3,which="target.mu") penlikfun3 <- function(p,meanval,penalty=1000) { v <- -sum(dweibull(time,shape=p[1],scale=p[2],log=TRUE)) pen <- penalty*(meanfun(p[1],p[2])-meanval)^2 val <- v+pen ## cat(p[1],p[2],penalty,meanval,v,pen,val,"\n") return(val) } penlikfun2 <- function(m,penalty=1000) { o <- optim(fn=penlikfun3, par=coef(w1), method="BFGS", meanval=m, penalty=penalty) r <- c(o$value,o$par) names(r) <- c("NLL","shape","scale") r } critval <- c(-logLik(w1)+qchisq(0.95,1)/2) pcritfun <- function(m,penalty=1000) { penlikfun2(m,penalty=penalty)[1]-critval } lowx <- c(5,13) upx <- c(14,30) penlower <- uniroot(pcritfun,lowx)$root penupper <- uniroot(pcritfun,upx)$root ci.pen1 = c(penlower,penupper) penvec <- 1:5 ##v <- seq(5,13,n=101) ##plot(v,sapply(v,pcritfun,penalty=10^2),type="l") penresults <- matrix(nrow=length(penvec),ncol=3) for (i in 2:length(penvec)) { penlower <- uniroot(pcritfun,lowx,penalty=10^penvec[i])$root penupper <- uniroot(pcritfun,upx,penalty=10^penvec[i])$root penresults[i,] <- c(penvec[i],penlower,penupper) } ################################################### ### chunk number 57: eval=FALSE ################################################### ## shape.deriv <- -shape^2*gamma(1+1/shape)*digamma(1+1/shape) ################################################### ### chunk number 58: ################################################### dvar <- deltavar(fun=scale*gamma(1+1/shape),meanval=coef(w1),Sigma=vcov(w1)) ################################################### ### chunk number 59: ################################################### sdapprox <- sqrt(dvar) mlmean <- meanfun(coef(w1)["shape"],coef(w1)["scale"]) ci.delta <- mlmean+c(-1.96,1.96)*sdapprox ################################################### ### chunk number 60: ################################################### pvars <- diag(vcov(w1)) pcov <- vcov(w1)["shape","scale"] mlshape <- coef(w1)["shape"] mlscale <- coef(w1)["scale"] scderiv <- gamma(1+1/mlshape) shderiv <-mlscale*-1/mlshape^2*gamma(1+1/mlshape)*digamma(1+1/mlshape) vapprox1 <- pvars["scale"]*scderiv^2 vapprox2 <- pvars["shape"]*shderiv^2 vapprox3 <- 2*pcov*shderiv*scderiv vapprox <- vapprox1+vapprox2+vapprox3 ################################################### ### chunk number 61: ################################################### vmat=mvrnorm(1000,mu=coef(w1),Sigma=vcov(w1)) ################################################### ### chunk number 62: ################################################### dist = numeric(1000) for (i in 1:1000) { dist[i] = meanfun(vmat[i,1],vmat[i,2]) } quantile(dist,c(0.025,0.975)) ################################################### ### chunk number 63: ################################################### ci.ppi <- quantile(dist,c(0.025,0.975)) ################################################### ### chunk number 64: ################################################### lval <- coef(w1)["scale"]^(-coef(w1)["shape"]) n <- length(time) inits <- list(list(shape=0.8,lambda=lval),list(shape=0.4,lambda=lval*2), list(shape=1.2,lambda=lval/2)) reefgoby.bugs <- bugs(data=list("time","n"), inits,parameters.to.save=c("shape", "scale","lambda","mean"), model.file="reefgobysurv.bug", n.chains=length(inits),n.iter=5000) reefgoby.coda <- as.mcmc(reefgoby.bugs) reefgoby.coda <- lump.mcmc.list(reefgoby.coda) ci.bayes <- HPDinterval(reefgoby.coda)["mean",] m <- as.matrix(reefgoby.coda)[,"mean"] m <- reefgoby.coda[,"mean",drop=FALSE] m <- as.matrix(reefgoby.coda)[,"mean"] ci.bayesq <- quantile(m,c(0.025,0.975)) ################################################### ### chunk number 65: ################################################### op=par(lwd=2,bty="l",las=1,cex=1.5,mgp=c(3,1,0)) ##par(mar=c(1,4,2,2)) vals = mvrnorm(1000,mu=coef(w1),Sigma=vcov(w1)) dist = apply(vals,1,function(x)meanfun(x[1],x[2])) textsize = 0.5 ang = 15 par(yaxs="i") ## hist(dist,breaks=30,col="gray",xlab="Mean survival time",main="",freq=FALSE, ## axes=FALSE,xlim=c(5,35)) ## axis(side=2,at=c(0,0.05,0.1),yaxs="i") ## axis(side=1) ##box() ##lines(density(dist)) conf.ppi <- quantile(dist,c(0.025,0.975)) ##abline(v=conf.ppi,lty=2,lwd=2) ##par(mar=c(5,4,1,2)) par(mar=c(4,4,2,2)) d1 = density(dist) d2 = density(lump.mcmc.list(as.mcmc(reefgoby.bugs)[,"mean"])) plot(d1,ylim=c(0,0.12),main="", xlab="",axes=FALSE,xlim=c(0,30)) axis(side=2,at=c(0,0.05,0.1,0.15)) lines(d2,col="gray") axis(side=1) box() mtext(side=1,line=2.5,at=15,"Mean survival time",cex=1.5) segments(rep(conf.ppi,2), rep(0,4), rep(conf.ppi,2), approx(d1$x,d1$y,xout=conf.ppi)$y) mpos = 13 labsize = 3 ht1 <- 0.006 arrows(c(mpos-labsize,mpos+labsize), rep(ht1,2), conf.ppi, rep(ht1,2),ang=ang) text(mpos,ht1,"PP interval",cex=textsize) segments(rep(ci.bayes,2), rep(0,4), rep(ci.bayes,2), approx(d2$x,d2$y,xout=ci.bayes)$y, col="gray") ht2 <- 0.012 mpos2 <- 15 labsize2 <- 3.5 arrows(c(mpos2-labsize2,mpos2+labsize2), rep(ht2,2), ci.bayes, rep(ht2,2),col="gray",ang=ang) text(mpos2,ht2,"Bayes credible",col="darkgray",cex=textsize) ## segments(rep(ci.bayesq,2), ## rep(0,4), ## rep(ci.bayesq,2), ## approx(d2$x,d2$y,xout=ci.bayesq)$y, ## col="gray",lty=3) ## ht3 <- 0.012 ## mpos3 <- 16 ## labsize3 <- 3.5 ## arrows(c(mpos3-labsize3,mpos3+labsize3), ## rep(ht3,2), ## ci.bayesq, ## rep(ht3,2),col="gray",ang=ang) ## text(mpos3,ht3,"Bayes quantile",col="darkgray",cex=textsize) par(op) ################################################### ### chunk number 66: eval=FALSE ################################################### ## lval <- coef(w1)["scale"]^(-coef(w1)["shape"]) ## n <- length(time) ## inits <- list(list(shape=0.8,lambda=lval),list(shape=0.4,lambda=lval*2), ## list(shape=1.2,lambda=lval/2)) ################################################### ### chunk number 67: eval=FALSE ################################################### ## reefgoby.bugs <- bugs(data=list("time","n"), ## inits,parameters.to.save=c("shape","scale","lambda","mean"), ## model.file="reefgobysurv.bug", ## n.chains=length(inits),n.iter=5000) ################################################### ### chunk number 68: ################################################### citab = rbind(ci.prof,ci.pen1,ci.delta,ci.ppi,ci.bayes)#,ci.bayesq) cinames = c("exact profile","profile:penalty", "delta method","PPI", "Bayes credible") #,"Bayes quantile") dimnames(citab)=list(cinames,c("lower","upper")) ################################################### ### chunk number 69: ################################################### latex(round(citab,3),file="",table.env=FALSE,title="method") ################################################### ### chunk number 70: eval=FALSE ################################################### ## tabpaste <- function(x,sep=" & ",eol="\\") { ## x2 <- rbind(c("",colnames(x)),cbind(rownames(x), ## matrix(as.character(x),nrow=nrow(x)))) ## x3 <- apply(x2,1,paste,collapse=sep) ## x4 <- paste(x3,collapse=eol) ## return(x4) ## } ################################################### ### chunk number 71: ################################################### x=c(0,0,0,0,0,0,0,1,1,1,1,1,2,2,2,2,2,3,4,5) ################################################### ### chunk number 72: ################################################### fit.nb=fitdistr(x,"negative binomial") lnb = c(-logLik(fit.nb)) fit.pois=fitdistr(x,"Poisson") lpois = c(-logLik(fit.pois)) dev = c(-2*(lnb-lpois)) pval = pchibarsq(dev,1,lower.tail=FALSE) ################################################### ### chunk number 73: ################################################### devdiff = 2*(logLik(fit.nb)-logLik(fit.pois)) pchisq(devdiff,df=1,lower.tail=FALSE) ################################################### ### chunk number 74: ################################################### pval=pchisq(2*(logLik(fit.nb)-logLik(fit.pois)),df=1,lower.tail=FALSE) ################################################### ### chunk number 75: ################################################### simulated.dev = function() { simx = rpois(length(x),lambda=mean(x)) simfitnb = try(fitdistr(simx,"negative binomial")) if (inherits(simfitnb,"try-error")) return(NA) simfitpois = fitdistr(simx,"Poisson") dev=c(2*(logLik(simfitnb)-logLik(simfitpois))) } ################################################### ### chunk number 76: ################################################### set.seed(1001) devdist = replicate(3000,simulated.dev()) devdist = na.omit(devdist) nreps = length(devdist) ################################################### ### chunk number 77: ################################################### obs.dev=2*(logLik(fit.nb)-logLik(fit.pois)) sum(devdist>=obs.dev)/nreps ################################################### ### chunk number 78: ################################################### weiblikfun3 <- function(shape,scale,target.mu,penalty=1000) { mu <- meanfun(shape,scale) NLL = -sum(dweibull(time,shape=shape,scale=scale,log=TRUE)) pen = penalty*(mu-target.mu)^2 NLL+pen } w3 <- mle2(weiblikfun3,start=list(shape=0.9,scale=13),fixed=list(target.mu=13)) ################################################### ### chunk number 79: eval=FALSE ################################################### ## if (shape>0) { ## NLL = -sum(dweibull(time,shape=shape,scale=scale,log=TRUE)) ## pen = 0 ## } else { ## NLL = -sum(dweibull(time,shape=0.0001,scale=scale,log=TRUE)) ## pen = penalty*shape^2 ## } ## NLL+pen ################################################### ### chunk number 80: ################################################### critval <- -logLik(w1)+qchisq(0.95,1)/2 ################################################### ### chunk number 81: ################################################### pcritfun <- function(target.mu,penalty=1000) { mfit <- mle2(weiblikfun3, start=list(shape=0.85,scale=12.4), fixed=list(target.mu=target.mu), data=list(penalty=penalty)) lval <- -logLik(mfit) lval - critval } ################################################### ### chunk number 82: ################################################### lowx <- c(5,13) penlower <- uniroot(pcritfun,lowx)$root ################################################### ### chunk number 83: ################################################### upx <- c(14,30) penupper <- uniroot(pcritfun,upx)$root ################################################### ### chunk number 84: ################################################### uniroot(pcritfun,lowx,penalty=1e6)$root ################################################### ### chunk number 85: ################################################### shape <- coef(w1)["shape"] scale <- coef(w1)["scale"] numericDeriv(quote(scale*gamma(1+1/shape)),c("scale","shape")) ################################################### ### chunk number 86: ################################################### dshape = 0.0001 x2 = scale*gamma(1+1/(shape+dshape)) x1 = scale*gamma(1+1/shape) (x2-x1)/dshape ################################################### ### chunk number 87: ################################################### reefgoby.coda <- as.mcmc(reefgoby.bugs) reefgoby.coda <- lump.mcmc.list(reefgoby.coda) ci.bayes <- HPDinterval(reefgoby.coda)["mean",] ##ci.bayesq <- quantile(reefgoby.coda,c(0.025,0.975))