content
stringlengths
0
14.9M
filename
stringlengths
44
136
plotPFstopEcallVSn=function(nvec,vn.int,pF,cF,pE,cE,p,shape1F,shape2F,shape1E=NULL,shape2E=NULL,col1="green",col2="red",progress=FALSE,cex.legend=1,show=TRUE,...){ if (is.null(shape1E)) shape1E=shape1F if (is.null(shape2E)) shape2E=shape2F if (is.unsorted(vn.int) == TRUE) stop('vn.int must be sorted in ascending order') if (progress) withProgress(message = 'Compute Operating Characteristics', value = 0,{ out=lapply(nvec, function(n) { if (n < min(vn.int)) stop('at least one interim necessary for calculation') incProgress(1/nvec, detail = paste("for n=", n)) vn.int1=vn.int[which(vn.int < n)] v.critE <- critEF(n=n, vn.int=vn.int1, crit=cE, pE=pE,pF=pF, EF="E", shape1=shape1E,shape2=shape2E) v.critF <- critEF(n=n, vn.int=vn.int1, crit=cF, pE=pE,pF=pF, EF="F", shape1=shape1F,shape2=shape2F) temp=pFstopEcall(p,c(vn.int1,n),v.critE,v.critF) res=c(temp$P.effic[length(vn.int1)+1], temp$P.futil.cum[length(vn.int1)+1]) res }) }) else out=lapply(nvec, function(n) { if (n < min(vn.int)) stop('at least one interim necessary for calculation') vn.int1=vn.int[which(vn.int < n)] v.critE <- critEF(n=n, vn.int=vn.int1, crit=cE, pE=pE,pF=pF, EF="E", shape1=shape1E,shape2=shape2E) v.critF <- critEF(n=n, vn.int=vn.int1, crit=cF, pE=pE,pF=pF, EF="F", shape1=shape1F,shape2=shape2F) temp=pFstopEcall(p,c(vn.int1,n),v.critE,v.critF) res=c(temp$P.effic[length(vn.int1)+1], temp$P.futil.cum[length(vn.int1)+1]) res }) names(out)=nvec eff=sapply(out, function(x) x[1]) fut=sapply(out, function(x) x[2]) res=list(eff=eff,fut=fut) if (show){ plot(as.numeric(names(eff)),eff,xlab="final sample size (n)", ylab="Probability", sub=paste0("Interim analyses at (",paste(vn.int,collapse=", "),"), ptrue=",p,", pF=",pF,", cF=",cF,", pE =",pE,", cE=",cE ), ylim=c(0,1),xlim=c(min(nvec),max(nvec)), type="n",las=1,...) # abline(v=min(nvec):max(nvec),lty=3,lwd=1,col="grey") points(as.numeric(names(eff)),eff,pch=4, col=col1) points(as.numeric(names(fut)),fut,pch=3, col=col2) legend("topleft",legend=c("Efficacy at Final","Cumulative Futility at Final" ),pch=c(4,3),col = c(col1,col2),cex=par()$cex*cex.legend) } class(res)="n_vs_pFstopEcall" invisible(res) }
/scratch/gouwar.j/cran-all/cranData/BDP2/R/plotPFstopEcallVSn.R
plotPFstopEstopVSn=function(nvec,vn.int,pF,cF,pE,cE,p,shape1F,shape2F,shape1E=NULL,shape2E=NULL,col1="green",col2="red",progress=FALSE,cex.legend=1,show=TRUE,...){ if (is.null(shape1E)) shape1E=shape1F if (is.null(shape2E)) shape2E=shape2F if (is.unsorted(vn.int) == TRUE) stop('vn.int must be sorted in ascending order') if (progress) withProgress(message = 'Compute Operating Characteristics', value = 0,{ out=lapply(nvec, function(n) { if (n < min(vn.int)) stop('at least one interim necessary for calculation') incProgress(1/nvec, detail = paste("for n=", n)) vn.int1=vn.int[which(vn.int < n)] v.critE <- critEF(n=n, vn.int=vn.int1, crit=cE, pE=pE,pF=pF, EF="E", shape1=shape1E,shape2=shape2E) v.critF <- critEF(n=n, vn.int=vn.int1, crit=cF, pE=pE,pF=pF, EF="F", shape1=shape1F,shape2=shape2F) temp=pFstopEstop(p,c(vn.int1,n),v.critE,v.critF) res=c(temp$P.effic.cum[length(vn.int1)+1], temp$P.futil.cum[length(vn.int1)+1]) res }) }) else out=lapply(nvec, function(n) { if (n < min(vn.int)) stop('at least one interim necessary for calculation') vn.int1=vn.int[which(vn.int < n)] v.critE <- critEF(n=n, vn.int=vn.int1, crit=cE, pE=pE,pF=pF, EF="E", shape1=shape1E,shape2=shape2E) v.critF <- critEF(n=n, vn.int=vn.int1, crit=cF, pE=pE,pF=pF, EF="F", shape1=shape1F,shape2=shape2F) temp=pFstopEstop(p,c(vn.int1,n),v.critE,v.critF) res=c(temp$P.effic.cum[length(vn.int1)+1], temp$P.futil.cum[length(vn.int1)+1]) res }) names(out)=nvec eff=sapply(out, function(x) x[1]) fut=sapply(out, function(x) x[2]) res=list(eff=eff,fut=fut) if (show){ plot(as.numeric(names(eff)),eff,xlab="final sample size (n)", ylab="Probability", sub=paste0("Interim analyses at (",paste(vn.int,collapse=", "),"), ptrue=",p,", pF=",pF,", cF=",cF,", pE =",pE,", cE=",cE ), ylim=c(0,1),xlim=c(min(nvec),max(nvec)), type="n",las=1,...) abline(v=min(nvec):max(nvec),lty=3,lwd=1,col="grey") lines(as.numeric(names(eff)),eff,lwd=2, col=col1) lines(as.numeric(names(fut)),fut,lwd=2, col=col2) legend("topleft",legend=c("Cumulative Efficacy at Final","Cumulative Futility at Final" ),lty=1,col = c(col1,col2),cex=par()$cex*cex.legend) } class(res)="n_vs_pFstopEstop" invisible(res) }
/scratch/gouwar.j/cran-all/cranData/BDP2/R/plotPFstopEstopVSn.R
plotPFstopVScF=function(n,vn.int,pF,cFvec,p0=NULL,p1=NULL,shape1,shape2,col1="green",col2="red",cex.legend=1,...){ pFstop_p0 <-pFstop_vec(n=n, p=p0, pF=pF, vn.int=vn.int, cFvec=cFvec, shape1=shape1,shape2=shape2) pFstop_p1 <-pFstop_vec(n=n, p=p1, pF=pF, vn.int=vn.int, cFvec=cFvec, shape1=shape1,shape2=shape2) plot(as.numeric(colnames(pFstop_p0$summary)),pFstop_p0$summary[length(vn.int)+1,],xlab=expression(c[F]), ylab="Cumulative Stopping Probability at Final",main=paste("Analyses at",paste(c(vn.int,n),collapse=", ") ), ylim=c(0,1),xlim=c(min(cFvec),max(cFvec)), type="n",las=1,...) #final lines(as.numeric(colnames(pFstop_p0$summary)),pFstop_p0$summary[length(vn.int)+1,], col=col1,lwd=2) lines(as.numeric(colnames(pFstop_p1$summary)),pFstop_p1$summary[length(vn.int)+1,], col=col2,lwd=2) legend("bottomright",legend=c(paste("ptrue=",p0),paste("ptrue=",p1)),lty=1,col = c(col1,col2),cex=par()$cex*cex.legend) }
/scratch/gouwar.j/cran-all/cranData/BDP2/R/plotPFstopVScF.R
plotPFstopVSptrue=function(n,vn.int,pF,cF,pvec,shape1,shape2, col=1, add=FALSE,show=TRUE,...){ v.crit <-crit(n=n, pThreshold=pF, vn.int=vn.int, crit=cF, shape1 = shape1, shape2 = shape2) out=lapply(pvec, function(p) {pFstop(p,c(vn.int,n),v.crit)}) names(out)=pvec summ=sapply(out, function(x) x$P.stop.cum) rownames(summ)= paste0("Pat.",c(vn.int,n)) res=list(summary=summ, all=out) if (show){ if (!add) plot(as.numeric(colnames(res$summary)),res$summary[length(vn.int)+1,],xlab=expression(p["true"]), ylab="Cumulative Stopping Probability at Final", main=paste("Analyses at",paste(c(vn.int,n),collapse=", "),"\npF =",pF,", cF=",cF ), ylim=c(0,1),xlim=c(min(pvec),max(pvec)), type="n",las=1,...) #final lines(as.numeric(colnames(res$summary)),res$summary[length(vn.int)+1,],lwd=2,col=col) } class(res)="ptrue_vs_pFstop" invisible(res) }
/scratch/gouwar.j/cran-all/cranData/BDP2/R/plotPFstopVSptrue.R
plotPostProb0or1SuccessesVSn=function(nmin,nmax,pF,shape1F,shape2F,cex.legend=1,...){ ymax=max(1-pbeta(pF,shape1F,shape2F+nmin),1-pbeta(pF,shape1F+1,shape2F+nmin-1)) plot(c(nmin,nmax),c(0,ymax), type="n",xlab="first interim at n=",ylab="P(p>pF|x successes out of n) (=cF)", xaxt="n",main=paste("Posterior probability of 0 or 1 successes out of n for pF=",pF),yaxs="i",las=1,...) axis(side=1,at=c(nmin:nmax)) abline(h=c(0.01,0.05,0.1), col="grey") # abline(v=c(nmin+1:nmax-1), col="grey",lty=2) function0 = function(x){1-pbeta(pF,shape1F,shape2F+x)} function1 = function(x){1-pbeta(pF,shape1F+1,shape2F+x-1)} points(c(nmin:nmax),function0(nmin:nmax),col="red",pch=4) points(c(nmin:nmax),function1(nmin:nmax),col="green",pch=3) # plot(function(x) 1-pbeta(pF,shape1F,shape2F+x),nmin,nmax,add=T,col="red",lwd=3,lty=1) # plot(function(x) 1-pbeta(pF,shape1F+1,shape2F+x-1),nmin,nmax,add=T,col="green",lwd=3,lty=1) legend("topright",legend=c("1 success out of n","no successes out of n"), pch=c(3,4), col=c("green","red"),cex=par()$cex*cex.legend) }
/scratch/gouwar.j/cran-all/cranData/BDP2/R/plotPostProb0or1SuccessesVSn.R
plotPredictivePowerVSk=function(n,vn.int,pF,cF,pE,cE,shape1F,shape2F,shape1E=NULL,shape2E=NULL,show=TRUE,...){ if (is.null(shape1E)) shape1E=shape1F if (is.null(shape2E)) shape2E=shape2F if (is.unsorted(vn.int) == TRUE) stop('vn.int must be sorted in ascending order') if (n < min(vn.int)) stop('at least one interim necessary for calculation') vn.int1=vn.int[which(vn.int < n)] v.critE <- critEF(n=n, vn.int=vn.int1, crit=cE, pE=pE,pF=pF, EF="E", shape1=shape1E,shape2=shape2E) v.critF <- critEF(n=n, vn.int=vn.int1, crit=cF, pE=pE,pF=pF, EF="F", shape1=shape1F,shape2=shape2F) n.evaluations=length(vn.int1) for (nint in c(1:n.evaluations)){ n.int=vn.int1[nint] plot(c(1,n.int),c(0,1), type="n",xlab="", ylab="Predictive Power",xaxt="n") axis(1, c(0:n.int), labels=c(0:n.int)) axis(1, c(0:n.int), labels=c(0:n.int)/n.int, line=1, lty=0, cex.axis=par()$cex.axis-.3) mtext('k (successes at interim)', 1, line=3) mtext('proportion of successes at interim', 1, line=4, cex=par()$cex.lab-.3) title(main=paste0("Interim analyses at (",paste(vn.int1,collapse=", "),"), final analysis at ",n,", pF=",pF,", cF=",cF,", pE =",pE,", cE=",cE), cex.main=par()$cex.main-.2,font.main=1) title(main=paste0("Interim at ",vn.int1[nint]), cex.main=par()$cex.main-.2,font.main=2,line=.7) y=sapply(0:n.int, function(k.int) predictivePower(n.int,k.int,vn.int=c(vn.int1,n),v.critE,v.critF,shape1E,shape2E)[,"PredPow_wFut"]) points(0:n.int,y,col="black",pch=4) } # class(res)="n_vs_pEcall_p0_p1" # invisible(res) }
/scratch/gouwar.j/cran-all/cranData/BDP2/R/plotPredictivePowerVSk.R
plotProb0SuccessesVSn=function(nmin,nmax,p0,p1,cex.legend=1,...){ plot(c(nmin,nmax), c(0,1), type="n",xlab="first interim at n=",ylab="Probability of 0 successes out of n", xaxt="n",main=paste("Probability of 0 successes out of n for p0=",p0," and p1=",p1),yaxs="i",las=1,...) axis(side=1,at=c(nmin:nmax)) abline(h=c(0.01,0.05,0.1), col="grey") # abline(v=c(nmin+1:nmax-1), col="grey",lty=2) points(c(nmin:nmax),dbinom(0,c(nmin:nmax),p1),col="red",pch=4) points(c(nmin:nmax),dbinom(0,c(nmin:nmax),p0),col="green",pch=3) legend("topright",legend=c(paste("ptrue=",p0),paste("ptrue=",p1)), col=c("green","red"),pch=c(3:4),cex=par()$cex*cex.legend) }
/scratch/gouwar.j/cran-all/cranData/BDP2/R/plotProb0SuccessesVSn.R
plotbFbEVSn=function(n,pF,cF,pE,cE, shape1F,shape2F,shape1E,shape2E, colF="red",colE="green",...){ pF=pF pE=pE cF=cF cE=cE bF=CritBoundaryF5(n=n, pF=pF, critF=cF, shape1=shape1F,shape2=shape2F) bE=CritBoundaryE5(n=n, pE=pE, critE=cE, shape1=shape1E,shape2=shape2E) t_col <- function(color, percent = 50, name = NULL) { # color = color name # percent = % transparency # name = an optional name for the color ## Get RGB values for named color rgb.val <- col2rgb(color) ## Make new color using input color as base and alpha set by transparency t.col <- rgb(rgb.val[1], rgb.val[2], rgb.val[3], maxColorValue = 255, alpha = (100-percent)*255/100, names = name) ## Save the color invisible(t.col) } mycolF <- t_col(colF, perc = 50, name = "lt.colF") mycolE <- t_col(colE, perc = 50, name = "lt.colE") plot(c(0:n),c(0:n), ylim=c(-0.5,max(c(bF,bE))),yaxt="n",xaxs="i",yaxs="i",type="n", xlab="Number of enrolled patients",ylab="Decision boundaries", main=paste0("Boundaries for futility (",colF,") and efficacy (",colE,")"), sub=paste0("pF =",pF,", cF=",cF,", pE=",pE,", cE=",cE ),... ) axis(side=2,at=c(0:max(c(bF,bE)))) lines(c(1:n),bF, col=colF,lwd=3) lines(c(1:n),bE, col=colE,lwd=3) abline(v=0:n,lty=3,lwd=1,col="grey") abline(h=c(0:max(c(bF,bE))), lty=3, lwd=1,col="grey") polygon(c(1,c(1:n),n),c(-1,bF,-1), border = NA,col=mycolF) polygon(c(1,c(1:n),n),c(max(c(bF,bE)),bE,max(c(bF,bE))), border = NA,col=mycolE) }
/scratch/gouwar.j/cran-all/cranData/BDP2/R/plotbFbEvsn.R
predictivePower=function(n.int,k.int,vn.int,v.critE,v.critF,shape1E,shape2E){ # Futility stopping probability at every interim: Evaluate at vn.int[i] and stop if #successes <= v.critF[i] # Probability of Calling efficacy at final: Evaluate at vn.int[i] and call if #successes >= v.critE[length(vn.int)] # Args: # n.int: sample size at the interim analsis # k.int: number of successes observed up until the interim analysis # vn.int: vector of sample sizes at the interim analyses # v.critE: vector of critical boundaries for calling efficacy at the interim analyses # v.critF: vector of critical boundaries for futility stopping at the interim analyses #use nomenclature from paper: final is the number of the final analysis in terms of number of interim analyses final=length(vn.int) if (final>7) stop("max 7 interims including final") #identify which interim corresponds to n.int if (identical(which(vn.int==n.int),integer(0))) stop("interim analysis not planned") current.interim=which(vn.int==n.int) my.dbetabinom=function(x,size,a,b){ if (x < 0 | x > size | a < 0 | b < 0){ xxx=0 } else{ xxx=choose(size, x)*beta(a + x, b + size - x)/beta(a, b) } return(xxx) } # if k.int was observed in final analysis if (current.interim == final){ pp=ifelse(k.int >= v.critE(final),1,0) } if (current.interim == final-1){ pp=0 if (k.int > v.critF[final-1]){ a1=shape1E+k.int b1=shape2E+n.int-k.int for (my.i in (v.critE[final] - k.int):(vn.int[final]-vn.int[final-1])) { pp <- pp + (my.i >= 0)*my.dbetabinom(x=my.i,size=vn.int[final]-vn.int[final-1],a=a1,b=b1) } } } if (current.interim == final-2){ pp=0 #my.i1 for (final-2 to) final-1 #my.i for (final-1 to) final if (k.int > v.critF[final-2]){ a1=shape1E+k.int b1=shape2E+n.int-k.int for (my.i1 in (v.critF[final-1] + 1 - k.int):(vn.int[final-1]-vn.int[final-2])) { a=shape1E+k.int + my.i1 b=shape2E+n.int-k.int + vn.int[final-1]-vn.int[final-2] - my.i1 for (my.i in (v.critE[final] - my.i1 - k.int):(vn.int[final]-vn.int[final-1])) { pp <- pp + (my.i1 >= 0)* my.dbetabinom(x=my.i1,size=vn.int[final-1]-vn.int[final-2],a=a1,b=b1)* (my.i >= 0)* my.dbetabinom(x=my.i,size=vn.int[final]-vn.int[final-1],a=a,b=b) } } } } if (current.interim == final-3){ pp=0 #my.i2 for (final-3 to) final-2 #my.i1 for (final-2 to) final-1 #my.i for (final-1 to) final if (k.int > v.critF[final-3]){ a2=shape1E+k.int b2=shape2E+n.int-k.int for (my.i2 in (v.critF[final-2] + 1 - k.int):(vn.int[final-2]-vn.int[final-3])) { a1=shape1E+k.int + my.i2 b1=shape2E+n.int-k.int + vn.int[final-2]-vn.int[final-3] - my.i2 for (my.i1 in (v.critF[final-1] + 1 - my.i2 - k.int):(vn.int[final-1]-vn.int[final-2])) { a=shape1E+k.int + my.i2 + my.i1 b=shape2E+n.int-k.int + vn.int[final-1]-vn.int[final-3] - my.i2 - my.i1 for (my.i in (v.critE[final] - my.i1 - my.i2 - k.int):(vn.int[final]-vn.int[final-1])) { pp <- pp + (my.i2 >= 0)* my.dbetabinom(x=my.i2,size=vn.int[final-2]-vn.int[final-3],a=a2,b=b2)* (my.i1 >= 0)* my.dbetabinom(x=my.i1,size=vn.int[final-1]-vn.int[final-2],a=a1,b=b1)* (my.i >= 0)* my.dbetabinom(x=my.i,size=vn.int[final]-vn.int[final-1],a=a,b=b) } } } } } if (current.interim == final-4){ pp=0 #my.i3 for (final-4 to) final-3 #my.i2 for (final-3 to) final-2 #my.i1 for (final-2 to) final-1 #my.i for (final-1 to) final if (k.int > v.critF[final-4]){ a3=shape1E+k.int b3=shape2E+n.int-k.int for (my.i3 in (v.critF[final-3] + 1 - k.int):(vn.int[final-3]-vn.int[final-4])) { a2=shape1E+k.int + my.i3 b2=shape2E+n.int-k.int + vn.int[final-3]-vn.int[final-4] - my.i3 for (my.i2 in (v.critF[final-2] + 1 -my.i3 - k.int):(vn.int[final-2]-vn.int[final-3])) { a1=shape1E+k.int + my.i3 + my.i2 b1=shape2E+n.int-k.int + vn.int[final-2]-vn.int[final-4] - my.i3 - my.i2 for (my.i1 in (v.critF[final-1] + 1 - my.i3 - my.i2 - k.int):(vn.int[final-1]-vn.int[final-2])) { a=shape1E+k.int + my.i3 + my.i2 + my.i1 b=shape2E+n.int-k.int + vn.int[final-1]-vn.int[final-4] - my.i3 - my.i2 - my.i1 for (my.i in (v.critE[final] - my.i1 - my.i2 - my.i3 - k.int):(vn.int[final]-vn.int[final-1])) { pp <- pp + (my.i3 >= 0)* my.dbetabinom(x=my.i3,size=vn.int[final-3]-vn.int[final-4],a=a3,b=b3)* (my.i2 >= 0)* my.dbetabinom(x=my.i2,size=vn.int[final-2]-vn.int[final-3],a=a2,b=b2)* (my.i1 >= 0)* my.dbetabinom(x=my.i1,size=vn.int[final-1]-vn.int[final-2],a=a1,b=b1)* (my.i >= 0)* my.dbetabinom(x=my.i,size=vn.int[final]-vn.int[final-1],a=a,b=b) } } } } } } if (current.interim == final-5){ pp=0 #my.i4 for (final-5 to) final-4 #my.i3 for (final-4 to) final-3 #my.i2 for (final-3 to) final-2 #my.i1 for (final-2 to) final-1 #my.i for (final-1 to) final if (k.int > v.critF[final-5]){ a4=shape1E+k.int b4=shape2E+n.int-k.int for (my.i4 in (v.critF[final-4] + 1 - k.int):(vn.int[final-4]-vn.int[final-5])) { a3=shape1E+k.int + my.i4 b3=shape2E+n.int-k.int + vn.int[final-4]-vn.int[final-5] - my.i4 for (my.i3 in (v.critF[final-3] + 1 - my.i4 - k.int):(vn.int[final-3]-vn.int[final-4])) { a2=shape1E+k.int + my.i4 + my.i3 b2=shape2E+n.int-k.int + vn.int[final-3]-vn.int[final-5] - my.i4 - my.i3 for (my.i2 in (v.critF[final-2] + 1 -my.i4 - my.i3 - k.int):(vn.int[final-2]-vn.int[final-3])) { a1=shape1E+k.int + my.i4 + my.i3 + my.i2 b1=shape2E+n.int-k.int + vn.int[final-2]-vn.int[final-5] - my.i4 - my.i3 - my.i2 for (my.i1 in (v.critF[final-1] + 1 - my.i4 - my.i3 - my.i2 - k.int):(vn.int[final-1]-vn.int[final-2])) { a=shape1E+k.int + my.i4 + my.i3 + my.i2 + my.i1 b=shape2E+n.int-k.int + vn.int[final-1]-vn.int[final-5] - my.i4 - my.i3 - my.i2 - my.i1 for (my.i in (v.critE[final] - my.i1 - my.i2 - my.i3 - my.i4 - k.int):(vn.int[final]-vn.int[final-1])) { pp <- pp + (my.i4 >= 0)* my.dbetabinom(x=my.i4,size=vn.int[final-4]-vn.int[final-5],a=a4,b=b4)* (my.i3 >= 0)* my.dbetabinom(x=my.i3,size=vn.int[final-3]-vn.int[final-4],a=a3,b=b3)* (my.i2 >= 0)* my.dbetabinom(x=my.i2,size=vn.int[final-2]-vn.int[final-3],a=a2,b=b2)* (my.i1 >= 0)* my.dbetabinom(x=my.i1,size=vn.int[final-1]-vn.int[final-2],a=a1,b=b1)* (my.i >= 0)* my.dbetabinom(x=my.i,size=vn.int[final]-vn.int[final-1],a=a,b=b) } } } } } } } if (current.interim == final-6){ pp=0 #my.i5 for (final-6 to) final-5 #my.i4 for (final-5 to) final-4 #my.i3 for (final-4 to) final-3 #my.i2 for (final-3 to) final-2 #my.i1 for (final-2 to) final-1 #my.i for (final-1 to) final if (k.int > v.critF[final-6]){ a5=shape1E+k.int b5=shape2E+n.int-k.int for (my.i5 in (v.critF[final-5] + 1 - k.int):(vn.int[final-5]-vn.int[final-6])) { a4=shape1E+k.int + my.i5 b4=shape2E+n.int-k.int + vn.int[final-5]-vn.int[final-6] - my.i5 for (my.i4 in (v.critF[final-4] + 1 - my.i5 - k.int):(vn.int[final-4]-vn.int[final-5])) { a3=shape1E+k.int + my.i5 + my.i4 b3=shape2E+n.int-k.int + vn.int[final-4]-vn.int[final-6] - my.i5 - my.i4 for (my.i3 in (v.critF[final-3] + 1 - my.i5 - my.i4 - k.int):(vn.int[final-3]-vn.int[final-4])) { a2=shape1E+k.int + my.i5 + my.i4 + my.i3 b2=shape2E+n.int-k.int + vn.int[final-3]-vn.int[final-6] - my.i5 - my.i4 - my.i3 for (my.i2 in (v.critF[final-2] + 1 - my.i5 - my.i4 - my.i3 - k.int):(vn.int[final-2]-vn.int[final-3])) { a1=shape1E+k.int + my.i5 + my.i4 + my.i3 + my.i2 b1=shape2E+n.int-k.int + vn.int[final-2]-vn.int[final-6] - my.i5 - my.i4 - my.i3 - my.i2 for (my.i1 in (v.critF[final-1] + 1 - my.i5 - my.i4 - my.i3 - my.i2 - k.int):(vn.int[final-1]-vn.int[final-2])) { a=shape1E+k.int + my.i5 + my.i4 + my.i3 + my.i2 + my.i1 b=shape2E+n.int-k.int + vn.int[final-1]-vn.int[final-6] - my.i5 - my.i4 - my.i3 - my.i2 - my.i1 for (my.i in (v.critE[final] - my.i1 - my.i2 - my.i3 - my.i4 - my.i5 - k.int):(vn.int[final]-vn.int[final-1])) { pp <- pp + (my.i5 >= 0)* my.dbetabinom(x=my.i5,size=vn.int[final-5]-vn.int[final-6],a=a5,b=b5)* (my.i4 >= 0)* my.dbetabinom(x=my.i4,size=vn.int[final-4]-vn.int[final-5],a=a4,b=b4)* (my.i3 >= 0)* my.dbetabinom(x=my.i3,size=vn.int[final-3]-vn.int[final-4],a=a3,b=b3)* (my.i2 >= 0)* my.dbetabinom(x=my.i2,size=vn.int[final-2]-vn.int[final-3],a=a2,b=b2)* (my.i1 >= 0)* my.dbetabinom(x=my.i1,size=vn.int[final-1]-vn.int[final-2],a=a1,b=b1)* (my.i >= 0)* my.dbetabinom(x=my.i,size=vn.int[final]-vn.int[final-1],a=a,b=b) } } } } } } } } pp_withoutFutility=PredPower(n=vn.int[final], n.int=n.int,k.int=k.int, k.crit=v.critE[final], shape1=shape1E, shape2=shape2E) predictivePower=data.frame(PredPow_wFut=pp,PredPow_woFut=pp_withoutFutility) predictivePower }
/scratch/gouwar.j/cran-all/cranData/BDP2/R/predictivePower.R
--- title: "BDP2 workflow" author: "created by BDP2 package version `r packageVersion('BDP2')` (Annette Kopp-Schneider, Manuel Wiesenfarth, Division of Biostatistics, German Cancer Research Center (DKFZ), Heidelberg, Germany)" date: "`r Sys.setlocale('LC_TIME', 'English'); format(Sys.time(), '%d %B, %Y')`" params: pF: NA pE: NA p0: NA p1: NA shape1F: NA shape2F: NA shape1E: NA shape2E: NA n.range_1: NA n.range_2: NA n.range_4: NA cF: NA cE.range_1: NA cE: NA firstInterim.at: NA furtherInterims.at: NA nfinal: NA nfinal.vec: NA ptrue.range_1: NA --- ```{r setup, include=FALSE} options(width=80) # out.format <- knitr::opts_knit$get("out.format") # img_template <- switch( out.format, # word = list("img-params"=list(fig.width=6, # fig.height=6, # dpi=150)), # { # # default # list("img-params"=list( dpi=150, # fig.width=6, # fig.height=6, # out.width="504px", # out.height="504px")) # } ) # # knitr::opts_template$set( img_template ) knitr::opts_chunk$set(echo = F,fig.width=7,fig.height = 3,dpi=300) pF = params$pF pE = params$pE p0 = params$p0 p1 = params$p1 shape1F = params$shape1F shape2F = params$shape2F shape1E = params$shape1E shape2E = params$shape2E n.range_1 = params$n.range_1 n.range_2 = params$n.range_2 n.range_4 = params$n.range_4 cF = params$cF cE.range_1 = params$cE.range_1 cE = params$cE firstInterim.at = params$firstInterim.at furtherInterims.at = params$furtherInterims.at nfinal = params$nfinal nfinal.vec = params$nfinal.vec ptrue.range_1 = params$ptrue.range_1 ``` # Chosen Settings - Uninteresting and target response rate: $p_0$=`r p0`, $p_1$=`r p1` - Beta prior for futility criterion: Beta(`r shape1F`, `r shape2F`) - Beta prior for efficacy criterion: Beta(`r shape1E`, `r shape2E`) - First interim at: `r firstInterim.at` - Second and potentially further interims at (selected based on logistic considerations): `r furtherInterims.at` - $p_F$=`r pF` and $c_F$=`r cF`, i.e. futility criterion $P(p>$ `r pF` $|Data) <$ `r cF` - $p_E$=`r pE` and $c_E$=`r cE`, i.e. efficacy criterion $P(p>$ `r pE` $|Data) \geq$ `r cE` # Figures ## 2a. Select timing of first interim analysis and futility stopping criterion, cF, such that the trial stops after a run of treatment failures ```{r } n.range_1=as.numeric(n.range_1) par(mfrow=c(1,2),cex=.7,cex.main=.9) #cex.main=.7,cex.lab=.8,cex.axis=.7, plotBDP2(x="n",y="Prob0Successes",n=c(n.range_1[1],n.range_1[2]),p0=p0,p1=p1) plotBDP2(x="n",y="PostProb0or1Successes",n=c(n.range_1[1],n.range_1[2]),pF=pF,shape1F=shape1F,shape2F=shape2F) ``` The left figure shows true (for $p_{true}=p_0$, in green) and false (for $p_{true}=p_1$, in red) stopping probability. False stopping probability should be bounded to an acceptable limit, e.g. 5%. Any n with false stopping probability below this limit can be used as timing of first interim. The actual choice may be guided by logistical considerations. From left figure, false stopping probability was evaluated and first interim chosen to be performed at `r firstInterim.at` patients. From right figure read P(p>$p_F$| 0 of n), in red, and P(p>$p_F$| 1 of n), in green, for the selected timing of first interim, i.e. for `r firstInterim.at` patients. The value of $c_F$ can be chosen anywhere between these two numbers and will ensure that the trial is stopped at first interim if no successes have been observed so far. From right figure $c_F$ was chosen: $c_F$ = `r cF`. Note: If it is not intended to stop the trial only after a run of treatment failures but also in case that a low number of successes is observed, the timing of first interim and $c_F$ can be chosen on basis of the operating characteristics and expected patient number without evaluating these plots. Timings of second and potentially further interims are selected based on logistical considerations. The choice was to perform (a) further potential interim(s) at `r furtherInterims.at` patients. ## 3. Selecting cE ```{r,fig.height=4} cE.range_1=as.numeric(cE.range_1) cEaccuracy=0.001 cEvec=seq(from=cE.range_1[1],to=cE.range_1[2],by=cEaccuracy) interims.at= c(firstInterim.at,as.numeric(unlist(strsplit(furtherInterims.at," ")))) n=nfinal par(cex.lab=.9,cex.axis=.9,mar=c(5.1, 4.1, 0.5, 2.1)) res=plotBDP2(x="cE",y="PEcall",n=n,interim.at=interims.at,pF=pF,cF=cF,pE=pE,cE=cEvec,p0=p0,p1=p1, shape1F=shape1F,shape2F=shape2F,shape1E=shape1E,shape2E=shape2E,col=c("green","red"),cex.sub=.8) abline(v=cE,col="gray",lty="dashed") ``` The plot shows power (in red) and type I error (in green) as function of $c_E$. Threshold $c_E$ should be selected such that type I error probability can be tolerated and power is maximized. Selected was $c_E$ = `r cE`. This leads to a type I error of `r round(res$y.p0[which.min(abs(res$x.p0-cE))[1]],3)` at $p_0$=`r p0`, and a power of `r round(res$y.p1[which.min(abs(res$x.p1-cE))[1]],3)` at $p_1$=`r p1`. ## 4. Operating characteristics ```{r} n.range_2=as.numeric(n.range_2) nvec=c(n.range_2[1]:n.range_2[2]) interims.at= c(firstInterim.at,as.numeric(unlist(strsplit(furtherInterims.at," ")))) par(mfrow=c(1,2),cex.main=1,cex.sub=.9,cex=.6,cex.lab=1.1,cex.axis=1.1) plotBDP2(x="n",y="PFstopEcall",n=nvec,interim.at=interims.at,pF=pF,cF=cF,pE=pE,cE=cE,ptrue=p0, shape1F=shape1F,shape2F=shape2F,shape1E=shape1E,shape2E=shape2E, progress=T,#cex.legend=.8, main="Type I error and probability of true stopping \nfor varying n") plotBDP2(x="n",y="PFstopEcall",n=nvec,interim.at=interims.at,pF=pF,cF=cF,pE=pE,cE=cE,ptrue=p1, shape1F=shape1F,shape2F=shape2F,shape1E=shape1E,shape2E=shape2E,progress=T,#cex.legend=.8, main="Power and probability of false stopping \nfor varying n") ``` The left plot shows the probabilities for declaration of efficacy and cumulative stopping for futility at final for $p_{true}=p_0$. The right plot shows the same quantities for $p_{true}=p_1$. ## 5. Power function for multiple sample sizes at final analysis and corresponding expected number of patients in the trial as a function of ptrue ```{r,fig.height=4} nvec= as.numeric(unlist(strsplit(nfinal.vec," "))) pvec=seq(ptrue.range_1[1],ptrue.range_1[2],by=.01) interims.at= c(firstInterim.at,as.numeric(unlist(strsplit(furtherInterims.at," ")))) par(mfrow=c(1,2),cex=.9,mar=c(5.1, 4.1, 0.5, 2.1)) n=nvec[1] vn.int=interims.at[interims.at<n] plotBDP2(x="ptrue",y="PEcall",n=n,interim.at=vn.int,pF=pF,cF=cF,pE=pE,cE=cE,ptrue=pvec, shape1F=shape1F,shape2F=shape2F,shape1E=shape1E,shape2E=shape2E,col=1,cex.sub=.7) abline(v=p0,col="grey") abline(v=p1,col="grey") for (jj in 2:length(nvec)) { n=nvec[jj] vn.int=interims.at[interims.at<n] plotBDP2(x="ptrue",y="PEcall",n=n,interim.at=vn.int,pF=pF,cF=cF,pE=pE,cE=cE,ptrue=pvec, shape1F=shape1F,shape2F=shape2F,shape1E=shape1E,shape2E=shape2E,add=TRUE,col=jj) } legend("bottomright",title="final analysis at ",legend=nvec,text.col = 1:length(nvec),cex=.8) n=nvec[1] vn.int=interims.at[interims.at<n] plotBDP2(x="ptrue",y="ExpectedNumber",n=n,interim.at=vn.int,pF=pF,cF=cF,pE=pE,cE=cE,ptrue=pvec,shape1F=shape1F,shape2F=shape2F,col=1,ylim=c(0,max(nvec)),cex.sub=.7) abline(v=p0,col="grey") abline(v=p1,col="grey") for (jj in 2:length(nvec)) { n=nvec[jj] vn.int=interims.at[interims.at<n] plotBDP2(x="ptrue",y="ExpectedNumber",n=n,interim.at=vn.int,pF=pF,cF=cF,pE=pE,cE=cE,ptrue=pvec,shape1F=shape1F,shape2F=shape2F,col=jj,add=TRUE) } legend("bottomright",title="final analysis at ",legend=nvec,text.col = 1:length(nvec),cex=.8) ``` ## 6. Decision boundaries for futility and efficacy (Design specification for clinician) and check for contradictory results ```{r,fig.height=4} vn.int=firstInterim.at n=n.range_4[2] plotBDP2(x="n",y="bFbE",n=n,pF=pF,cF=cF,pE=pE,cE=cE, shape1F=shape1F,shape2F=shape2F,shape1E=shape1E,shape2E=shape2E,col=c("red","green"),cex.sub=.8,cex.main=.9) ``` The plot shows the decision boundaries for the selected trial design in terms of number of successes per number of enrolled patients. The trial is stopped for futility if the observed number of successes among enrolled patients is in the red part of the plot, including the boundary. Efficacy can be called if the observed number of successes among patients at final analysis is in the green part of the plot, including the boundary. The range of final sample size should be increased to the maximal feasible number to check for contradictory results, i.e. for overlap between red and green areas. # Reference Kopp-Schneider, A., Wiesenfarth, M., Witt, R., Edelmann, D., Witt, O. and Abel, U. (2018). Monitoring futility and efficacy in phase II trials with Bayesian posterior distributions - a calibration approach. *Biometrical Journal*, to appear.
/scratch/gouwar.j/cran-all/cranData/BDP2/inst/appdir/report.Rmd
function(input, output) { output$ProbSuccesses <- renderPlot({ p0=input$p0 p1=input$p1 pF=input$pF shape1F=input$shape1F shape2F=input$shape2F n.range_1=as.numeric(input$n.range_1) par(mfrow=c(1,2)) plotBDP2(x="n",y="Prob0Successes",n=c(n.range_1[1],n.range_1[2]),p0=p0,p1=p1) plotBDP2(x="n",y="PostProb0or1Successes",n=c(n.range_1[1],n.range_1[2]),pF=pF,shape1F=shape1F,shape2F=shape2F) }) cE.vs.PEcall= reactive({ pF=input$pF pE=input$pE p0=input$p0 p1=input$p1 shape1F=input$shape1F shape2F=input$shape2F shape1E=input$shape1E shape2E=input$shape2E cF=input$cF cE.range_1=as.numeric(input$cE.range_1) cEaccuracy=0.001 cEvec=seq(from=cE.range_1[1],to=cE.range_1[2],by=cEaccuracy) interims.at= c(input$firstInterim.at,as.numeric(unlist(strsplit(input$furtherInterims.at," ")))) # vn.int=input$firstInterim.at n=input$nfinal res=plotBDP2(x="cE",y="PEcall",n=n,interim.at=interims.at,pF=pF,cF=cF,pE=pE,cE=cEvec,p0=p0,p1=p1, shape1F=shape1F,shape2F=shape2F,shape1E=shape1E,shape2E=shape2E,col=c("green","red"),cex.lab=1.4,show=FALSE) return(res) }) output$cE.vs.PEcall <- renderPlot({ plot.cE_vs_pEcall(cE.vs.PEcall()) abline(v=input$cE,col="gray",lty="dashed") }) output$OCs.selected.cE <- renderText({ cE=input$cE res=cE.vs.PEcall() paste0("Selected cE leads to a type I error of ", round(res$y.p0[which.min(abs(res$x.p0-cE))[1]],3)," at p0=",input$p0, " and a power of ",round(res$y.p1[which.min(abs(res$x.p1-cE))[1]],3)," at p1=",input$p1,".") }) output$n.vs.bFbE <- renderPlot({ pF=input$pF pE=input$pE shape1F=input$shape1F shape2F=input$shape2F shape1E=input$shape1E shape2E=input$shape2E cF=input$cF cE=input$cE vn.int=input$firstInterim.at n=input$n.range_4[2] plotBDP2(x="n",y="bFbE",n=n,pF=pF,cF=cF,pE=pE,cE=cE, shape1F=shape1F,shape2F=shape2F,shape1E=shape1E,shape2E=shape2E,col=c("red","green")) }) output$n.vs.PFstopEcall <- renderPlot({ pF=input$pF pE=input$pE p0=input$p0 p1=input$p1 cF=input$cF cE=input$cE shape1F=input$shape1F shape2F=input$shape2F shape1E=input$shape1E shape2E=input$shape2E n.range_2=as.numeric(input$n.range_2) nvec=c(n.range_2[1]:n.range_2[2]) interims.at= c(input$firstInterim.at,as.numeric(unlist(strsplit(input$furtherInterims.at," ")))) par(mfrow=c(1,2)) plotBDP2(x="n",y="PFstopEcall",n=nvec,interim.at=interims.at,pF=pF,cF=cF,pE=pE,cE=cE,ptrue=p0, shape1F=shape1F,shape2F=shape2F,shape1E=shape1E,shape2E=shape2E, progress=T, main="Type I error and probability of true stopping for varying n",cex.lab=1.4) plotBDP2(x="n",y="PFstopEcall",n=nvec,interim.at=interims.at,pF=pF,cF=cF,pE=pE,cE=cE,ptrue=p1, shape1F=shape1F,shape2F=shape2F,shape1E=shape1E,shape2E=shape2E,progress=T, main="Power and probability of false stopping for varying n",cex.lab=1.4,cex.legend = 1) }) output$ptrue.vs.PEcall <- renderPlot({ pF=input$pF pE=input$pE p0=input$p0 p1=input$p1 cF=input$cF cE=input$cE shape1F=input$shape1F shape2F=input$shape2F shape1E=input$shape1E shape2E=input$shape2E nvec= as.numeric(unlist(strsplit(input$nfinal.vec," "))) pvec=seq(input$ptrue.range_1[1],input$ptrue.range_1[2],by=.01) interims.at= c(input$firstInterim.at,as.numeric(unlist(strsplit(input$furtherInterims.at," ")))) par(mfrow=c(1,2)) # x="ptrue",y="PEcall" n=nvec[1] # vn.int=seq(0,n,by=input$interim.atEvery)[-1] # vn.int=vn.int[-length(vn.int)] vn.int=interims.at[interims.at<n] plotBDP2(x="ptrue",y="PEcall",n=n,interim.at=vn.int,pF=pF,cF=cF,pE=pE,cE=cE,ptrue=pvec, shape1F=shape1F,shape2F=shape2F,shape1E=shape1E,shape2E=shape2E,col=1,cex.lab=1.4) abline(v=p0,col="grey") abline(v=p1,col="grey") for (jj in 2:length(nvec)) { n=nvec[jj] # vn.int=seq(0,n,by=input$interim.atEvery)[-1] # vn.int=vn.int[-length(vn.int)] vn.int=interims.at[interims.at<n] plotBDP2(x="ptrue",y="PEcall",n=n,interim.at=vn.int,pF=pF,cF=cF,pE=pE,cE=cE,ptrue=pvec, shape1F=shape1F,shape2F=shape2F,shape1E=shape1E,shape2E=shape2E,add=TRUE,col=jj) } legend("bottomright",title="final analysis at ",legend=nvec,text.col = 1:length(nvec)) # (x="ptrue",y="ExpectedNumber" n=nvec[1] # vn.int=seq(0,n,by=input$interim.atEvery)[-1] # vn.int=vn.int[-length(vn.int)] vn.int=interims.at[interims.at<n] plotBDP2(x="ptrue",y="ExpectedNumber",n=n,interim.at=vn.int,pF=pF,cF=cF,pE=pE,cE=cE,ptrue=pvec,shape1F=shape1F,shape2F=shape2F,col=1,ylim=c(0,max(nvec)),cex.lab=1.4) abline(v=p0,col="grey") abline(v=p1,col="grey") for (jj in 2:length(nvec)) { n=nvec[jj] # vn.int=seq(0,n,by=input$interim.atEvery)[-1] # vn.int=vn.int[-length(vn.int)] vn.int=interims.at[interims.at<n] plotBDP2(x="ptrue",y="ExpectedNumber",n=n,interim.at=vn.int,pF=pF,cF=cF,pE=pE,cE=cE,ptrue=pvec,shape1F=shape1F,shape2F=shape2F,col=jj,add=TRUE) } legend("bottomright",title="final analysis at ",legend=nvec,text.col = 1:length(nvec)) }) output$report <- downloadHandler( # For PDF output, change this to "report.pdf" filename = function() { paste('report', sep = '.', switch( input$format, PDF = 'pdf', HTML = 'html', Word = 'docx' )) }, content = function(file) { # Copy the report file to a temporary directory before processing it, in # case we don't have write permissions to the current working dir (which # can happen when deployed). tempReport <- file.path(tempdir(), "report.Rmd") # file.copy(paste0(normalizePath( find.package("BDP2"),winslash = "/"),"/exdata/report.Rmd"), tempReport, overwrite = TRUE) file.copy(file.path(system.file("appdir", package = "BDP2"), "report.Rmd"), tempReport, overwrite = TRUE) # Set up parameters to pass to Rmd document params <- list( pF=input$pF, pE=input$pE, p0=input$p0, p1=input$p1, shape1F=input$shape1F, shape2F=input$shape2F, shape1E=input$shape1E, shape2E=input$shape2E, n.range_1=input$n.range_1, n.range_2=input$n.range_2, n.range_4=input$n.range_4, cF=input$cF, cE.range_1=input$cE.range_1, cE=input$cE, firstInterim.at=input$firstInterim.at, furtherInterims.at=input$furtherInterims.at, nfinal=input$nfinal, nfinal.vec= input$nfinal.vec, ptrue.range_1=input$ptrue.range_1 ) # Knit the document, passing in the `params` list, and eval it in a # child of the global environment (this isolates the code in the document # from the code in this app). # render(tempReport, output_file = file, # params = params, # envir = new.env(parent = globalenv()) # ) out <- render(tempReport, switch( input$format, PDF = pdf_document(), HTML = html_document(), Word = word_document() ),params = params, envir = new.env(parent = globalenv()) ) file.rename(out, file) } ) }
/scratch/gouwar.j/cran-all/cranData/BDP2/inst/appdir/server.R
library(shinyBS) library(BDP2) fluidPage( # oben titlePanel(paste0("BDP2 workflow (version ",packageVersion('BDP2'),")")), h3("Workflow to determine design parameters for a multi-stage single-arm phase II trial with binary endpoint. Declaration of efficacy and futility is based on Bayesian posterior distribution."), h4("Annette Kopp-Schneider, Manuel Wiesenfarth, Division of Biostatistics, German Cancer Research Center (DKFZ), Heidelberg, Germany"), br(), h4("1. Common settings: Select pF, pE and the prior distribution for the response rate"),#br(), fluidRow( column(3, h5("Uninteresting and target response rate"), numericInput("p0", "p0:", value=.12, min = 0, max = 1, step=.02),bsTooltip("p0", "Uninteresting (control) response rate", "right", options = list(container = "body")), numericInput("p1", "p1:", value=.3, min = 0, max = 1, step=.02),bsTooltip("p1", "Target response rate", "right", options = list(container = "body")) ), column(2, h5("pF and pE"), numericInput("pF", "pF:", value=.3, min = 0, max = 1, step=.02), bsTooltip("pF", "Response rate used for futility criterion P(p>pF|Data)", "right", options = list(container = "body")), numericInput("pE", "pE:", value=.12, min = 0, max = 1, step=.02),bsTooltip("pE", "Response rate used for efficacy criterion P(p>pE|Data)", "right", options = list(container = "body")) ), column(2, h5("Beta prior for futility criterion"), numericInput("shape1F", "shape1F:", value=.3, step=.02),bsTooltip("shape1F", "shape1 parameter for Beta prior for futility criterion", "right", options = list(container = "body")), numericInput("shape2F", "shape2F:", value=.7, step=.02),bsTooltip("shape2F", "shape2 parameter for Beta prior for futility criterion", "right", options = list(container = "body")) ), column(2, h5("Beta prior for efficacy criterion"), numericInput("shape1E", "shape1E:", value=.12, step=.02),bsTooltip("shape1E", "shape1 parameter for Beta prior for efficacy criterion", "right", options = list(container = "body")), numericInput("shape2E", "shape2E:", value=.88, step=.02),bsTooltip("shape2E", "shape2 parameter for Beta prior for efficacy criterion", "right", options = list(container = "body")) ) ), br(),hr(),br(),#br(), sidebarLayout( # unten links sidebarPanel( h5("Note: For support for settings and for effect of settings on trial characteristics click on tabs to the right!"),hr(), h4( "2. Select timing of interims and cF"), numericInput("firstInterim.at", "First interim at:", value=10, min = 0, step=1), numericInput("cF", "cF (for futility criterion P(p>pF|Data) < cF):", value=.01, min = 0, max = 1, step=.01), br(), textInput("furtherInterims.at", "Second and potential further interims at (separate by blank):", value = "20"), hr(), h4("3. Select cE"), numericInput("cE", "cE (for efficacy criterion P(p>pE|Data) >= cE):", value=.9, min = 0, max = 1, step=.01), hr(), downloadButton("report", "Generate report"), radioButtons('format', 'Document format', c('PDF', 'HTML', 'Word'), inline = TRUE) ), # unten rechts mainPanel( tabsetPanel( tabPanel(title="2. Select timing of interims and cF", h4("2a. Select timing of first interim analysis and futility stopping criterion, cF, such that the trial stops after a run of treatment failures:"), sliderInput("n.range_1", "Range of sample sizes at first interim:", min = 0, max = 200, value = c(4,15),width = 400), plotOutput("ProbSuccesses"), h5("The left figure shows true (for ptrue=p0, in green) and false (for ptrue=p1, in red) stopping probability. False stopping probability should be bounded to an acceptable limit, e.g., 5%. Any n with false stopping probability below this limit can be used as timing of first interim. The actual choice may be guided by logistical considerations."), h5("From the right figure read P(p>pF| 0 of n), in red, and P(p>pF| 1 of n), in green, for your selected timing of the first interim. The value of cF can be chosen anywhere between these two numbers and will ensure that the trial is stopped at first interim if no success has been observed so far. Consider the operating characteristics (tab 4), power and expected patient number (tab 5) for final decision on cF."), h5("Note: If it is intended to stop the trial not only after a run of treatment failures but also in case a low number of successes is observed, the timing of first interim and cF can be chosen on the basis of the operating characteristics (tab 4), power and expected patient number (tab 5) without evaluating these plots.",style = "color:blue"), h4("2b. Timings of second and potential further interims are selected based on logistical considerations."), br() ), tabPanel(title="3. Select cE", h3("3. Selecting cE"),br(), fluidRow( column(2,numericInput("nfinal", "final analysis at :", value=20, min = 0, step=1)), column(2,sliderInput("cE.range_1", "Range of cE values:", min = 0, max = 1, value = c(0.75,0.99),width = 400)) ), plotOutput("cE.vs.PEcall"), h5("The plot shows power (in red) and type I error (in green) as function of cE."), h5("Select threshold cE such that type I error probability can be tolerated and power is maximized.") , textOutput("OCs.selected.cE"), br() ), tabPanel(title="4. Operating characteristics", h3("4. Investigating operating characteristics"),br(), sliderInput("n.range_2", "Range of final sample sizes n:", min = 0, max = 200, value = c(15,30),width = 400), plotOutput("n.vs.PFstopEcall"), h5("The left plot shows the probabilities for declaration of efficacy and cumulative stopping for futility at final for ptrue=p0."), h5("The right plot shows the same quantities for ptrue=p1. "), br() ), tabPanel(title="5. Power and expected number of patients for multiple sample sizes", h3("5. Power function for multiple sample sizes at final analysis and corresponding expected number of patients in the trial as a function of ptrue"),br(), fluidRow( column(2,textInput("nfinal.vec", "final sample sizes to compare", value = "20 30")), # column(2,numericInput("interim.atEvery", "interim at every ... patient :", value=10, min = 0, step=1)), column(2,sliderInput("ptrue.range_1", "Range of ptrue values:", min = 0, max = 1, value = c(0,0.5),width = 400)) ), plotOutput("ptrue.vs.PEcall"), # plotOutput("ptrue.vs.ExpectedNumber") br() ), tabPanel(title="6. Decision boundaries", h3("6. Decision boundaries for futility and efficacy (Design specification for clinician) and check for contradictory results"), sliderInput("n.range_4", "Range of final sample sizes n:", min = 0, max = 200, value = c(0,40),width = 400), plotOutput("n.vs.bFbE"), h5("The plot shows the decision boundaries for the selected trial design in terms of number of successes per number of enrolled patients."), h5("The trial is stopped for futility if the observed number of successes among enrolled patients is in the red part of the plot, including the boundary."), h5("Efficacy can be called if the observed number of successes among patients at final analysis is in the green part of the plot, including the boundary."), h5("The range of final sample size should be increased to the maximal feasible number to check for contradictory results, i.e., for overlap between red and green areas."), br() ) ) ) ),br(),br(), h4("Reference"), h5("Kopp-Schneider, A., Wiesenfarth, M., Witt, R., Edelmann, D., Witt, O. and Abel, U. (2018). Monitoring futility and efficacy in phase II trials with Bayesian posterior distributions - a calibration approach. Biometrical Journal, to appear.") )
/scratch/gouwar.j/cran-all/cranData/BDP2/inst/appdir/ui.R
## ----setup, include = FALSE---------------------------------------------- knitr::opts_chunk$set( collapse = TRUE, comment = "#>", fig.width=5, fig.height=5 ) ## ---- get parameters, message=F, warning=F------------------------------- library(BDP2) p0=0.12 p1=0.3 pF=0.3 pE=0.12 shape1F=0.3 shape2F=0.7 shape1E=0.12 shape2E=0.88 cF=0.01 cE=0.9 ## ---- Figure 1, fig.show='hold',fig.width=6, fig.height=4---------------- ##plot PF plot(function(x) x,0,0.8,add=F,type="n",col="black",xlab="",ylab="",xaxt="n",yaxt="n",ylim=c(0,4), cex.axis=1.5,cex.lab=1.5,xaxs='i',yaxs='i') plot(function(x) dbeta(x,shape1F+2,shape2F+8),add=T,col="black",lwd=2,lty=1) xy <- seq(0.3,1,length=1000) fxy <- dbeta(xy,shape1F+2,shape2F+8) xyx <- c(1,0.3,xy) yyx <- c(0.0001,0.0001,fxy) polygon(xyx,yyx,col='red') lines(c(0.3,0.3),c(0,dbeta(0.3,shape1F+2,shape2F+8)),lwd=3) axis(side=1,at=c(0.12,0.3),label=c(expression(p[E]),expression(p[F])),cex.axis=1.5) axis(side=1,at=c(0.12,0.3),label=c(expression(paste("=",p[0])),expression(paste("=",p[1]))),cex.axis=1.5,line=1.5,lty=0) text(0.65,0.7,labels=expression(paste("P(p > ",p[F],"| Data)")),cex=1.5) lines(c(0.4,0.5),c(0.5,0.7),lwd=3) ##plot PE plot(function(x) x,0,0.8,add=F,type="n",col="black",xlab="",ylab="",xaxt="n",yaxt="n",ylim=c(0,4), cex.axis=1.5,cex.lab=1.5,xaxs='i',yaxs='i') plot(function(x) dbeta(x,shape1E+2,shape2E+8),add=T,col="black",lwd=2,lty=1) xy <- seq(0.12,1,length=1000) fxy <- dbeta(xy,shape1E+2,shape2E+8) xyx <- c(1,0.12,xy) yyx <- c(0.0001,0.0001,fxy) polygon(xyx,yyx,col='green') lines(c(0.12,0.12),c(0,dbeta(0.12,shape1E+2,shape2E+8)),lwd=3) axis(side=1,at=c(0.12,0.3),label=c(expression(p[E]),expression(p[F])),cex.axis=1.5) axis(side=1,at=c(0.12,0.3),label=c(expression(paste("=",p[0])),expression(paste("=",p[1]))),cex.axis=1.5,line=1.5,lty=0) text(0.65,0.7,labels=expression(paste("P(p > ",p[E],"| Data)")),cex=1.5) lines(c(0.4,0.5),c(0.5,0.7),lwd=3) ## ---- Figure 2----------------------------------------------------------- n=20 plot(function(x) pbeta(pF,shape1=shape1F+x,shape2=shape2F+n-x,lower.tail = F)-cF, 0,n,ylim=c(-1,1),lwd=3, xlab="x",ylab=expression(paste("P(p>",p[R],"|x,n = 20) - c")),col="red") plot(function(x) pbeta(pE,shape1=shape1E+x,shape2=shape2E+n-x,lower.tail = F)-cE, 0,n,ylim=c(-1,1),lwd=3,col="green",add=TRUE) abline(h=0) legend("bottomright",legend=c(expression(paste("Futility decision: c=",c[F],", ",p[R],"=",p[F])), expression(paste("Efficacy decision: c=",c[E],", ",p[R],"=",p[E]))), lty=1,col = c("red", "green"),cex=1) abline(v=c(0:20),lty=3,col="grey") ## ---- Figure 3, fig.show='hold',fig.width=7------------------------------ nmin=4 nmax=15 plotBDP2(x="n",y="Prob0Successes",n=c(nmin,nmax),p0=p0,p1=p1) plotBDP2(x="n",y="PostProb0or1Successes",n=c(nmin,nmax),pF=pF,shape1F=shape1F,shape2F=shape2F) ## ---- Figure 4,fig.width=6----------------------------------------------- n=20 interim.at=10 cE=c(7500:9900)/10000 plotBDP2(x = "cE", y = "PEcall", n=n, interim.at=interim.at, p0=p0,p1=p1, pF=pF,cF=cF,pE=pE,cE=cE, shape1F=shape1F,shape2F=shape2F,shape1E=shape1E,shape2E=shape2E, col = c("green", "red")) ## ---- Figure 5----------------------------------------------------------- n=40 cE=0.9 cF=0.01 plotBDP2(x = "n", y = "bFbE", n=n,pF=pF,cF=cF,pE=pE,cE=cE, shape1F=shape1F,shape2F=shape2F,shape1E=shape1E,shape2E=shape2E, col=c("red","green")) ## ---- Figure 6,fig.width=7----------------------------------------------- nvec=c(18:40) interim.at=c(10,20,30) ptrue=0.12 plotBDP2(x="n", y="PFstopEcall", n =nvec, interim.at = interim.at, pF=pF,cF=cF,pE=pE,cE=cE,ptrue=ptrue,shape1F=shape1F,shape2F=shape2F,shape1E=shape1E,shape2E=shape2E) ptrue=0.3 plotBDP2(x="n", y="PFstopEcall", n =nvec, interim.at = interim.at, pF=pF,cF=cF,pE=pE,cE=cE,ptrue=ptrue,shape1F=shape1F,shape2F=shape2F,shape1E=shape1E,shape2E=shape2E) ## ---- Figure 7,fig.width=6----------------------------------------------- n=20 interim.at=10 ptrue=c(0:40)/100 plotBDP2(x = "ptrue", y = "PEcall", n=n, interim.at=interim.at, ptrue=ptrue, pF=pF, cF=cF, pE=pE, cE=cE, p0=p0, p1=p1, shape1F=shape1F, shape2F=shape2F, shape1E=shape1E , shape2E=shape2E , col = "green") n=30 interim.at=c(10,20) plotBDP2(x = "ptrue", y = "PEcall", n=n, interim.at=interim.at, ptrue=ptrue, pF=pF, cF=cF, pE=pE, cE=cE, p0=p0, p1=p1, shape1F=shape1F, shape2F=shape2F, shape1E=shape1E , shape2E=shape2E , col = "red",lty=2,add=TRUE) abline(v=0.12,col="grey",lty=2) abline(v=0.3,col="grey",lty=2) ## ---- Figure 8,fig.width=6----------------------------------------------- n=30 interim.at=c(10,20) pvec=c(0:40)/100 interim.at=interim.at[interim.at<n] plotBDP2(x="ptrue", y="ExpectedNumber", n=n,interim.at=interim.at,pF=pF,cF=cF,pE=pE,cE=cE,ptrue=pvec, shape1F=shape1F,shape2F=shape2F,col="red",ylim=c(0,n),cex.lab=1.4) n=20 interim.at=interim.at[interim.at<n] plotBDP2(x="ptrue", y="ExpectedNumber", n=n,interim.at=interim.at,pF=pF,cF=cF,pE=pE,cE=cE,ptrue=pvec, shape1F=shape1F,shape2F=shape2F,col="green",add=TRUE) abline(h=20,col="grey",lty=2) abline(h=30,col="grey",lty=2) ## ---- Figure 9,fig.width=7----------------------------------------------- interim.at=c(10,20) nfinal=30 plotBDP2(x="k",y="PredictivePower",n=nfinal,interim.at = interim.at, cE=cE,cF=cF, pE=pE,pF=pF, shape1E=shape1E,shape2E=shape2E,shape1F=shape1F,shape2F=shape2F) ## ---- Figure 10---------------------------------------------------------- n=100 plotBDP2(x = "n", y = "bFbE", n=n,pF=pF,cF=cF,pE=pE,cE=cE, shape1F=shape1F,shape2F=shape2F,shape1E=shape1E,shape2E=shape2E, col=c("red","green")) ## ------------------------------------------------------------------------ sessionInfo()
/scratch/gouwar.j/cran-all/cranData/BDP2/inst/doc/reproduce_results.R
--- title: "Monitoring futility and efficacy in phase II trials with Bayesian posterior distributions -- a calibration approach" author: "Annette Kopp-Schneider, Manuel Wiesenfarth, Ruth Witt, Dominic Edelmann, Olaf Witt and Ulrich Abel" date: "`r Sys.Date()`" output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{Monitoring futility and efficacy in phase II trials with Bayesian posterior distributions -- a calibration approach} %\VignetteEncoding{UTF-8} %\VignetteEngine{knitr::rmarkdown} editor_options: chunk_output_type: console --- ```{r setup, include = FALSE} knitr::opts_chunk$set( collapse = TRUE, comment = "#>", fig.width=5, fig.height=5 ) ``` # Introduction This vignette reproduces results and figures in Kopp-Schneider, A., Wiesenfarth, M., Witt, R., Edelmann, D., Witt, D. and Abel, U. (2018). \cr Monitoring futility and efficacy in phase II trials with Bayesian posterior distributions - a calibration approach. *Biometrical Journal*, to appear. Note that most figures are also shown in the interactive shiny app using `BDP2workflow()` # Parameters First we set the parameters as in the paper. Notation is identical as in the paper: p0, p1, pF, pE, cF, cE as in the paper, shape1F, shape2F are the parameters for the prior for futility, and shape1E, shape2E are the parameters for the prior for efficacy. ```{r, get parameters, message=F, warning=F} library(BDP2) p0=0.12 p1=0.3 pF=0.3 pE=0.12 shape1F=0.3 shape2F=0.7 shape1E=0.12 shape2E=0.88 cF=0.01 cE=0.9 ``` # Figure 1 Figure 1: Posterior distribution of response probability used for futility stop decision: the trial will be stopped for futility if the coloured area is $< c_F$ (left panel). Posterior distribution of response probability used for efficacy calling: the trial will be called efficaceous if the coloured area is $\geq c_E$ (right panel). The Figure also shows the choice of $p_F=p_1$ and of $p_E=p_0$ as discussed in the actual design of the trial. ```{r, Figure 1, fig.show='hold',fig.width=6, fig.height=4} ##plot PF plot(function(x) x,0,0.8,add=F,type="n",col="black",xlab="",ylab="",xaxt="n",yaxt="n",ylim=c(0,4), cex.axis=1.5,cex.lab=1.5,xaxs='i',yaxs='i') plot(function(x) dbeta(x,shape1F+2,shape2F+8),add=T,col="black",lwd=2,lty=1) xy <- seq(0.3,1,length=1000) fxy <- dbeta(xy,shape1F+2,shape2F+8) xyx <- c(1,0.3,xy) yyx <- c(0.0001,0.0001,fxy) polygon(xyx,yyx,col='red') lines(c(0.3,0.3),c(0,dbeta(0.3,shape1F+2,shape2F+8)),lwd=3) axis(side=1,at=c(0.12,0.3),label=c(expression(p[E]),expression(p[F])),cex.axis=1.5) axis(side=1,at=c(0.12,0.3),label=c(expression(paste("=",p[0])),expression(paste("=",p[1]))),cex.axis=1.5,line=1.5,lty=0) text(0.65,0.7,labels=expression(paste("P(p > ",p[F],"| Data)")),cex=1.5) lines(c(0.4,0.5),c(0.5,0.7),lwd=3) ##plot PE plot(function(x) x,0,0.8,add=F,type="n",col="black",xlab="",ylab="",xaxt="n",yaxt="n",ylim=c(0,4), cex.axis=1.5,cex.lab=1.5,xaxs='i',yaxs='i') plot(function(x) dbeta(x,shape1E+2,shape2E+8),add=T,col="black",lwd=2,lty=1) xy <- seq(0.12,1,length=1000) fxy <- dbeta(xy,shape1E+2,shape2E+8) xyx <- c(1,0.12,xy) yyx <- c(0.0001,0.0001,fxy) polygon(xyx,yyx,col='green') lines(c(0.12,0.12),c(0,dbeta(0.12,shape1E+2,shape2E+8)),lwd=3) axis(side=1,at=c(0.12,0.3),label=c(expression(p[E]),expression(p[F])),cex.axis=1.5) axis(side=1,at=c(0.12,0.3),label=c(expression(paste("=",p[0])),expression(paste("=",p[1]))),cex.axis=1.5,line=1.5,lty=0) text(0.65,0.7,labels=expression(paste("P(p > ",p[E],"| Data)")),cex=1.5) lines(c(0.4,0.5),c(0.5,0.7),lwd=3) ``` # Figure 2 Upper tail function for $n=20$, for a design with $p_F=0.3$, $c_F = 0.01$ and prior distribution Be($p_F,1-p_F$) for futility (in red), and $p_E=0.12$, $c_E = 0.9$ and prior distribution Be($p_E,1-p_E$) for efficacy (in green). From the graphs, $b_F(20)=1$ and $b_E(20)=5$. ```{r, Figure 2} n=20 plot(function(x) pbeta(pF,shape1=shape1F+x,shape2=shape2F+n-x,lower.tail = F)-cF, 0,n,ylim=c(-1,1),lwd=3, xlab="x",ylab=expression(paste("P(p>",p[R],"|x,n = 20) - c")),col="red") plot(function(x) pbeta(pE,shape1=shape1E+x,shape2=shape2E+n-x,lower.tail = F)-cE, 0,n,ylim=c(-1,1),lwd=3,col="green",add=TRUE) abline(h=0) legend("bottomright",legend=c(expression(paste("Futility decision: c=",c[F],", ",p[R],"=",p[F])), expression(paste("Efficacy decision: c=",c[E],", ",p[R],"=",p[E]))), lty=1,col = c("red", "green"),cex=1) abline(v=c(0:20),lty=3,col="grey") ``` # Figure 3 Binomial density with zero responders,$(1-p)^n$, for varying $n$, evaluated for $p=p_0=0.12$ and for $p=p_1=0.3$ (left panel). Posterior probabilities $P(p \geq p_F | 0,n)$ and $P(p \geq p_F | 1,n)$ for varying $n$ for $p_F=0.3$ with prior distribution Beta($p_F,1-p_F$) (right panel). ```{r, Figure 3, fig.show='hold',fig.width=7} nmin=4 nmax=15 plotBDP2(x="n",y="Prob0Successes",n=c(nmin,nmax),p0=p0,p1=p1) plotBDP2(x="n",y="PostProb0or1Successes",n=c(nmin,nmax),pF=pF,shape1F=shape1F,shape2F=shape2F) ``` # Figure 4 Probability of calling efficacy at final analysis with $n_\text{final}=20$ patients as a function of $c_E$. Design parameters are $p_F=0.3, p_E=0.12$, prior distributions Beta($p_F,1-p_F$) and Beta($p_E,1-p_E$), $c_F=0.01$ and one interim at $10$ patients. For $p_{true}=p_0=0.12$ this corresponds to type I error, for $p_{true}=p_1=0.3$ this corresponds to power. ```{r, Figure 4,fig.width=6} n=20 interim.at=10 cE=c(7500:9900)/10000 plotBDP2(x = "cE", y = "PEcall", n=n, interim.at=interim.at, p0=p0,p1=p1, pF=pF,cF=cF,pE=pE,cE=cE, shape1F=shape1F,shape2F=shape2F,shape1E=shape1E,shape2E=shape2E, col = c("green", "red")) ``` # Figure 5 Decision boundaries for futility (in red) and efficacy (in green) for a design with $c_F = 0.01$ and $c_E = 0.9$. Other design parameters are $p_F=0.3, p_E=0.12$, prior distributions Beta($p_F,1-p_F$) and Beta($p_E,1-p_E$). ```{r, Figure 5} n=40 cE=0.9 cF=0.01 plotBDP2(x = "n", y = "bFbE", n=n,pF=pF,cF=cF,pE=pE,cE=cE, shape1F=shape1F,shape2F=shape2F,shape1E=shape1E,shape2E=shape2E, col=c("red","green")) ``` # Figure 6 Type I error ($\text{CumP}_{\text{callE}}$) and probability of true stopping ($\text{CumP}_{\text{stopF}}$) for the uninteresting response rate $p=p_0=0.12$ (left panel). Power ($\text{CumP}_{\text{callE}}$) and probability of false stopping ($\text{CumP}_{\text{stopF}}$) for the target response rate $p=p_1=0.3$ (right panel). Other design parameters are $c_F = 0.01$ and $c_E = 0.9$, prior distributions Beta($p_F,1-p_F$) and Beta($p_E,1-p_E$), interim analyses every $10$ patients. ```{r, Figure 6,fig.width=7} nvec=c(18:40) interim.at=c(10,20,30) ptrue=0.12 plotBDP2(x="n", y="PFstopEcall", n =nvec, interim.at = interim.at, pF=pF,cF=cF,pE=pE,cE=cE,ptrue=ptrue,shape1F=shape1F,shape2F=shape2F,shape1E=shape1E,shape2E=shape2E) ptrue=0.3 plotBDP2(x="n", y="PFstopEcall", n =nvec, interim.at = interim.at, pF=pF,cF=cF,pE=pE,cE=cE,ptrue=ptrue,shape1F=shape1F,shape2F=shape2F,shape1E=shape1E,shape2E=shape2E) ``` # Figure 7 Power function ($\text{CumP}_{\text{callE}}$) at $n_\text{final}= 20$ (in green) and $n_\text{final}=30$ (in red) as a function of $p$. Other design parameters are $p_F=0.3, p_E=0.12$, prior distributions Beta($p_F,1-p_F$) and Beta($p_E,1-p_E$), $c_F=0.01$ and $c_E=0.3$, interim analyses every $10$ patients. ```{r, Figure 7,fig.width=6} n=20 interim.at=10 ptrue=c(0:40)/100 plotBDP2(x = "ptrue", y = "PEcall", n=n, interim.at=interim.at, ptrue=ptrue, pF=pF, cF=cF, pE=pE, cE=cE, p0=p0, p1=p1, shape1F=shape1F, shape2F=shape2F, shape1E=shape1E , shape2E=shape2E , col = "green") n=30 interim.at=c(10,20) plotBDP2(x = "ptrue", y = "PEcall", n=n, interim.at=interim.at, ptrue=ptrue, pF=pF, cF=cF, pE=pE, cE=cE, p0=p0, p1=p1, shape1F=shape1F, shape2F=shape2F, shape1E=shape1E , shape2E=shape2E , col = "red",lty=2,add=TRUE) abline(v=0.12,col="grey",lty=2) abline(v=0.3,col="grey",lty=2) ``` # Figure 8 Expected number of patients in the trial for $n_\text{final}= 20$ (in green) and $n_\text{final}=30$ (in red) as a function of $p$. Other design parameters are $p_F=0.3, p_E=0.12$, prior distributions Beta($p_F,1-p_F$) and Beta($p_E,1-p_E$), $c_F=0.01$ and $c_E=0.3$, interim analyses every $10$ patients. Maximal numbers of patients ($n=20$ and $n=30$, resp.) are shown as dotted lines. ```{r, Figure 8,fig.width=6} n=30 interim.at=c(10,20) pvec=c(0:40)/100 interim.at=interim.at[interim.at<n] plotBDP2(x="ptrue", y="ExpectedNumber", n=n,interim.at=interim.at,pF=pF,cF=cF,pE=pE,cE=cE,ptrue=pvec, shape1F=shape1F,shape2F=shape2F,col="red",ylim=c(0,n),cex.lab=1.4) n=20 interim.at=interim.at[interim.at<n] plotBDP2(x="ptrue", y="ExpectedNumber", n=n,interim.at=interim.at,pF=pF,cF=cF,pE=pE,cE=cE,ptrue=pvec, shape1F=shape1F,shape2F=shape2F,col="green",add=TRUE) abline(h=20,col="grey",lty=2) abline(h=30,col="grey",lty=2) ``` # Figure 9 Predictive power (including futility stop) as function of observed responders, evaluated at interim at $10$ patients (left panel) or $20$ patients (right panel). Final analysis at $n_\text{final}= 30$. Other design parameters are $p_F=0.3, p_E=0.12$, prior distributions Beta($p_F,1-p_F$) and Beta($p_E,1-p_E$), $c_F=0.01$ and $c_E=0.3$ ```{r, Figure 9,fig.width=7} interim.at=c(10,20) nfinal=30 plotBDP2(x="k",y="PredictivePower",n=nfinal,interim.at = interim.at, cE=cE,cF=cF, pE=pE,pF=pF, shape1E=shape1E,shape2E=shape2E,shape1F=shape1F,shape2F=shape2F) ``` # Figure 10 Decision boundaries for futility (in red) and efficacy (in green) for a design with $c_F = 0.01$ and $c_E = 0.9$ for up to $100$ enrolled patients. Other design parameters are $p_F=0.3, p_E=0.12$, prior distributions Beta($p_F,1-p_F$) and Beta($p_E,1-p_E$). ```{r, Figure 10} n=100 plotBDP2(x = "n", y = "bFbE", n=n,pF=pF,cF=cF,pE=pE,cE=cE, shape1F=shape1F,shape2F=shape2F,shape1E=shape1E,shape2E=shape2E, col=c("red","green")) ``` Session info ------------ ```{r} sessionInfo() ```
/scratch/gouwar.j/cran-all/cranData/BDP2/inst/doc/reproduce_results.Rmd
--- title: "Monitoring futility and efficacy in phase II trials with Bayesian posterior distributions -- a calibration approach" author: "Annette Kopp-Schneider, Manuel Wiesenfarth, Ruth Witt, Dominic Edelmann, Olaf Witt and Ulrich Abel" date: "`r Sys.Date()`" output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{Monitoring futility and efficacy in phase II trials with Bayesian posterior distributions -- a calibration approach} %\VignetteEncoding{UTF-8} %\VignetteEngine{knitr::rmarkdown} editor_options: chunk_output_type: console --- ```{r setup, include = FALSE} knitr::opts_chunk$set( collapse = TRUE, comment = "#>", fig.width=5, fig.height=5 ) ``` # Introduction This vignette reproduces results and figures in Kopp-Schneider, A., Wiesenfarth, M., Witt, R., Edelmann, D., Witt, D. and Abel, U. (2018). \cr Monitoring futility and efficacy in phase II trials with Bayesian posterior distributions - a calibration approach. *Biometrical Journal*, to appear. Note that most figures are also shown in the interactive shiny app using `BDP2workflow()` # Parameters First we set the parameters as in the paper. Notation is identical as in the paper: p0, p1, pF, pE, cF, cE as in the paper, shape1F, shape2F are the parameters for the prior for futility, and shape1E, shape2E are the parameters for the prior for efficacy. ```{r, get parameters, message=F, warning=F} library(BDP2) p0=0.12 p1=0.3 pF=0.3 pE=0.12 shape1F=0.3 shape2F=0.7 shape1E=0.12 shape2E=0.88 cF=0.01 cE=0.9 ``` # Figure 1 Figure 1: Posterior distribution of response probability used for futility stop decision: the trial will be stopped for futility if the coloured area is $< c_F$ (left panel). Posterior distribution of response probability used for efficacy calling: the trial will be called efficaceous if the coloured area is $\geq c_E$ (right panel). The Figure also shows the choice of $p_F=p_1$ and of $p_E=p_0$ as discussed in the actual design of the trial. ```{r, Figure 1, fig.show='hold',fig.width=6, fig.height=4} ##plot PF plot(function(x) x,0,0.8,add=F,type="n",col="black",xlab="",ylab="",xaxt="n",yaxt="n",ylim=c(0,4), cex.axis=1.5,cex.lab=1.5,xaxs='i',yaxs='i') plot(function(x) dbeta(x,shape1F+2,shape2F+8),add=T,col="black",lwd=2,lty=1) xy <- seq(0.3,1,length=1000) fxy <- dbeta(xy,shape1F+2,shape2F+8) xyx <- c(1,0.3,xy) yyx <- c(0.0001,0.0001,fxy) polygon(xyx,yyx,col='red') lines(c(0.3,0.3),c(0,dbeta(0.3,shape1F+2,shape2F+8)),lwd=3) axis(side=1,at=c(0.12,0.3),label=c(expression(p[E]),expression(p[F])),cex.axis=1.5) axis(side=1,at=c(0.12,0.3),label=c(expression(paste("=",p[0])),expression(paste("=",p[1]))),cex.axis=1.5,line=1.5,lty=0) text(0.65,0.7,labels=expression(paste("P(p > ",p[F],"| Data)")),cex=1.5) lines(c(0.4,0.5),c(0.5,0.7),lwd=3) ##plot PE plot(function(x) x,0,0.8,add=F,type="n",col="black",xlab="",ylab="",xaxt="n",yaxt="n",ylim=c(0,4), cex.axis=1.5,cex.lab=1.5,xaxs='i',yaxs='i') plot(function(x) dbeta(x,shape1E+2,shape2E+8),add=T,col="black",lwd=2,lty=1) xy <- seq(0.12,1,length=1000) fxy <- dbeta(xy,shape1E+2,shape2E+8) xyx <- c(1,0.12,xy) yyx <- c(0.0001,0.0001,fxy) polygon(xyx,yyx,col='green') lines(c(0.12,0.12),c(0,dbeta(0.12,shape1E+2,shape2E+8)),lwd=3) axis(side=1,at=c(0.12,0.3),label=c(expression(p[E]),expression(p[F])),cex.axis=1.5) axis(side=1,at=c(0.12,0.3),label=c(expression(paste("=",p[0])),expression(paste("=",p[1]))),cex.axis=1.5,line=1.5,lty=0) text(0.65,0.7,labels=expression(paste("P(p > ",p[E],"| Data)")),cex=1.5) lines(c(0.4,0.5),c(0.5,0.7),lwd=3) ``` # Figure 2 Upper tail function for $n=20$, for a design with $p_F=0.3$, $c_F = 0.01$ and prior distribution Be($p_F,1-p_F$) for futility (in red), and $p_E=0.12$, $c_E = 0.9$ and prior distribution Be($p_E,1-p_E$) for efficacy (in green). From the graphs, $b_F(20)=1$ and $b_E(20)=5$. ```{r, Figure 2} n=20 plot(function(x) pbeta(pF,shape1=shape1F+x,shape2=shape2F+n-x,lower.tail = F)-cF, 0,n,ylim=c(-1,1),lwd=3, xlab="x",ylab=expression(paste("P(p>",p[R],"|x,n = 20) - c")),col="red") plot(function(x) pbeta(pE,shape1=shape1E+x,shape2=shape2E+n-x,lower.tail = F)-cE, 0,n,ylim=c(-1,1),lwd=3,col="green",add=TRUE) abline(h=0) legend("bottomright",legend=c(expression(paste("Futility decision: c=",c[F],", ",p[R],"=",p[F])), expression(paste("Efficacy decision: c=",c[E],", ",p[R],"=",p[E]))), lty=1,col = c("red", "green"),cex=1) abline(v=c(0:20),lty=3,col="grey") ``` # Figure 3 Binomial density with zero responders,$(1-p)^n$, for varying $n$, evaluated for $p=p_0=0.12$ and for $p=p_1=0.3$ (left panel). Posterior probabilities $P(p \geq p_F | 0,n)$ and $P(p \geq p_F | 1,n)$ for varying $n$ for $p_F=0.3$ with prior distribution Beta($p_F,1-p_F$) (right panel). ```{r, Figure 3, fig.show='hold',fig.width=7} nmin=4 nmax=15 plotBDP2(x="n",y="Prob0Successes",n=c(nmin,nmax),p0=p0,p1=p1) plotBDP2(x="n",y="PostProb0or1Successes",n=c(nmin,nmax),pF=pF,shape1F=shape1F,shape2F=shape2F) ``` # Figure 4 Probability of calling efficacy at final analysis with $n_\text{final}=20$ patients as a function of $c_E$. Design parameters are $p_F=0.3, p_E=0.12$, prior distributions Beta($p_F,1-p_F$) and Beta($p_E,1-p_E$), $c_F=0.01$ and one interim at $10$ patients. For $p_{true}=p_0=0.12$ this corresponds to type I error, for $p_{true}=p_1=0.3$ this corresponds to power. ```{r, Figure 4,fig.width=6} n=20 interim.at=10 cE=c(7500:9900)/10000 plotBDP2(x = "cE", y = "PEcall", n=n, interim.at=interim.at, p0=p0,p1=p1, pF=pF,cF=cF,pE=pE,cE=cE, shape1F=shape1F,shape2F=shape2F,shape1E=shape1E,shape2E=shape2E, col = c("green", "red")) ``` # Figure 5 Decision boundaries for futility (in red) and efficacy (in green) for a design with $c_F = 0.01$ and $c_E = 0.9$. Other design parameters are $p_F=0.3, p_E=0.12$, prior distributions Beta($p_F,1-p_F$) and Beta($p_E,1-p_E$). ```{r, Figure 5} n=40 cE=0.9 cF=0.01 plotBDP2(x = "n", y = "bFbE", n=n,pF=pF,cF=cF,pE=pE,cE=cE, shape1F=shape1F,shape2F=shape2F,shape1E=shape1E,shape2E=shape2E, col=c("red","green")) ``` # Figure 6 Type I error ($\text{CumP}_{\text{callE}}$) and probability of true stopping ($\text{CumP}_{\text{stopF}}$) for the uninteresting response rate $p=p_0=0.12$ (left panel). Power ($\text{CumP}_{\text{callE}}$) and probability of false stopping ($\text{CumP}_{\text{stopF}}$) for the target response rate $p=p_1=0.3$ (right panel). Other design parameters are $c_F = 0.01$ and $c_E = 0.9$, prior distributions Beta($p_F,1-p_F$) and Beta($p_E,1-p_E$), interim analyses every $10$ patients. ```{r, Figure 6,fig.width=7} nvec=c(18:40) interim.at=c(10,20,30) ptrue=0.12 plotBDP2(x="n", y="PFstopEcall", n =nvec, interim.at = interim.at, pF=pF,cF=cF,pE=pE,cE=cE,ptrue=ptrue,shape1F=shape1F,shape2F=shape2F,shape1E=shape1E,shape2E=shape2E) ptrue=0.3 plotBDP2(x="n", y="PFstopEcall", n =nvec, interim.at = interim.at, pF=pF,cF=cF,pE=pE,cE=cE,ptrue=ptrue,shape1F=shape1F,shape2F=shape2F,shape1E=shape1E,shape2E=shape2E) ``` # Figure 7 Power function ($\text{CumP}_{\text{callE}}$) at $n_\text{final}= 20$ (in green) and $n_\text{final}=30$ (in red) as a function of $p$. Other design parameters are $p_F=0.3, p_E=0.12$, prior distributions Beta($p_F,1-p_F$) and Beta($p_E,1-p_E$), $c_F=0.01$ and $c_E=0.3$, interim analyses every $10$ patients. ```{r, Figure 7,fig.width=6} n=20 interim.at=10 ptrue=c(0:40)/100 plotBDP2(x = "ptrue", y = "PEcall", n=n, interim.at=interim.at, ptrue=ptrue, pF=pF, cF=cF, pE=pE, cE=cE, p0=p0, p1=p1, shape1F=shape1F, shape2F=shape2F, shape1E=shape1E , shape2E=shape2E , col = "green") n=30 interim.at=c(10,20) plotBDP2(x = "ptrue", y = "PEcall", n=n, interim.at=interim.at, ptrue=ptrue, pF=pF, cF=cF, pE=pE, cE=cE, p0=p0, p1=p1, shape1F=shape1F, shape2F=shape2F, shape1E=shape1E , shape2E=shape2E , col = "red",lty=2,add=TRUE) abline(v=0.12,col="grey",lty=2) abline(v=0.3,col="grey",lty=2) ``` # Figure 8 Expected number of patients in the trial for $n_\text{final}= 20$ (in green) and $n_\text{final}=30$ (in red) as a function of $p$. Other design parameters are $p_F=0.3, p_E=0.12$, prior distributions Beta($p_F,1-p_F$) and Beta($p_E,1-p_E$), $c_F=0.01$ and $c_E=0.3$, interim analyses every $10$ patients. Maximal numbers of patients ($n=20$ and $n=30$, resp.) are shown as dotted lines. ```{r, Figure 8,fig.width=6} n=30 interim.at=c(10,20) pvec=c(0:40)/100 interim.at=interim.at[interim.at<n] plotBDP2(x="ptrue", y="ExpectedNumber", n=n,interim.at=interim.at,pF=pF,cF=cF,pE=pE,cE=cE,ptrue=pvec, shape1F=shape1F,shape2F=shape2F,col="red",ylim=c(0,n),cex.lab=1.4) n=20 interim.at=interim.at[interim.at<n] plotBDP2(x="ptrue", y="ExpectedNumber", n=n,interim.at=interim.at,pF=pF,cF=cF,pE=pE,cE=cE,ptrue=pvec, shape1F=shape1F,shape2F=shape2F,col="green",add=TRUE) abline(h=20,col="grey",lty=2) abline(h=30,col="grey",lty=2) ``` # Figure 9 Predictive power (including futility stop) as function of observed responders, evaluated at interim at $10$ patients (left panel) or $20$ patients (right panel). Final analysis at $n_\text{final}= 30$. Other design parameters are $p_F=0.3, p_E=0.12$, prior distributions Beta($p_F,1-p_F$) and Beta($p_E,1-p_E$), $c_F=0.01$ and $c_E=0.3$ ```{r, Figure 9,fig.width=7} interim.at=c(10,20) nfinal=30 plotBDP2(x="k",y="PredictivePower",n=nfinal,interim.at = interim.at, cE=cE,cF=cF, pE=pE,pF=pF, shape1E=shape1E,shape2E=shape2E,shape1F=shape1F,shape2F=shape2F) ``` # Figure 10 Decision boundaries for futility (in red) and efficacy (in green) for a design with $c_F = 0.01$ and $c_E = 0.9$ for up to $100$ enrolled patients. Other design parameters are $p_F=0.3, p_E=0.12$, prior distributions Beta($p_F,1-p_F$) and Beta($p_E,1-p_E$). ```{r, Figure 10} n=100 plotBDP2(x = "n", y = "bFbE", n=n,pF=pF,cF=cF,pE=pE,cE=cE, shape1F=shape1F,shape2F=shape2F,shape1E=shape1E,shape2E=shape2E, col=c("red","green")) ``` Session info ------------ ```{r} sessionInfo() ```
/scratch/gouwar.j/cran-all/cranData/BDP2/vignettes/reproduce_results.Rmd
# simple loglikelihood loglik.sim.dw <- function(lik.par , x , lq.extra , lbeta.extra , logit) { l.l = length(lik.par) if( l.l != 2) stop('error in the number of parameters! ',l.l,' <> T = ',2) q = lik.par[1] * lq.extra beta = lik.par[2] * lbeta.extra if (all(beta >= 0) && all(q<= 1) && all(q >= 0) ){ loglik = sum(log(q^(x^beta)-q^((x+1)^beta))) }else{ loglik = NA } return(loglik) } # loglikelihood - regression on q loglik.q.dw <- function(lik.par , x , y , lq.extra , lbeta.extra , logit ) { l.like.par = length(lik.par) if( l.like.par != ncol(x)+1) stop('error in the number of parameters!',l.like.par,'<> T=',ncol(x)+1) beta = lik.par[ l.like.par] * lbeta.extra theta= lik.par[-l.like.par] * lq.extra if(logit){ q = exp (x %*% theta-log(1+exp(x %*% theta)) ) }else{ q = exp (- exp ( x %*% theta )) } if (all(beta >= 0) && all(q <= 1) && all(q >= 0) ){ loglik = sum(log(q^(y^beta)-q^((y+1)^beta))) }else{ loglik = NA } return(loglik) } # loglikelihood - regression on beta loglik.beta.dw <- function(lik.par , x , y , lq.extra , lbeta.extra , logit) { l.l = length(lik.par) if(l.l != ncol(x)+1) stop('error in the number of parameters!You:',l.l,' <> T = ',ncol(x)+1) q = lik.par[ 1] * lq.extra #par[ length(par)] theta = lik.par[-1] * lbeta.extra #par[-length(par)] beta = exp(x %*% theta) #if(q %in% theta) print('Q in theta!') if (all(beta >= 0) && all(q <= 1) && all(q >= 0) ){ loglik = sum(log(q^(y^beta)-q^((y+1)^beta))) }else{ loglik = NA } return(loglik) } # loglikelihood - regression on both beta and q loglik.qbeta.dw<- function(lik.par , x , y , lq.extra , lbeta.extra , logit) { ncx = ncol(x) l.l = length(lik.par) if( l.l != 2*ncx) stop('error in the number of parameters!',l.l,' <> T = ',2*ncol(x) ) theta.q = lik.par[1: ncx ] * lq.extra theta.beta = tail(lik.par , ncx ) * lbeta.extra x1 = x #+ xxx1 x2 = x #+ xxx2 if(all(x[,1]==1)){ x1[,1]=1 x2[,1]=1 } if(logit){ q = exp(x2 %*% theta.q-log(1+exp(x %*% theta.q))) }else{ q = exp(-exp(x2 %*% theta.q)) } beta = exp(x1 %*% theta.beta) if (all(beta >= 0) && all(q <= 1) && all(q >= 0) ){ loglik = sum(log(q^(y^beta)-q^((y+1)^beta))) }else{ loglik = NA } return(loglik) } ########### end of likelihoods ################## # prior distribution prior.tot.dw <- function(pr.par , q.par , b.par , dist.q , dist.b , lq , lb , l.par , dist.l , penalized , fixed.l , para.q , para.b , lq.extra , lbeta.extra , logit , x = x , y = y , prior.function = prior.function) { #------ Lambda prior parameters if needed par.length = length(pr.par) if((penalized == TRUE) && (fixed.l <= 0) ){ if(par.length != (lb+lq+1)) stop('error in the number of parameters!',par.length,' <> T = ',(lb+lq+1)) #lp = pr.par[(lb+lq+1):par.length] lp = pr.par[par.length] l.par1 = l.par[1] l.par2 = l.par[2] lambda.prior = sum (dist.l(lp , l.par1 , l.par2 , log = TRUE )) }else if ( (penalized == TRUE) && (fixed.l > 0) ){ if(par.length != (lb+lq)) stop('error in the number of parameters!',par.length,' <> T = ' ,(lb+lq)) lambda.prior = 0 lp = fixed.l }else{ if(par.length != (lb+lq)) stop('error in the number of parameters!',par.length,' <> T = ',(lb+lq)) #lp = rep(1,lp+lq) lp = 1 lambda.prior = 0 } #------ Q prior parameters q.par1 = q.par[1] q.par2 = sqrt(lp) * q.par[2] #q.par2 = head(lp,lq)* q.par[2] #------ Beta prior parameters b.par1 = b.par[1] b.par2 = sqrt(lp) * b.par[2] #b.par2 = tail(lp,lb) * b.par[2] #------ model parameters qp = (pr.par[1:lq] ) bp = (pr.par[ (lq+1):(lq+lb)]) #------ priors theta.prior = sum (dist.q(qp , q.par1 , q.par2 , log = TRUE)) gamma.prior = sum (dist.b(bp , b.par1 , b.par2 , log = TRUE)) prior = ( theta.prior + gamma.prior + lambda.prior) return(prior) } # posteriot distribution posterior.tot.dw <- function(par , x , y , lq.extra , lbeta.extra , para.q , para.b , prior.function , ####### END OF PRIOR #### dist.q , q.par , dist.b , b.par , dist.l , l.par , penalized , fixed.l , logit , iter, jeffry, ... ) { iterTresh = 1;jm=5 if ((para.b == FALSE) && (para.q == TRUE)) { loglik = loglik.q.dw (lik.par = par[1:(ncol(x) + 1)], x = x , y = y , lq.extra = lq.extra , lbeta.extra = lbeta.extra, logit = logit) if(jeffry==FALSE){ prior = prior.function(pr.par = par, q.par = q.par , b.par = b.par , dist.q = dist.q , dist.b = dist.b , #lb = 1 , lq = ncol(x)-1 , lb = 1 , lq = ncol(x) , l.par = l.par , dist.l = dist.l , penalized = penalized , fixed.l = fixed.l, ### para.q = para.q , para.b = para.b , lq.extra = lq.extra , lbeta.extra = lbeta.extra, logit = logit , x = x , y = y ) }else if (jeffry==TRUE && (iter>jm*iterTresh) && (iter %% iterTresh == 0)){ #------- jeffry Prior fit = optim(par = par[1:(ncol(x) + 1)], fn = loglik.q.dw, x = x , y = y , lq.extra = lq.extra , lbeta.extra = lbeta.extra, logit = logit, #method = 'BFGS', control=list("fnscale"=-1), hessian=TRUE) fisher_info = solve(-fit$hessian) prior = log(sqrt(det(fisher_info)+10^-16)) }else{ prior = 0 } #------ post = loglik + prior }else if ((para.b == TRUE ) && (para.q == FALSE)) { loglik = loglik.beta.dw(lik.par = par[1:(ncol(x) + 1)], x = x, y = y , lq.extra = lq.extra ,lbeta.extra = lbeta.extra, logit = logit) if (jeffry==FALSE){ prior = prior.function(pr.par = par, q.par = q.par , b.par = b.par , dist.q = dist.q , dist.b = dist.b , dist.l = dist.l , l.par = l.par , #lb = ncol(x)-1 , lq = 1 , lb = ncol(x) , lq = 1 , penalized = penalized , fixed.l = fixed.l, para.q = para.q , para.b = para.b , lq.extra = lq.extra , lbeta.extra = lbeta.extra, logit = logit , x = x , y = y) }else if(jeffry==TRUE && (iter>jm*iterTresh) && (iter %% iterTresh == 0)){ #------- jeffry Prior fit = optim(par = par[1:(ncol(x) + 1)], fn = loglik.beta.dw, x = x , y = y , lq.extra = lq.extra , lbeta.extra = lbeta.extra, logit = logit, #method = 'BFGS', control=list("fnscale"=-1), hessian=TRUE) fisher_info = solve(-fit$hessian) prior = log(sqrt(det(fisher_info)+10^-16)) #------ }else{ prior = 0 } post = loglik + prior }else if ((para.b == TRUE) && (para.q == TRUE)) { loglik = loglik.qbeta.dw(lik.par = par[1:(2*ncol(x))], x = x, y = y , lq.extra = lq.extra ,lbeta.extra = lbeta.extra, logit = logit) if(jeffry==FALSE){ prior = prior.function (pr.par = par , q.par = q.par , b.par = b.par , dist.q = dist.q , dist.b = dist.b , dist.l = dist.l , l.par = l.par , lb = ncol(x) , lq = ncol(x) , penalized = penalized , fixed.l = fixed.l, para.q = para.q , para.b = para.b , lq.extra = lq.extra , lbeta.extra = lbeta.extra, logit = logit , x = x , y = y) }else if(jeffry==TRUE && (iter>jm*iterTresh) && (iter %% iterTresh == 0)){ #------- jeffry Prior fit = optim(par = par[1:(2*ncol(x))], fn = loglik.qbeta.dw, x = x , y = y , lq.extra = lq.extra , lbeta.extra = lbeta.extra, logit = logit, #method = 'BFGS', control=list("fnscale"=-1), hessian=TRUE) fisher_info = solve(-fit$hessian) prior = log(sqrt(det(fisher_info)+10^-16)) #------ }else{ prior = 0 } post = loglik + prior }else{ loglik = loglik.sim.dw (lik.par = par[1:2], x = y , lq.extra = lq.extra ,lbeta.extra = lbeta.extra, logit = logit) if(jeffry==TRUE){ prior = prior.function(pr.par = par , q.par = q.par , b.par = b.par , dist.q = dist.q , dist.b = dist.b , dist.l = dist.l , l.par = l.par , lb = 1 , lq = 1 , penalized = penalized , fixed.l = fixed.l, para.q = para.q , para.b = para.b , lq.extra = lq.extra , lbeta.extra = lbeta.extra, logit = logit , x = x , y = y) }else if(jeffry==TRUE && (iter>jm*iterTresh) && (iter %% iterTresh == 0)){ #------- jeffry Prior # fit = optim(par = par[1:2], # fn = loglik.sim.dw, # x = x , y = y , # lq.extra = lq.extra , # lbeta.extra = lbeta.extra, # logit = logit, # #method = 'BFGS', # control=list("fnscale"=-1), # hessian=TRUE) # fisher_info = solve(-fit$hessian) # prior = log(sqrt(det(fisher_info)+10^-16)) prior = log(((-log(par[1]))^(1/par[2]))/par[2]) }else{ prior = 0 } #------ post = (loglik + prior) } return(post) } # Reversible jumps & Metropolis-Hasting sampling MH.tot.dw <- function(formula, data, startvalue , para.q , para.b , dist.q , dist.b , q.par , b.par , dist.l , l.par , fixed.l , logit , cov.m , penalized , v.scale , iterations , lq.extra, lbeta.extra , prior.function , RJ = FALSE , jeffry = FALSE ) { if ( para.q || para.b ) { call <- match.call() mf <- match.call(expand.dots = TRUE) m <- match(c("formula", "data"), names(mf), 0L) mf <- mf[c(1L, m)] mf$drop.unused.levels <- TRUE mf[[1L]] <- as.name("model.frame") mf <- eval(mf, parent.frame()) mt <- attr(mf, "terms") y <- model.response(mf, "numeric") x <- model.matrix(mt, mf, contrasts) if (para.b == TRUE) {lb = ncol(x)}else{lb = 1} if (para.q == TRUE) {lq = ncol(x)}else{lq = 1} }else{ y = as.vector(data) x = NA lb = lq = 1 RJ = FALSE } # if( is.na(startvalue) ){ # if(para.q || para.b){ # o = DWreg::dw.reg(formula = formula,data = data, # para.q1 = logit * para.q , para.q2 = para.q * !logit, # para.beta = para.b) # startvalue = o$coefficients # if(logit * para.q){ # startvalue = o$tTable$estimate[,1] # }else if (!logit * para.q){ # startvalue = o$tTable[,1] # } # if(penalized){ # startvalue = c(startvalue,max(cov(x,y)) ) # } # }else{ # if(is.matrix(data)) stop('data must have just one column!') # o = DWreg::dw.parest(data = data) # startvalue = c(o$q,o$beta) # } # } len.par = length(startvalue) #### This is for RJ if(RJ){ #message('Reversible-Jump in action ... ') penalized = FALSE ; fixed.l = -1 } total.a.par = lb + lq prob = rep(.5 , total.a.par) # initial probability of existing variables rjmu = rep( 0 , total.a.par) rjsig = rep(.5 , total.a.par) model.chain = c() chain = array(dim = c(iterations + 1 , len.par)); chain[1,] = startvalue ####### Start iterations ####### pr2 = posterior.tot.dw( par = chain[1 , ] , para.q = para.q , para.b = para.b , q.par = q.par , b.par = b.par , dist.q = dist.q , dist.b = dist.b , dist.l = dist.l, l.par = l.par , x = x , y = y , logit = logit , lq.extra = lq.extra , lbeta.extra = lbeta.extra , penalized = penalized , prior.function = prior.function , fixed.l = fixed.l , iter = 1 , jeffry = jeffry ) state = startvalue functionat = pr2 ########################## if(length( startvalue )>1 ) { fit = optim(par = startvalue, fn = posterior.tot.dw, para.q = para.q , para.b = para.b , q.par = q.par , b.par = b.par , dist.q = dist.q , dist.b = dist.b , dist.l = dist.l , l.par = l.par , x = x , y = y, logit = logit , lq.extra = lq.extra , lbeta.extra = lbeta.extra , penalized = penalized , prior.function = prior.function , fixed.l = fixed.l, iter =1 , jeffry = jeffry , control=list("fnscale"=-1),hessian=TRUE) fisher_info = solve(-fit$hessian) prop_sigma = sqrt(diag(fisher_info)+10^-16) prop_sigma = diag(prop_sigma) }else{ prop_sigma<- 1+ chain[1 , ]/2 } mytemp = make.positive.definite(prop_sigma) # Proposal distribution proposalfunction.tot.dw <- function(par , v.scale , para.q, para.b , s , i , cov.m , lb , lq ,tmp){ length.par = length(par) sm = v.scale if (cov.m == 1) { if(i >= 100 && i %% 100 == 0) { sm = dw.cov.matrix(x = s , i = i ) }else{ sm = tmp } ncs = ncol(s) b1 = MASS::mvrnorm(n = 1 , mu = par*0 , Sigma = sm) #b2 = rnorm (n = 1 , mean = 0 , sd = rep(1/ncs , ncs)) prop.d = par+b1 #+ v.scale*b2 }else if (cov.m == 2) { prop.d = par + runif(length.par , -abs(v.scale)/2 , abs(v.scale)/2 ) }else if (cov.m == 3) { prop.d = par + rlaplace(n = length.par , mu = 0 ,sigma = v.scale ) }else{ prop.d = par + rnorm(length.par, 0 , v.scale ) } if (length.par > lb + lq) { lp = (lb + lq + 1):(length.par) prop.d[lp] = abs(prop.d[lp]) } return(list(prop.d=prop.d,sm=sm)) } ######################### # ---- CORE i = 1; j = 1; k = 0 ; ReAc = 0; error = 0 ; it.interval = round(iterations/100) ; interval = 0 while (i <= iterations) { if (i %% it.interval == 0) { acc2 = apply(chain,2, function(x){1-mean(duplicated(x))} ) acceptance =acc2 acceptance = max (acceptance) * 100 info <- paste(round(i/iterations*100), '% done, Acceptance = ',round(acceptance,2),'%') cat('\r ', info ,rep(' ',20)) } if (i < 15) { #just to make sure that the process is not stuck vs = 10 + v.scale } else { vs = v.scale } proposal.raw = proposalfunction.tot.dw(par = chain[i , ], para.q = para.q ,para.b = para.b, v.scale = vs , s = chain , i = i , cov.m = cov.m , lb = lb , lq = lq, tmp = mytemp) proposal=proposal.raw$prop.d mytemp=proposal.raw$sm # To make sure that proposal is not acting on zero parmeters. if(RJ){ zeros = which (chain[i , ] == 0) if(length(zeros) > 0) { proposal[zeros] = 0 } } pr1 = posterior.tot.dw( par = proposal , para.q = para.q , para.b = para.b , q.par = q.par , b.par = b.par , dist.q = dist.q , dist.b = dist.b , dist.l = dist.l , l.par = l.par , x = x , y = y, logit = logit , lq.extra = lq.extra , lbeta.extra = lbeta.extra , penalized = penalized , prior.function = prior.function , fixed.l = fixed.l , iter =i , jeffry = jeffry ) probab = min(1,exp( pr1 - pr2 )) #* correction if (!is.na(probab)) { if ((runif(1) <= probab ) ) { chain[i + 1 , ] = proposal ReAc [i + 1 ] = 1 #pr4 = pr2 pr2 = pr1 }else{ chain[i + 1 , ] = chain[i , ] ReAc [i + 1 ] = 0 #pr4 = pr1 } ###### ----- This is a maximizing procedure ---- ### if (tail(functionat,1) < pr1 ) { state = rbind(state , proposal) functionat = c(functionat,pr1) #cat('\r OK') } ###### END of Maximizing #----- START Riversible jump! sz = 1 # one sample each step! if(lb==1 && lq>1){ interval = 1:lq r = sample(x = interval , size = sz) }else if(lb>1 && lq==1){ interval = 2:total.a.par r = sample(x = interval , size = sz) }else if(lb>1 && lq>1){ interval = 1:total.a.par r = sample(x = interval, size = sz) }else{ RJ = FALSE } if(RJ){ pr4 = pr2 tr = chain[i + 1 , r] newchain = as.vector(chain[i + 1 , ]) if ( all(tr == 0) ){ rv = rnorm(length(r) , rjmu[r] , rjsig[r]) newchain[r] = rv pr3 = posterior.tot.dw( par = newchain , para.q = para.q , para.b = para.b , q.par = q.par , b.par = b.par , dist.q = dist.q , dist.b = dist.b , dist.l = dist.l , l.par = l.par , x = x , y = y , logit = logit , lq.extra = lq.extra , lbeta.extra = lbeta.extra , penalized = penalized , prior.function = prior.function , fixed.l = fixed.l, iter =i , jeffry = jeffry ) # num = pr3 + dnorm(rv , chain[i + 1 , r] , chain[i + 1 , len.par], log = TRUE) + log(prob[r]) num = pr3 + sum(dist.b(rv , b.par[1], b.par[2], log = TRUE)) + sum(log( prob[r])) den = pr4 + sum(dnorm (rv , rjmu[r] , rjsig[r], log = TRUE)) + sum(log(1-prob[r])) }else{ rv = 0 newchain[r] = rv pr3 = posterior.tot.dw( par = newchain , para.q = para.q , para.b = para.b , q.par = q.par , b.par = b.par , dist.q = dist.q , dist.b = dist.b , dist.l = dist.l , l.par = l.par , x = x , y = y , logit = logit , lq.extra = lq.extra , lbeta.extra = lbeta.extra , penalized = penalized , prior.function = prior.function , fixed.l = fixed.l, iter =i , jeffry = jeffry ) #den = pr4 + dnorm(tr , chain[i + 1 , r] , chain[i + 1 , len.par] , log = TRUE) + log(prob[r]) num = pr3 + sum(dnorm (tr , rjmu[r], rjsig[r], log = TRUE)) + sum(log(1-prob[r])) den = pr4 + sum(dist.b(tr ,b.par[1], b.par[2], log = TRUE)) + sum(log( prob[r])) } if(runif(1) <= min(1,exp(num-den)) ){ chain[i + 1 , r] = rv pr2 = pr3 }else{ chain[i + 1 , r] = tr } if(chain[i + 1 , r]==0) adre = -1 else adre = 1 model.chain[i] = adre*r } #----- END Riverseible jump! i = i + 1; j = 1 }else{ j = j + 1; k = k + 1; #cat('\r E:',k) if ( j > 1500 ) stop('error in model! Maybe you need a different set of initial values or model parameters.',call. = 0) } } # --- cat('\r\n') if (k > 0) {cat('\n There are ',k,' ignored values in the process!')} ; error = k return(list( chain = chain , RejAcc = ReAc , error = error , cov.m = cov.m , minf = functionat , minState = state , x = x , y = y , lb = lb , lq = lq , logit = logit , RJ = RJ , model.chain = checkin(model.chain,interval ) ) ) } # semi final function (after is the final algorithm) par.bayesian.tot.dw <- function(formula = NA, data, initials , burn.in , q.par , b.par , dist.q , dist.b , para.q , para.b , dist.l , l.par , fixed.l , logit , v.scale , iterations , cov.m , sampling = c('indp','syst','bin'), ### penalized , lq.extra = 1 , lbeta.extra = 1 , prior.function = prior.tot.dw, RJ = FALSE, jeffry = FALSE, ... ) { #library('MASS') if(RJ & (para.q || para.b)){ #message('Reversible-Jump in action ... ') penalized = FALSE ; fixed.l = -1 }else{ RJ = FALSE } cat('\n\n============================== Sampler configuration ============================== \n') cat('Iterations:',iterations,'\t|', 'Data:' ,is.data.frame(data) , '\t \t|','Length of Initials:',length(initials),'\n') cat('RegQ:',para.q==1 , '\t \t|' ,'RegB:',para.b==1 , '\t \t|','Formula:',is(formula,"formula"),'\n') cat('Logit:',logit==1 , '\t \t|' ,'Scale:',v.scale , '\t\t| Rev.Jumps:',RJ==1,'\n') cat('Penalized:',penalized==1, '\t|' ,'Fixed.penalty:',fixed.l>0, '\t| Jeffrey.Prior:',jeffry==1,'\n') cat('---------------------------------------------------------------------------------- \n' ) cat('Proposal (1=Adaptive MH,2=Uniform,3=Laplace,>3=Gaussian):',cov.m,'\n' ) cat('* if Adaptive MH is activated, then there is no need to set proposal scale.\n' ) cat('---------------------------------------------------------------------------------- \n' ) cat('Chain summary (bin=Burn-in, syst=Systematic, indp=Independent):',sampling,'\n' ) cat('---------------------------------------------------------------------------------- \n' ) cat('* If Penalized=TRUE then you need to set all distributions. \n' ) #cat('---------------------------------------------------------------------------------- \n' ) cat('* If RJ=TRUE then Penalized is automatically set to FALSE and fixed.l diactivates. \n' ) cat('__________________________________________________________________________________ \n' ) # Start the clock! ptm <- proc.time() m.chain=MH.tot.dw(formula = formula , data=data, startvalue = initials, para.b = para.b , para.q = para.q , dist.q = dist.q , dist.b = dist.b , q.par = q.par , b.par = b.par , dist.l = dist.l, l.par = l.par , fixed.l = fixed.l , cov.m = cov.m , v.scale = v.scale , iterations = iterations , penalized = penalized , lq.extra = lq.extra , lbeta.extra = lbeta.extra , prior.function = prior.function , logit = logit , RJ = RJ , jeffry = jeffry ) unused.sample = round(iterations * burn.in) #----- SAMPLING if(sampling =='syst'){ samp.seq = seq(2,iterations,length.out = iterations-unused.sample) samp.seq = round(samp.seq) chain = m.chain$chain [samp.seq,] model.chain= m.chain$model.chain[samp.seq ] }else if(sampling == 'indp'){ samp.seq = sample(x = 2:iterations,size = iterations-unused.sample) chain = m.chain$chain [samp.seq,] model.chain= m.chain$model.chain[samp.seq ] }else{ chain = m.chain$chain [-(1:unused.sample),] model.chain= m.chain$model.chain[-(1:unused.sample) ] } acceptance = apply(chain,2, function(x){1-mean(duplicated(x[x!=0]))}) * 100 # Stop the clock cat('\n Procedure finished in ',( proc.time() - ptm )[1],' seconds. \n') out = list(chain = chain , formula = formula , acceptance.rate = acceptance , data = data , iterations = iterations , q.par = q.par , b.par = b.par , initials = initials, burn.in = burn.in , dist.q = dist.q , dist.b = dist.b , para.b = para.b , para.q = para.q , dist.l = dist.l , l.par = l.par , fixed.l = fixed.l , v.scale = v.scale , sampling = sampling , RejAccChain = m.chain$RejAcc , cov.m = cov.m , jeffry = jeffry , error = m.chain$error , x =m.chain$x , y = m.chain$y , minf = m.chain$minf , minState = m.chain$minState, lq.extra = lq.extra , lbeta.extra = lbeta.extra , penalized = penalized , prior.function = prior.function , lb = m.chain$lb , lq = m.chain$lq , model.chain = model.chain , logit = logit, RJ = m.chain$RJ , duration = proc.time() - ptm ) return(out) } plot.bdw = function(x,est = Mode, prob = 0.95, adj = 2, r.outliers = TRUE, density = FALSE, exc.tun = FALSE , ...){ dw.object = x bdw.plot( dw.object$chain, estimate.statistic = est , adj = adj , remove.outliers = r.outliers, sampling = TRUE , ...) cat('\n =======',round(prob*100),'% Confidence interval ======= \n') dw.HPDinterval ( dw.object,sub='Parameters',prob = prob, bw = adj, remove.outliers = r.outliers, density = density, exclude.tuning = exc.tun,...) } # Draw a plot for bayesian object bdw.plot <- function(dw.object, estimate.statistic = Mode, adj = 1 , truepar = NA, remove.outliers = TRUE, sampling = TRUE ,lw = 3, PlotAdj=c(0,0), lableSize=2, ...) { if(requireNamespace('coda') == FALSE){ stop ('Package Coda is needed in order to execute this function!' ,call. = FALSE) } truepar= as.matrix(truepar) chain = dw.object$chain if(dw.object$fixed.l > 0) {chain = chain[,-ncol(chain)]} #### initials #### acc = dw.object$acceptance.rate; acc=round(acc,2) ncc = ncol(chain) nrc = nrow(chain) nctp = ncol(truepar) col.names = colnames(truepar,do.NULL = FALSE) names = chain.name(ncc,dw.object$lq,dw.object$lb) names2 = extract.vars(dw.object,reg=TRUE) symb.p = names$symb.p symb.p2 = names2$symb.p scl = dw.object$v.scale; scl=round(scl,3) lw = lw col = 3 lty = 3 lsize = lableSize #int.shift = 1.1 if(all(col.names!="")) {cname.chi =col.names}else{cname.chi='E/T'} if(length(scl) == 1) scl = rep(scl,ncc) if(exists('n.repeat',where = dw.object) == TRUE) {nrep=dw.object$n.repeat}else{nrep=1} par(mfrow = c(2,3),cex=.75) for(i in 1:ncc){ chi = chain[,i] chi = na.omit(chi) if((sampling == TRUE) && (nrep>1) ){ schi = sample(chi,nrc/nrep) pchi = chi[seq(1,nrc,length.out = nrc/nrep )] rnd.rep = round(runif(1,0,nrep-1)) /nrep * nrc achi = (rnd.rep+1):(rnd.rep + nrc/nrep) }else{ schi = pchi = achi = chi } if(dw.object$RJ){ schi = schi[schi!=0];if(length(schi)==0){schi=c(0,0)} pchi = pchi[pchi!=0];if(length(pchi)==0){pchi=0} achi = achi[achi!=0];if(length(achi)==0){achi=0} chi =chi [chi !=0];if(length(chi) ==0){chi =0} } m = estimate.statistic(schi);#m=round(m,2) if(remove.outliers == TRUE) { schi = remove_outliers(schi) schi = na.omit(schi) } #schi = c(min(schi)*4/5,schi,max(schi)*6/5) #pchi = c(min(pchi)*4/5,pchi,max(pchi)*6/5) ac=acc[i] hist(schi, add=0, probability = TRUE, #breaks = 30, main = symb.p[i], xlab=paste('Bayesian estimation = ',round(m,2), ', AcR = ', round(ac,5)), xlim=c(min(schi,na.rm = TRUE)-PlotAdj[1],max(schi,na.rm = TRUE)+PlotAdj[2]) , ... ) lines(density(schi,adjust = adj),col='black') if(nrow(truepar) >= i && all(is.na(truepar) == FALSE) ){ abline(v=truepar[i,], col=col:(col+nctp-1), lty=lty:(lty+nctp-1), lw=lw ) legend('topleft', legend = c( paste(cname.chi,':',round(truepar[i,],2)), paste('Bayesian:',round(m,2)) ), seg.len = lsize, #fill = c(col:(col+nctp-1),2), lty = c(lty:(lty+nctp-1),2), col = c(col:(col+nctp-1),2), bg = 'transparent' , lwd=lw-1) } abline(v = m , col = 2 , lw=lw , lty = 2) #abline(...) if (nrc > 50000){ ptype = 'b'} else {ptype='l'} plot(pchi,xlab='Index', #ylim = c(min(pchi)[1]*int.shift,max(pchi)[1]*int.shift), ylab='Estimation', type = ptype , #main=paste('Convergence of parameter ',i ,'/', ncc,sep = ''), main = symb.p[i], col='gray' , pch ='.' , ylim=c(min(pchi,na.rm = TRUE)-PlotAdj[1],max(pchi,na.rm = TRUE)+PlotAdj[2]) ) if(nrow(truepar) >= i && all(is.na(truepar[i,]) == FALSE) ){ abline(h=truepar[i,], col=col:(col+nctp-1), lty=lty:(lty+nctp-1), lw=lw) legend('topleft', legend = c( paste(cname.chi,':',round(truepar[i,],2)), paste('Bayesian:',round(m,2)) ), seg.len = lsize, #fill = c(col:(col+nctp-1),2), lty = c(lty:(lty+nctp-1),2), col = c(col:(col+nctp-1),2), bg = 'transparent' , lwd=lw-1) } abline(h = m , col=2 , lw=lw,lty=2) #ACF must be computed from the ORIGINAL chain! acf=acf(achi,plot = FALSE , lag.max = ceiling(sqrt(nrc/nrep))) if(any(is.nan(acf$acf)== TRUE) ) acf=rep(0,ceiling(sqrt(nrc/nrep))) #plot(acf,type='h',xlab='Lag',ylab='ACF',main=paste('ACF of parameter ',i ,'/', ncc,sep = ''),col='gray') plot(acf,type='h',xlab='Lag',ylab='ACF',main = symb.p[i],col='gray') cat('\r',i,' of ',ncc,' plot completed.') } par(mfrow=c(1,1)) if(dw.object$RJ){ model.chain = dw.object$model.chain h=table(model.chain) h2=length(h)/2 p=(h[(h2+1):(2*h2)]/(h[h2:1]+h[(h2+1):(2*h2)])) bplot= barplot(-h[h2:1],col=2,ylim=c(-1.5*max(abs(h)),2.5*(max(abs(h)))),xpd=1, xaxt='n',density = 80) barplot(h[(h2+1):(2*h2)],add=1,col=3,xpd=1, xaxt='n') #axis(1, at=bplot ,labels=paste('V.',1:(h2),' | ',round(p,2),sep=''),las=3,cex.axis=.8) abline(v=bplot,col='gray',lty=3) axis(1, at=bplot ,labels=symb.p2,las=3,cex.axis=.8) legend('topright', horiz = 1, legend = c('Accepted','Rejected'),col = c(3,2),fill = c(3,2),density = c(100,80)) text (x=bplot,y=1.5*max(abs(h)),labels = paste('+',round(p*100,1),'%')) title(main = 'Reversible-Jumps MH model selection') } #crosscorr.plot(as.mcmc(chain),main='Chain correlation diagram') } ############################# bay.laplace.calc <- function (logpost, mode, ...) { options(warn = -1) fit = optim(mode, logpost, gr = NULL, ..., hessian = TRUE, control = list(fnscale = -1) ) options(warn = 0) mode = fit$par h = -solve(fit$hessian) p = length(mode) int = p/2 * log(2 * pi) + 0.5 * log(det(h)) + logpost(mode, ...) stuff = list(mode = mode, var = h, int = int, converge = fit$convergence == 0) return(stuff) } ########BF dw.BF <- function (dw.object, est.stat = Mode , ...) { options(warn = -1) if (dw.object$chain$RJ){ mode.v = apply (dw.object$chain$chain , 2 , function(x) { x=x[x!=0] ; est.stat(x)} ) }else{ mode.v = apply (dw.object$chain$chain , 2 , est.stat ) } fit = optim( par = mode.v , fn = posterior.tot.dw , gr = NULL, ..., hessian = TRUE , control = list(fnscale = -1) , para.b = dw.object$chain$para.b , para.q = dw.object$chain$para.q , dist.q = dw.object$chain$dist.q , dist.b = dw.object$chain$dist.b , q.par = dw.object$chain$q.par , b.par = dw.object$chain$b.par , dist.l = dw.object$chain$dist.l , l.par = dw.object$chain$l.par , x = dw.object$chain$x , y = dw.object$chain$y , logit = dw.object$chain$logit , lbeta.extra = dw.object$chain$lbeta.extra, lq.extra = dw.object$chain$lq.extra , penalized = dw.object$chain$penalized , prior.function = dw.object$chain$prior.function, fixed.l = dw.object$chain$fixed.l , iter = dw.object$chain$iter , jeffry = dw.object$chain$jeffry ) options(warn = 0) mode = fit$par h = -solve(fit$hessian) p = length(mode) int = p/2 * log(2 * pi) + 0.5 * log(det(h)) + posterior.tot.dw(par = mode, para.b = dw.object$chain$para.b , para.q = dw.object$chain$para.q , dist.q = dw.object$chain$dist.q , dist.b = dw.object$chain$dist.b , q.par = dw.object$chain$q.par , b.par = dw.object$chain$b.par , dist.l = dw.object$chain$dist.l , l.par = dw.object$chain$l.par , x = dw.object$chain$x , y = dw.object$chain$y , logit = dw.object$chain$logit , lbeta.extra = dw.object$chain$lbeta.extra, lq.extra = dw.object$chain$lq.extra , penalized = dw.object$chain$penalized, fixed.l = dw.object$chain$fixed.l , prior.function = dw.object$chain$prior.function, iter = dw.object$chain$iter , jeffry = dw.object$chain$jeffry) stuff = list(mode = mode, var = h, bf = int, converge = fit$convergence == 0 ) return(stuff) } ############################################################################## # Estimate Deviance Information Criterion (DIC) # # References: # Bayesian Data Analysis. # Gelman, A., Carlin, J., Stern, H., and Rubin D. # Second Edition, 2003 # # Bayesian predictive information criterion for the evaluation of # hierarchical Bayesian and empirical Bayes models. # Ando, T. # Biometrika, 2007 # # Input: # x : matrix of posterior samples # lik : vector of the likelihood of the posterior samples # lik.fun : function that calculates the likelihood # ... : other parameters that are passed to 'lik.fun' # # Output: # list() # DIC : Deviance Information Criterion # IC : Bayesian Predictive Information Criterion # pD : Effective number of parameters (pD = Dbar - Dhat) # pV : Effective number of parameters (pV = var(D)/2) # Dbar : Expected value of the deviance over the posterior # Dhat : Deviance at the mean posterior estimate ############################################################################## # calc.dic <- function(x,lik,lik.fun,...) { # D.bar <- -2*mean(lik) # theta.bar <- summary(x)$statistics[,"Mean"] # D.hat <- -2*lik.fun(theta.bar,...) # pD <- D.bar - D.hat # pV <- var(-2*lik)/2 # list(DIC=pD+D.bar,IC=2*pD+D.bar,pD=pD,pV=pV,Dbar=D.bar,Dhat=D.hat) # } dw.info.Criteria = function (dw.object, est.stat = Mode , prob = .95, sample.p = TRUE , ...){ lik = l.tot.dw(dw.object , est.stat = NA , chain.values = TRUE , sample.p = sample.p) D.bar = -2 * mean(lik) D.hat = -2 * (l.tot.dw(dw.object , est.stat = mean , chain.values = FALSE , sample.p = sample.p)) pD = D.bar - D.hat pV = var(-2*lik)/2 ############################# L = ( l.tot.dw(dw.object , est.stat = est.stat , sample.p = sample.p) ) k = dw.object$chain$lb + dw.object$chain$lq if (dw.object$chain$penalized || dw.object$chain$RJ){ zr = dw.HPDinterval(dw.object = dw.object ,prob = prob ,draw = FALSE , density = FALSE ) df = k - sum(zr[1:k,4]) }else{ df =k } n = length(dw.object$chain$y) BIC = -2*L + k * log(n) CAIC = -2*L + k * (log(n)+1) AIC = -2*L + k *2 AICc = AIC + 2*k*(k+1)/(n-k+1) QIC = -2 * (L - k*log(k))/n stuff = list( AIC = AIC , AICc = AICc, BIC = BIC , QIC = QIC , CAIC = CAIC , df = df , DIC=pD+D.bar, BPIC=2*pD+D.bar, pD=pD,pV=pV,Dbar=D.bar,Dhat=D.hat, loglik = L ) return(stuff) } summary.bdw = function(object,est = Mode , prob =.95 , samp = TRUE , ...){ dw.object = object cat('\r Please wait ...') BF = dw.BF (dw.object, est.stat = est , ... ) cr = dw.info.Criteria ( dw.object ,est.stat = est, prob = prob ,sample.p = samp , ...) info = dw.object$chain cat('\r\n', '============================== Sampler ================================ \n' , ' Iterations : ' , info$iterations , '\t Logit : ' , info$logit==1 , '\t Scale : ' ,round(info$v.scale,5) , '\n' , ' Rev.Jump : ' , info$RJ==1 , '\t RegQ : ' , info$para.q==1 ,'\t RegB : ' ,info$para.b==1 , '\n' , ' Penalized : ' , info$penalized==1 , '\t Fixed.penalty : ' , info$fixed.l>0, '\n' , '============================ Model Summary ============================ \n' , ' AIC : ' , cr$AIC , '\t AICc : ' , cr$AICc , '\t BIC : ' , cr$BIC , '\n' , ' QIC : ' , cr$QIC , '\t CAIC : ' , cr$CAIC , '\t LogPPD : ' , BF$bf , '\n' , ' DIC : ' , cr$DIC , '\t PBIC : ' , cr$BPIC , '\t df : ' , cr$df , '\n' , '======================================================================= \n' ) } ######### likelihood l.tot.dw <- function(dw.object , est.stat = Mode , chain.values = FALSE , sample.p ) { para.q = dw.object$chain$para.q para.b = dw.object$chain$para.b l.par = dw.object$chain$lb + dw.object$chain$lq x = dw.object$chain$x y = dw.object$chain$y logit = dw.object$chain$logit lq.extra = dw.object$chain$lq.extra lbeta.extra = dw.object$chain$lbeta.extra if(chain.values == FALSE){ par = apply(dw.object$chain$chain[,1:l.par] , 2 , est.stat) par = matrix(par,nrow=1) }else{ par = dw.object$chain$chain[,1:l.par] ny = nrow(par) smp = sample(1:ny,round(ny*sample.p)) par = par[smp,] } if( (para.b == FALSE) && (para.q == TRUE)){ loglik = apply(X = par , MARGIN = 1 , FUN = loglik.q.dw , x=x , y=y , lq.extra=lq.extra , lbeta.extra=lbeta.extra , logit = logit) }else if((para.b == TRUE ) && (para.q == FALSE)){ loglik = apply(X = par , MARGIN = 1 , FUN = loglik.beta.dw , x=x , y=y , lq.extra=lq.extra , lbeta.extra=lbeta.extra , logit = logit) }else if((para.b == TRUE) && (para.q == TRUE)) { loglik = apply(X = par , MARGIN = 1 , FUN = loglik.qbeta.dw , x=x , y=y , lq.extra=lq.extra , lbeta.extra=lbeta.extra , logit = logit) }else{ loglik = apply(X = par , MARGIN = 1 , FUN = loglik.sim.dw , x=y , lq.extra=lq.extra , lbeta.extra=lbeta.extra , logit = logit) } return( loglik ) } ########### HPDinterval dw.HPDinterval <- function (dw.object , prob = 0.95 , bw = 2.5 , remove.outliers = TRUE , draw = TRUE , density = FALSE , exclude.tuning = FALSE, var.lab = NA ,fixedcol = 1 , ...){ if(requireNamespace('coda') == FALSE){ stop ('Package Coda is needed in order to execute this function!' ,call. = FALSE) } lq = dw.object$chain$lq lb = dw.object$chain$lb chain = dw.object$chain$chain nc.chain = ncol(chain) if((nc.chain> lq+lb) && (exclude.tuning==TRUE)){ chain = chain[,1:(lb+lq)] nc.chain = nc.chain -1 } if (remove.outliers == TRUE){ chi = apply(chain,2,remove_outliers) }else{ chi = chain } if(dw.object$chain$RJ){ est = apply(chi,2,function(x) {x=x[x!=0] ; x=na.omit(x); Mode(x = x)}) res = apply(chi,2,function(x) {x=x[x!=0] ; x=na.omit(x); if(length(x)>5) {coda::HPDinterval(coda::as.mcmc(x),prob = prob)}else{c(-10^-8,10^-8)} }) if(density==TRUE) {d = apply(chi,2,function(x,dw){x=x[x!=0] ; x=na.omit(x); density(na.omit(x),adjust = bw)})} }else{ est = apply(chi,2,function(x) {x=na.omit(x); Mode(x = x)}) res = apply(chi,2,function(x) {x=na.omit(x); if(length(x)>5) {coda::HPDinterval(coda::as.mcmc(x),prob = prob)}else{c(-10^-8,10^-8)} }) if(density==TRUE) {d = apply(chi,2,function(x,dw){x=na.omit(x); density(na.omit(x),adjust = bw)})} } #acc.r = round(dw.object$chain$acceptance.rate,2) chname = chain.name(nc.chain,lq,lb,var.lab) symb = chname$symb symb.p = chname$symb.p las = chname$las marb = chname$marb colnames(res) = symb rownames(res) = c('lower','upper') res=t(res) lower = res[,1] upper = res[,2] Zero.included = apply(res,1,function(x){prod(sign(x))<=0}) if (draw){ if(lb+lq > 20){cexv= 1/log(nrow(res)+1)+.5}else{cexv=1} par(mar =c(marb,4,3,2),cex=cexv) nx = nrow(res) matplot( cbind ( res , est) , col=c(2,3,1) , lty = c ( 3 , 3 , 1 ) , type = c('n' , 'n' , 'p') , xaxt = 'n' , lwd = 1 , pch = c( 0 , 0 , 1 ) , ylim = c(min(res,est,na.rm = 1)-.5,max(res,est,na.rm = 1)+.5), xlim = c(1, ncol(chain)+1) , #xlab = ' \r\n Variables' , ylab = paste(round(prob*100,3),'% HPD interval ') #xlab = paste('Variables, Acceptance rate = ', round(dw.object$chain$acceptance.rate[1],2),'%' ) ) abline ( h = 0 , v =1:nx, col = 'cornsilk2' , lty = 6) title(...) col.count = 1 for(k in 1:nx){ if(abs(res[k,1]-res[k,2]) > 10^-6){ arrows(k , res[k,1] , k , res[k,2] , length = 0.1 , angle = 90 , code = 3 , #col = c ( col.count%%2+2 , col.count%%2+2 ) , col = c(fixedcol*Zero.included[k]+2,fixedcol*Zero.included[k]+2) , lwd = 2, lty = fixedcol*Zero.included[k]*2+1 ) col.count = col.count + 1 } } if(density == TRUE){ for(i in 1:ncol(chain)){ #with(d,expr = lines(d[[i]]$y/2.65+i,(d[[i]]$x) , lwd =1 ,col=(i)%%2+2 ,lty = i%%2+1)) with(d,expr = lines(d[[i]]$y/sd(d[[i]]$y)/4+i,(d[[i]]$x) , lwd =1 ,col= fixedcol*Zero.included[i]+2 ,lty = fixedcol*Zero.included[i]*2+1 ) ) abline(v = i , lty = 3 , col = 'gray') } } axis(1, 1:nx , labels = symb.p , las = las ) if(dw.object$chain$fixed.l <= 0 && dw.object$chain$penalized==TRUE){abline (v = ncol(chain) , lty = 5 , col = 'gray') } } res=cbind(lower,est,upper,Zero.included) return(res) } #### Plot density for a fixed x dw.bay.plot.density <- function (x, dw.object , xmax = 15 , smooth = .5 , draw = TRUE , var.lab = NA , ...){ ncx = ncol(dw.object$chain$x) logit = dw.object$chain$logit if( dw.object$chain$para.q == TRUE && dw.object$chain$para.b == FALSE){ a = 1:ncx b = ncx+1 q.t = cbind(1 , x) %*% as.matrix(dw.object$res[a]) b.t = dw.object$res[b] if(logit){ q = exp(q.t - log ( 1 + exp(q.t) ) ) }else{ q = exp(-exp(q.t )) } beta = rep(b.t , 1) }else if(dw.object$chain$para.q == FALSE && dw.object$chain$para.b == TRUE){ a = 1 b = 2:(ncx+1) q.t = dw.object$res[a] b.t = cbind( 1 , x ) %*% as.matrix(dw.object$res[b]) q = rep( q.t , 1) beta = exp(b.t) }else if(dw.object$chain$para.q == TRUE && dw.object$chain$para.b == TRUE){ a = 1:ncx b = (ncx+1):(2*ncx) q.t = cbind( 1 , x ) %*% as.matrix(dw.object$res[a]) b.t = cbind( 1 , x ) %*% as.matrix(dw.object$res[b]) if(logit){ q = exp(q.t - log ( 1 + exp(q.t) ) ) }else{ q = exp(-exp(q.t )) } beta = exp(b.t) }else{ a = 1 b = 2 q = rep (dw.object$res[a] , 1) beta = rep (dw.object$res[b] , 1) } res = c() d = seq(from = 0 , to = xmax , by = 1 ) for(i in d ){ res[i+1] = ddw(i , q = q , beta = beta ) } res = smooth.spline (res , spar = smooth ) if(draw == TRUE){ plot( res$x , res$y , type = 'l' ,main = 'PMF' , xlab ='x' , ylab = 'pmf' , ...) } return(list ( y = res$y , range = res$x , q = q , beta = beta ) ) } # multicore bdw.mc <- function(dw.object , n.repeat = 10 , cores = 0 ) { if(requireNamespace('foreach') == FALSE | requireNamespace('doParallel') == FALSE | requireNamespace('BDWreg') == FALSE ) stop ('Package needed!') #require('foreach') # Register all cores cat('\r Processing ...') if (cores<1) cores = parallel::detectCores() doParallel::registerDoParallel(cores = cores) ini = dw.object$chain$initials dw.temp.object = dw.object ################### stime = proc.time() i=1 ch4 = foreach(i = 1:n.repeat , .inorder = FALSE ) %dopar% { dw.temp.object$chain$initials = ini/i do.call(par.bayesian.tot.dw , dw.temp.object$chain) } message('Algorithm executed in ',round((proc.time()-stime)[3]) ,' seconds.') chain = ch4[[1]]$chain acceptance.rate = ch4[[1]]$acceptance.rate minf = ch4[[1]]$minf minState = ch4[[1]]$minState RejAccChain = ch4[[1]]$RejAccChain error = ch4[[1]]$error initials = ch4[[1]]$initials model.chain = ch4[[1]]$model.chain ########### foreach::foreach(i = 2:n.repeat,.inorder = TRUE) %do% { chain = rbind(chain , ch4[[i]]$chain) acceptance.rate = (acceptance.rate + ch4[[i]]$acceptance.rate) minf = c(minf , ch4[[i]]$minf) minState = rbind(minState , ch4[[i]]$minState) RejAccChain = c(RejAccChain , ch4[[i]]$RejAccChain) error = c(error + ch4[[i]]$error) initials = rbind(initials , ch4[[i]]$initials) model.chain = c(model.chain , ch4[[i]]$model.chain) cat('\r merging ...',i,' of ' ,n.repeat) } ### close connection here message('Closing connections ...') base::closeAllConnections() message('End.') dw.object$chain$chain=chain dw.object$chain$acceptance.rate=acceptance.rate/n.repeat dw.object$chain$minf=minf dw.object$chain$minState=minState dw.object$chain$RejAccChain=RejAccChain dw.object$chain$error=error dw.object$chain$initials=initials dw.object$chain$n.repeat=n.repeat dw.object$chain$model.chain=model.chain dw.object$chain$iterations=dw.object$chain$iterations*n.repeat dw.object$chain$duration = (proc.time()-stime) dw.object$chain$cores=cores dw.object$all = ch4 class(dw.object) = 'bdw' return(dw.object ) }
/scratch/gouwar.j/cran-all/cranData/BDWreg/R/bayesian.dw.R
# main function bdw<-function(data , formula = NA , reg.q =FALSE , reg.b = FALSE , logit = TRUE , initial = c(.5,.5) , iteration = 25000 , v.scale = 0.1 , RJ = FALSE , dist.q = imp.d , dist.b = imp.d , q.par = c(0,0) , b.par = c(0,0) , penalized = FALSE , dist.l = imp.d , l.par = c(0,0) , bi.period =.25 , cov = 1 , sampling = c('bin'), est = Mode , fixed.l= -1 , jeffrey = FALSE ) { jeffry = jeffrey if (jeffry) { dist.q = imp.d dist.b = imp.d dist.l = imp.d } #Rprof ( tf <- "nplregarma1.log", memory.profiling = TRUE ) chain = par.bayesian.tot.dw(data = data ,formula = formula , para.q = reg.q , para.b = reg.b , q.par = q.par , b.par = b.par , dist.q = dist.q , dist.b = dist.b , dist.l = dist.l , l.par = l.par , initials = initial , burn.in=bi.period , iterations = iteration , fixed.l = fixed.l , v.scale=v.scale , cov.m = cov , sampling = sampling , penalized = penalized, logit = logit , RJ = RJ, jeffry=jeffry ) #Rprof ( NULL ) ; cat ( '\n ------- DEBUG DATA ------- \n' ) ; print ( summaryRprof ( tf ) ) res = apply(chain$chain,2,est) out = list(res=res , chain=chain) class(out) = 'bdw' return(out) }
/scratch/gouwar.j/cran-all/cranData/BDWreg/R/main.R
checkin <- function(x,interval){ nx = length(x) ni = length(interval) x[nx:(nx-ni*2+1)] = c(-interval,interval) return(x) } chain.name <- function (nc.chain, lq, lb, var.lab = NA){ symb.q.p = symb.b.p = list if(lq==1) { symb.q = 'q' symb.q.p = lapply(0, function(i)bquote(q)) }else{ symb.q = paste('Theta',0:(lq-1),sep = '') symb.q.p = lapply(0:(lq-1), function(i)bquote(theta[.(i)])) } if(lb==1) { symb.b = 'B' symb.b.p = lapply(0, function(i)bquote(beta)) }else{ symb.b = paste('Gamma',0:(lb-1),sep = '') symb.b.p = lapply(0:(lb-1), function(i)bquote(gamma[.(i)])) } symb = c(symb.q , symb.b) symb.p = c(symb.q.p , symb.b.p) if((lb+lq) < nc.chain){ symb.l = paste('l', 1:(nc.chain - (lq+lb)) , sep = '') symb.l.p = (lapply(1:(nc.chain - (lq+lb)) , function(i)bquote(lambda[.(i)]))) symb = c (symb , symb.l ) symb.p = c (symb.p , symb.l.p) } if(length(var.lab) > 1){ symb [1:(lb+lq)] = var.lab symb.p = symb las = 2 marb = max(nchar(x = var.lab))/2 }else{ symb.p = as.expression(symb.p) las = 1 marb = 5 } return(list(symb = symb , symb.p = symb.p , las = las , marb = marb) ) } extract.vars = function (dw.object , reg = FALSE){ nc.chain = ncol(dw.object$chain) lq = dw.object$lq lb = dw.object$lb para.q = dw.object$para.q para.b = dw.object$para.b names = chain.name (nc.chain, lq, lb, var.lab = NA) symb.p= names$symb.p symb = names$symb if(reg){ if(para.q & para.b){ symb.p = names$symb.p[1:(lb+lq)] symb = names$symb [1:(lb+lq)] }else if (para.q && !para.b){ symb.p = names$symb.p[1:lq] symb = names$symb [1:lq] }else if (!para.q && para.b){ symb.p = names$symb.p[(lq+1):(lb+lq)] symb = names$symb [(lq+1):(lb+lq)] }else{ symb.p = names$symb.p[1:2] symb = names$symb [1:2] } } return(list(symb=symb,symb.p=symb.p)) } remove_outliers <- function(x, na.rm = TRUE, ...) { qnt <- quantile(x, probs=c(.25, .75), na.rm = na.rm, ...) H <- 1.5 * IQR(x, na.rm = na.rm) y <- x y[x < (qnt[1] - H)] <- NA y[x > (qnt[2] + H)] <- NA return(y) } # find mode of population Mode <- function(x , adj = 1 , na.rm = TRUE , remove.outliers = TRUE) { if(length(x)<50000){ if (remove.outliers){ x = remove_outliers(x,na.rm = na.rm) } x = na.omit(x) } ux <- x #unique(x) if(length(ux)>20){ den<-density(ux,adjust = adj) ux=den$x[which(den$y==max(den$y))] }else{ ux = mean(ux,na.rm = 1) if(is.na(ux)) ux=0 } return(ux[1]) } # improper prior! imp.d<-function(par, ...){ #return(1/abs(par)) #return(1/(1+par^2)) #return(sign(par)/(1+par^2)) return(par) } # laplace distribution plaplace <- function(q, m=0, s=1){ if(any(q<0))stop("q must contain non-negative values") if(any(s<=0))stop("s must be positive") u <- (q-m)/s t <- exp(-abs(u))/2 ifelse(u<0,t,1-t) } dlaplace <- function(x, m=0, s=1, log=FALSE , normalized = TRUE){ #if(any(s<=0))stop("s must be positive") s=abs(s) if(normalized){ ss=s }else{ ss=1 } r=1/ss * exp(-(abs(x-m))/ s) if(log==TRUE) {r=log(r)} return (r) } rlaplace = function(n,mu,sigma){ U = runif(n,0,1) #This will give negative value half of the time sign = ifelse(rbinom(n,1,.5)>.5,1,-1) y = mu + sign*(sigma)/sqrt(2)*log(1-U) y } ddw<-function(x, q=exp(-1),beta=1) { if(max(q)> 1 | min(q) < 0){ stop('q must be between 0 and 1', call. = FALSE) } if(min(beta) <= 0){ stop('beta must be positive', call. = FALSE) } is.wholenumber <-function(x, tol = sqrt(.Machine$double.eps)) { abs(x - round(x)) < tol} for(i in 1:length(beta)){ if(beta==1){ res<-dgeom(x,1-q) } else{ if(is.wholenumber(x)){ res<-q^(x^(beta))-q^((x+1)^(beta)) }else{ res<- 1 #<<<< log(1)=0 print("Warning message: non-integer value in ddw") } } } return(res) } pdw<-function(x,q=exp(-1),beta=1) { if(x<0) res<-0 else res<-1-q^((floor(x)+1)^(beta)) return(res) } qdw<-function(p,q=exp(-1),beta=1) { if(max(q)>1 | min(q) <0) stop('q must be between 0 and 1', call. = FALSE) if(min(beta) <= 0) stop('beta must be positive', call. = FALSE) if(p<=1-q) res<-0 else res<-ceiling((log(1-p)/log(q))^(1/beta)-1) return(res) } rdw<-function(n,q=exp(-1),beta=1) { if(max(q)>1 | min(q)<0){ stop('q must be between 0 and 1', call. = FALSE) } if(min(beta) <=0){ stop('beta must be positive', call. = FALSE) } y<-runif(n,0,1) x<-as.numeric(lapply(y,qdw,q=q,beta=beta)) return(x) } digamma <- function (x, shape, scale = 1, log = FALSE) { if (shape <= 0 | scale <= 0) { stop("Shape or scale parameter negative in dinvgamma().\n") } x=abs(x) alpha <- shape beta <- scale log.density <- alpha * log(beta+10^-10) - lgamma(alpha) - (alpha + 1) * log(x+10^-10) - (beta/x) if(log){ return(log.density) }else{ return(exp(log.density)) } } dw.cov.matrix <- function(x,i){ #per = round(i*exp(-sqrt(i)/1*runif(1,0,.05))) #per = round(i*exp(-4*sqrt(i)/log(i+1)*runif(1,0,.05))) per=99 if((is.matrix(x)==TRUE) & (per>5) ){ res = cov(x[(i-per ):i,]) res = make.positive.definite(res) }else{ res = 1 } return(res) } BF <- function (fun, chain , est.stat = Mode , ...) { options(warn = -1) mode.v = apply (chain , 2 , est.stat ) fit = optim( par = mode.v , fn = fun , gr = NULL, hessian = TRUE , control = list(fnscale = -1) , ... ) options(warn = 0) mode = fit$par diag(fit$hessian)=diag(fit$hessian)+10^-8 h = -solve(fit$hessian) p = length(mode) int = p/2 * log(2 * pi) + 0.5 * log(abs(det(h))) + fun(mode,...) stuff = list(mode = mode, var = h, int = int, converge = fit$convergence == 0 ) return(stuff) } make.positive.definite <- function(m, tol) { # Author: # Copyright 2003-05 Korbinian Strimmer # Rank, condition, and positive definiteness of a matrix # GNU General Public License, Version 2 # Method by Higham 1988 if (!is.matrix(m)) { m = as.matrix(m) } d = dim(m)[1] if ( dim(m)[2] != d ) { stop("Input matrix is not square!") } es = eigen(m) esv = es$values if (missing(tol)) { tol = d*max(abs(esv))*.Machine$double.eps } delta = 2*tol # factor two is just to make sure the resulting # matrix passes all numerical tests of positive definiteness tau = pmax(0, delta - esv) dm = es$vectors %*% diag(tau, d) %*% t(es$vectors) # print(max(DA)) # print(esv[1]/delta) return( m + dm ) } #generalized negative binomial density dgnbinom <- function(y,mu,theta,log=FALSE){ d = gamma(theta+y)/gamma(theta) * (1/factorial(y)) * (1/(mu+theta))^(y+theta) * (mu^y )* (theta^theta) if(log)d=log(d) return(d) }
/scratch/gouwar.j/cran-all/cranData/BDWreg/R/others.R
.onAttach <- function( lib, pkg ) { packageStartupMessage( paste0( '\n ========================================================================', '\n If you have any question about this package and corresponding paper use ', '\n [email protected] ', '\n ========================================================================' ), domain = NULL, appendLF = TRUE ) }
/scratch/gouwar.j/cran-all/cranData/BDWreg/R/zzz.R
## - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - | # Copyright (C) 2012 - 2021 Reza Mohammadi | # | # This file is part of BDgraph package. | # | # BDgraph is free software: you can redistribute it and/or modify it under | # the terms of the GNU General Public License as published by the Free | # Software Foundation; see <https://cran.r-project.org/web/licenses/GPL-3>.| # | # Maintainer: Reza Mohammadi <[email protected]> | ## - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - | # Extract links from an adjacency matrix | ## - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - | adj2link = function( adj ) { G = BDgraph::get_graph( adj ) if( sum( G ) == 0 ) print( " 'adj' has no link. " ) p = ncol( G ) links = vector() for( i in 1:p ) for( j in 1:p ) if( G[ i, j ] == 1 ) links = rbind( links, c( i, j ) ) return( links ) } ## - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - |
/scratch/gouwar.j/cran-all/cranData/BDgraph/R/adj2link.R
## - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - | # Copyright (C) 2012 - 2021 Reza Mohammadi | # | # This file is part of BDgraph package. | # | # BDgraph is free software: you can redistribute it and/or modify it under | # the terms of the GNU General Public License as published by the Free | # Software Foundation; see <https://cran.r-project.org/web/licenses/GPL-3>.| # | # Maintainer: Reza Mohammadi <[email protected]> | ## - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - | # Reports the measures to assess the performance of estimated graphs | ## - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - | auc = function( pred, actual, cut = 200, calibrate = TRUE ) { if( !inherits( pred, "list" ) ) pred = list( pred ) length_pred = length( pred ) if( !is.vector( actual ) ) { adj_G = BDgraph::get_graph( actual ) actual = adj_G[ upper.tri( adj_G ) ] } if( ( sum( actual == 0 ) + sum( actual == 1 ) ) != length( actual ) ) stop( "Elements of 'actual' must be 0 or 1" ) auc_value = vector() for( i in 1:length_pred ) { output_tp_fp = compute_tp_fp( pred = pred[[i]], actual = actual, cut = cut, smooth = FALSE, calibrate = calibrate ) fp = output_tp_fp $ fp tp = output_tp_fp $ tp diffs_x = fp[ -length( fp ) ] - fp[ -1 ] means_vert = ( tp[ -1 ] + tp[ -length( tp ) ] ) / 2 auc_value = c( auc_value, sum( means_vert * diffs_x ) ) } return( auc_value ) } ## - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - |
/scratch/gouwar.j/cran-all/cranData/BDgraph/R/auc.R
## - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - | # Copyright (C) 2012 - 2021 Reza Mohammadi | # | # This file is part of BDgraph package. | # | # BDgraph is free software: you can redistribute it and/or modify it under | # the terms of the GNU General Public License as published by the Free | # Software Foundation; see <https://cran.r-project.org/web/licenses/GPL-3>.| # | # Maintainer: Reza Mohammadi <[email protected]> | ## - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - | # Main function of BDgraph package: BDMCMC algorithm for graphical models | ## - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - | bdgraph = function( data, n = NULL, method = "ggm", algorithm = "bdmcmc", iter = 5000, burnin = iter / 2, not.cont = NULL, g.prior = 0.2, df.prior = 3, g.start = "empty", jump = NULL, save = FALSE, cores = NULL, threshold = 1e-8, verbose = TRUE, nu = 1 ) { if( df.prior < 3 ) stop( "'prior.df' must be >= 3" ) if( iter < burnin ) stop( "'iter' must be higher than 'burnin'" ) burnin <- floor( burnin ) if( is.numeric( verbose ) ) { if( ( verbose < 1 ) | ( verbose > 100 ) ) stop( "'verbose' (for numeric case) must be between ( 1, 100 )" ) trace_mcmc = floor( verbose ) verbose = TRUE }else{ trace_mcmc = ifelse( verbose == TRUE, 10, iter + 1000 ) } list_S_n_p = BDgraph::get_S_n_p( data = data, method = method, n = n, not.cont = not.cont ) S = list_S_n_p $ S n = list_S_n_p $ n p = list_S_n_p $ p method = list_S_n_p $ method data = list_S_n_p $ data colnames_data = list_S_n_p $ colnames_data if( ( is.null( cores ) ) & ( p < 16 ) ) cours = 1 cores = BDgraph::get_cores( cores = cores, verbose = verbose ) if( method == "gcgm" ) { not.cont = list_S_n_p $ not.cont R = list_S_n_p $ R Z = list_S_n_p $ Z gcgm_NA = list_S_n_p $ gcgm_NA } if( method == "tgm" ) { tu = stats::rgamma( n, shape = nu / 2, rate = nu / 2 ) mu = tu %*% data / sum( tu ) S = matrix( 0, p, p ) for( i in 1:n ) { d_mu = data[ i, , drop = FALSE ] - mu S = S + tu[ i ] * t( d_mu ) %*% d_mu } } b = df.prior b_star = b + n D = diag( p ) Ds = D + S Ts = chol( solve( Ds ) ) Ti = chol( solve( D ) ) # only for double Metropolis-Hastings algorithms g_prior = BDgraph::get_g_prior( g.prior = g.prior, p = p ) G = BDgraph::get_g_start( g.start = g.start, g_prior = g_prior, p = p ) K = BDgraph::get_K_start( G = G, g.start = g.start, Ts = Ts, b_star = b_star, threshold = threshold ) if( save == TRUE ) { qp1 = ( p * ( p - 1 ) / 2 ) + 1 string_g = paste( c( rep( 0, qp1 ) ), collapse = '' ) sample_graphs = c( rep ( string_g, iter - burnin ) ) # vector of numbers like "10100" graph_weights = c( rep ( 0, iter - burnin ) ) # waiting time for every state all_graphs = c( rep ( 0, iter - burnin ) ) # vector of numbers like "10100" all_weights = c( rep ( 1, iter - burnin ) ) # waiting time for every state size_sample_g = 0 }else{ p_links = matrix( 0, p, p ) } if( ( verbose == TRUE ) && ( save == TRUE ) && ( p > 50 & iter > 20000 ) ) { cat( " WARNING: Memory needs to run this function is around: " ) print( ( iter - burnin ) * utils::object.size( string_g ), units = "auto" ) } K_hat = matrix( 0, p, p ) last_graph = K_hat last_K = K_hat if( ( is.null( jump ) ) && ( p > 10 & iter > ( 5000 / p ) ) ) jump = floor( p / 10 ) if( is.null( jump ) ) jump = 1 if( ( p < 10 ) && ( jump > 1 ) ) cat( " WARNING: the value of jump should be 1. " ) if( jump > min( p, sqrt( p * 11 ) ) ) cat( " WARNING: the value of jump should be smaller. " ) if( verbose == TRUE ) cat( paste( c( iter, " MCMC sampling ... in progress: \n" ), collapse = "" ) ) # - - main BDMCMC algorithms implemented in C++ - - - - - - - - - - - - - | if( save == TRUE ) { if( ( method == "tgm" ) && ( algorithm == "bdmcmc" ) && ( jump == 1 ) ) { result = .C( "tgm_bdmcmc_map", as.integer(iter), as.integer(burnin), G = as.integer(G), as.double(g_prior), as.double(Ts), K = as.double(K), as.integer(p), as.double(threshold), all_graphs = as.integer(all_graphs), all_weights = as.double(all_weights), K_hat = as.double(K_hat), sample_graphs = as.character(sample_graphs), graph_weights = as.double(graph_weights), size_sample_g = as.integer(size_sample_g), as.integer(b), as.integer(b_star), as.double(D), as.double(Ds), as.integer(trace_mcmc), as.double(data), as.integer(n), as.double(nu), as.double(mu), as.double(tu), PACKAGE = "BDgraph" ) } if( ( method == "ggm" ) && ( algorithm == "bdmcmc" ) && ( jump == 1 ) ) { result = .C( "ggm_bdmcmc_map", as.integer(iter), as.integer(burnin), G = as.integer(G), as.double(g_prior), as.double(Ts), K = as.double(K), as.integer(p), as.double(threshold), all_graphs = as.integer(all_graphs), all_weights = as.double(all_weights), K_hat = as.double(K_hat), sample_graphs = as.character(sample_graphs), graph_weights = as.double(graph_weights), size_sample_g = as.integer(size_sample_g), as.integer(b), as.integer(b_star), as.double(Ds), as.integer(trace_mcmc), PACKAGE = "BDgraph" ) } if( ( method == "ggm" ) && ( algorithm == "bdmcmc" ) && ( jump != 1 ) ) { counter_all_g = 0 result = .C( "ggm_bdmcmc_map_multi_update", as.integer(iter), as.integer(burnin), G = as.integer(G), as.double(g_prior), as.double(Ts), K = as.double(K), as.integer(p), as.double(threshold), all_graphs = as.integer(all_graphs), all_weights = as.double(all_weights), K_hat = as.double(K_hat), sample_graphs = as.character(sample_graphs), graph_weights = as.double(graph_weights), size_sample_g = as.integer(size_sample_g), counter_all_g = as.integer(counter_all_g), as.integer(b), as.integer(b_star), as.double(Ds), as.integer(jump), as.integer(trace_mcmc), PACKAGE = "BDgraph" ) } if( ( method == "ggm" ) && ( algorithm == "rjmcmc" ) ) { result = .C( "ggm_rjmcmc_map", as.integer(iter), as.integer(burnin), G = as.integer(G), as.double(g_prior), as.double(Ts), K = as.double(K), as.integer(p), as.double(threshold), all_graphs = as.integer(all_graphs), all_weights = as.double(all_weights), K_hat = as.double(K_hat), sample_graphs = as.character(sample_graphs), graph_weights = as.double(graph_weights), size_sample_g = as.integer(size_sample_g), as.integer(b), as.integer(b_star), as.double(Ds), as.integer(trace_mcmc), PACKAGE = "BDgraph" ) } if( ( method == "gcgm" ) && ( algorithm == "bdmcmc" ) && ( jump == 1 ) ) { not_continuous = not.cont result = .C( "gcgm_bdmcmc_map", as.integer(iter), as.integer(burnin), G = as.integer(G), as.double(g_prior), as.double(Ts), K = as.double(K), as.integer(p), as.double(threshold), as.double(Z), as.integer(R), as.integer(not_continuous), as.integer(n), as.integer(gcgm_NA), all_graphs = as.integer(all_graphs), all_weights = as.double(all_weights), K_hat = as.double(K_hat), sample_graphs = as.character(sample_graphs), graph_weights = as.double(graph_weights), size_sample_g = as.integer(size_sample_g), as.integer(b), as.integer(b_star), as.double(D), as.double(Ds), as.integer(trace_mcmc), PACKAGE = "BDgraph" ) } if( ( method == "gcgm" ) && ( algorithm == "bdmcmc" ) && ( jump != 1 ) ) { not_continuous = not.cont counter_all_g = 0 result = .C( "gcgm_bdmcmc_map_multi_update", as.integer(iter), as.integer(burnin), G = as.integer(G), as.double(g_prior), as.double(Ts), K = as.double(K), as.integer(p), as.double(threshold), as.double(Z), as.integer(R), as.integer(not_continuous), as.integer(n), as.integer(gcgm_NA), all_graphs = as.integer(all_graphs), all_weights = as.double(all_weights), K_hat = as.double(K_hat), sample_graphs = as.character(sample_graphs), graph_weights = as.double(graph_weights), size_sample_g = as.integer(size_sample_g), counter_all_g = as.integer(counter_all_g), as.integer(b), as.integer(b_star), as.double(D), as.double(Ds), as.integer(jump), as.integer(trace_mcmc), PACKAGE = "BDgraph" ) } if( ( method == "gcgm" ) && ( algorithm == "rjmcmc" ) ) { not_continuous = not.cont result = .C( "gcgm_rjmcmc_map", as.integer(iter), as.integer(burnin), G = as.integer(G), as.double(g_prior), as.double(Ts), K = as.double(K), as.integer(p), as.double(threshold), as.double(Z), as.integer(R), as.integer(not_continuous), as.integer(n), as.integer(gcgm_NA), all_graphs = as.integer(all_graphs), all_weights = as.double(all_weights), K_hat = as.double(K_hat), sample_graphs = as.character(sample_graphs), graph_weights = as.double(graph_weights), size_sample_g = as.integer(size_sample_g), as.integer(b), as.integer(b_star), as.double(D), as.double(Ds), as.integer(trace_mcmc), PACKAGE = "BDgraph" ) } # for Double Metropolis-Hasting if( ( method == "ggm" ) && ( algorithm == "bd-dmh" ) && ( jump == 1 ) ) { result = .C( "ggm_DMH_bdmcmc_map", as.integer(iter), as.integer(burnin), G = as.integer(G), as.double(g_prior), as.double(Ts), as.double(Ti), K = as.double(K), as.integer(p), as.double(threshold), all_graphs = as.integer(all_graphs), all_weights = as.double(all_weights), K_hat = as.double(K_hat), sample_graphs = as.character(sample_graphs), graph_weights = as.double(graph_weights), size_sample_g = as.integer(size_sample_g), as.integer(b), as.integer(b_star), as.double(Ds), as.double(D), as.integer(trace_mcmc), PACKAGE = "BDgraph" ) } if( ( method == "ggm" ) && ( algorithm == "bd-dmh" ) && ( jump != 1 ) ) { counter_all_g = 0 result = .C( "ggm_DMH_bdmcmc_map_multi_update", as.integer(iter), as.integer(burnin), G = as.integer(G), as.double(g_prior), as.double(Ts), as.double(Ti), K = as.double(K), as.integer(p), as.double(threshold), all_graphs = as.integer(all_graphs), all_weights = as.double(all_weights), K_hat = as.double(K_hat), sample_graphs = as.character(sample_graphs), graph_weights = as.double(graph_weights), size_sample_g = as.integer(size_sample_g), counter_all_g = as.integer(counter_all_g), as.integer(b), as.integer(b_star), as.double(Ds), as.double(D), as.integer(jump), as.integer(trace_mcmc), PACKAGE = "BDgraph" ) } if( ( method == "ggm" ) && ( algorithm == "rj-dmh" ) ) { result = .C( "ggm_DMH_rjmcmc_map", as.integer(iter), as.integer(burnin), G = as.integer(G), as.double(g_prior), as.double(Ts), as.double(Ti), K = as.double(K), as.integer(p), as.double(threshold), all_graphs = as.integer(all_graphs), all_weights = as.double(all_weights), K_hat = as.double(K_hat), sample_graphs = as.character(sample_graphs), graph_weights = as.double(graph_weights), size_sample_g = as.integer(size_sample_g), as.integer(b), as.integer(b_star), as.double(Ds), as.double(D), as.integer(trace_mcmc), PACKAGE = "BDgraph" ) } if( ( method == "gcgm" ) && ( algorithm == "bd-dmh" ) && ( jump == 1 ) ) { not_continuous = not.cont result = .C( "gcgm_DMH_bdmcmc_map", as.integer(iter), as.integer(burnin), G = as.integer(G), as.double(g_prior), as.double(Ts), as.double(Ti), K = as.double(K), as.integer(p), as.double(threshold), as.double(Z), as.integer(R), as.integer(not_continuous), as.integer(n), as.integer(gcgm_NA), all_graphs = as.integer(all_graphs), all_weights = as.double(all_weights), K_hat = as.double(K_hat), sample_graphs = as.character(sample_graphs), graph_weights = as.double(graph_weights), size_sample_g = as.integer(size_sample_g), as.integer(b), as.integer(b_star), as.double(D), as.double(Ds), as.integer(trace_mcmc), PACKAGE = "BDgraph" ) } if( ( method == "gcgm" ) && ( algorithm == "bd-dmh" ) && ( jump != 1 ) ) { not_continuous = not.cont counter_all_g = 0 result = .C( "gcgm_DMH_bdmcmc_map_multi_update", as.integer(iter), as.integer(burnin), G = as.integer(G), as.double(g_prior), as.double(Ts), as.double(Ti), K = as.double(K), as.integer(p), as.double(threshold), as.double(Z), as.integer(R), as.integer(not_continuous), as.integer(n), as.integer(gcgm_NA), all_graphs = as.integer(all_graphs), all_weights = as.double(all_weights), K_hat = as.double(K_hat), sample_graphs = as.character(sample_graphs), graph_weights = as.double(graph_weights), size_sample_g = as.integer(size_sample_g), counter_all_g = as.integer(counter_all_g), as.integer(b), as.integer(b_star), as.double(D), as.double(Ds), as.integer(jump), as.integer(trace_mcmc), PACKAGE = "BDgraph" ) } if( ( method == "gcgm" ) && ( algorithm == "rj-dmh" ) ) { not_continuous = not.cont result = .C( "gcgm_DMH_rjmcmc_map", as.integer(iter), as.integer(burnin), G = as.integer(G), as.double(g_prior), as.double(Ts), as.double(Ti), K = as.double(K), as.integer(p), as.double(threshold), as.double(Z), as.integer(R), as.integer(not_continuous), as.integer(n), as.integer(gcgm_NA), all_graphs = as.integer(all_graphs), all_weights = as.double(all_weights), K_hat = as.double(K_hat), sample_graphs = as.character(sample_graphs), graph_weights = as.double(graph_weights), size_sample_g = as.integer(size_sample_g), as.integer(b), as.integer(b_star), as.double(D), as.double(Ds), as.integer(trace_mcmc), PACKAGE = "BDgraph" ) } }else{ if( ( method == "tgm" ) && ( algorithm == "bdmcmc" ) && ( jump == 1 ) ) { # double D[], double data[], int *n, double *nu, double mu[], double tu[] result = .C( "tgm_bdmcmc_ma", as.integer(iter), as.integer(burnin), G = as.integer(G), as.double(g_prior), K = as.double(K), as.integer(p), as.double(threshold), K_hat = as.double(K_hat), p_links = as.double(p_links), as.integer(b), as.integer(b_star), as.integer(trace_mcmc), as.double(D), as.double(data), as.integer(n), as.double(nu), as.double(mu), as.double(tu), PACKAGE = "BDgraph" ) } if( ( method == "ggm" ) && ( algorithm == "bdmcmc" ) && ( jump == 1 ) ) { result = .C( "ggm_bdmcmc_ma", as.integer(iter), as.integer(burnin), G = as.integer(G), as.double(g_prior), as.double(Ts), K = as.double(K), as.integer(p), as.double(threshold), K_hat = as.double(K_hat), p_links = as.double(p_links), as.integer(b), as.integer(b_star), as.double(Ds), as.integer(trace_mcmc), PACKAGE = "BDgraph" ) } if( ( method == "ggm" ) && ( algorithm == "bdmcmc" ) && ( jump != 1 ) ) { result = .C( "ggm_bdmcmc_ma_multi_update", as.integer(iter), as.integer(burnin), G = as.integer(G), as.double(g_prior), as.double(Ts), K = as.double(K), as.integer(p), as.double(threshold), K_hat = as.double(K_hat), p_links = as.double(p_links), as.integer(b), as.integer(b_star), as.double(Ds), as.integer(jump), as.integer(trace_mcmc), PACKAGE = "BDgraph" ) } if( ( method == "ggm" ) && ( algorithm == "rjmcmc" ) ) { result = .C( "ggm_rjmcmc_ma", as.integer(iter), as.integer(burnin), G = as.integer(G), as.double(g_prior), as.double(Ts), K = as.double(K), as.integer(p), as.double(threshold), K_hat = as.double(K_hat), p_links = as.integer(p_links), as.integer(b), as.integer(b_star), as.double(Ds), as.integer(trace_mcmc), PACKAGE = "BDgraph" ) } if( ( method == "gcgm" ) && ( algorithm == "bdmcmc" ) && ( jump == 1 ) ) { not_continuous = not.cont result = .C( "gcgm_bdmcmc_ma", as.integer(iter), as.integer(burnin), G = as.integer(G), as.double(g_prior), as.double(Ts), K = as.double(K), as.integer(p), as.double(threshold), as.double(Z), as.integer(R), as.integer(not_continuous), as.integer(n), as.integer(gcgm_NA), K_hat = as.double(K_hat), p_links = as.double(p_links), as.integer(b), as.integer(b_star), as.double(D), as.double(Ds), as.integer(trace_mcmc), PACKAGE = "BDgraph" ) } if( ( method == "gcgm" ) && ( algorithm == "bdmcmc" ) && ( jump != 1 ) ) { not_continuous = not.cont result = .C( "gcgm_bdmcmc_ma_multi_update", as.integer(iter), as.integer(burnin), G = as.integer(G), as.double(g_prior), as.double(Ts), K = as.double(K), as.integer(p), as.double(threshold), as.double(Z), as.integer(R), as.integer(not_continuous), as.integer(n), as.integer(gcgm_NA), K_hat = as.double(K_hat), p_links = as.double(p_links), as.integer(b), as.integer(b_star), as.double(D), as.double(Ds), as.integer(jump), as.integer(trace_mcmc), PACKAGE = "BDgraph" ) } if( ( method == "gcgm" ) && ( algorithm == "rjmcmc" ) ) { not_continuous = not.cont result = .C( "gcgm_rjmcmc_ma", as.integer(iter), as.integer(burnin), G = as.integer(G), as.double(g_prior), as.double(Ts), K = as.double(K), as.integer(p), as.double(threshold), as.double(Z), as.integer(R), as.integer(not_continuous), as.integer(n), as.integer(gcgm_NA), K_hat = as.double(K_hat), p_links = as.integer(p_links), as.integer(b), as.integer(b_star), as.double(D), as.double(Ds), as.integer(trace_mcmc), PACKAGE = "BDgraph" ) } # for Double Metropolis-Hasting if( ( method == "ggm" ) && ( algorithm == "bd-dmh" ) && ( jump == 1 ) ) { result = .C( "ggm_DMH_bdmcmc_ma", as.integer(iter), as.integer(burnin), G = as.integer(G), as.double(g_prior), as.double(Ts), as.double(Ti), K = as.double(K), as.integer(p), as.double(threshold), K_hat = as.double(K_hat), p_links = as.double(p_links), as.integer(b), as.integer(b_star), as.double(Ds), as.double(D), as.integer(trace_mcmc), PACKAGE = "BDgraph" ) } if( ( method == "ggm" ) && ( algorithm == "bd-dmh" ) && ( jump != 1 ) ) { result = .C( "ggm_DMH_bdmcmc_ma_multi_update", as.integer(iter), as.integer(burnin), G = as.integer(G), as.double(g_prior), as.double(Ts), as.double(Ti), K = as.double(K), as.integer(p), as.double(threshold), K_hat = as.double(K_hat), p_links = as.double(p_links), as.integer(b), as.integer(b_star), as.double(Ds), as.double(D), as.integer(jump), as.integer(trace_mcmc), PACKAGE = "BDgraph" ) } if( ( method == "ggm" ) && ( algorithm == "rj-dmh" ) ) { result = .C( "ggm_DMH_rjmcmc_ma", as.integer(iter), as.integer(burnin), G = as.integer(G), as.double(g_prior), as.double(Ts), as.double(Ti), K = as.double(K), as.integer(p), as.double(threshold), K_hat = as.double(K_hat), p_links = as.integer(p_links), as.integer(b), as.integer(b_star), as.double(Ds), as.double(D), as.integer(trace_mcmc), PACKAGE = "BDgraph" ) } if( ( method == "gcgm" ) && ( algorithm == "bd-dmh" ) && ( jump == 1 ) ) { not_continuous = not.cont result = .C( "gcgm_DMH_bdmcmc_ma", as.integer(iter), as.integer(burnin), G = as.integer(G), as.double(g_prior), as.double(Ts), as.double(Ti), K = as.double(K), as.integer(p), as.double(threshold), as.double(Z), as.integer(R), as.integer(not_continuous), as.integer(n), as.integer(gcgm_NA), K_hat = as.double(K_hat), p_links = as.double(p_links), as.integer(b), as.integer(b_star), as.double(D), as.double(Ds), as.integer(trace_mcmc), PACKAGE = "BDgraph" ) } if( ( method == "gcgm" ) && ( algorithm == "bd-dmh" ) && ( jump != 1 ) ) { not_continuous = not.cont result = .C( "gcgm_DMH_bdmcmc_ma_multi_update", as.integer(iter), as.integer(burnin), G = as.integer(G), as.double(g_prior), as.double(Ts), as.double(Ti), K = as.double(K), as.integer(p), as.double(threshold), as.double(Z), as.integer(R), as.integer(not_continuous), as.integer(n), as.integer(gcgm_NA), K_hat = as.double(K_hat), p_links = as.double(p_links), as.integer(b), as.integer(b_star), as.double(D), as.double(Ds), as.integer(jump), as.integer(trace_mcmc), PACKAGE = "BDgraph" ) } if( ( method == "gcgm" ) && ( algorithm == "rj-dmh" ) ) { not_continuous = not.cont result = .C( "gcgm_DMH_rjmcmc_ma", as.integer(iter), as.integer(burnin), G = as.integer(G), as.double(g_prior), as.double(Ts), as.double(Ti), K = as.double(K), as.integer(p), as.double(threshold), as.double(Z), as.integer(R), as.integer(not_continuous), as.integer(n), as.integer(gcgm_NA), K_hat = as.double(K_hat), p_links = as.integer(p_links), as.integer(b), as.integer(b_star), as.double(D), as.double(Ds), as.integer(trace_mcmc), PACKAGE = "BDgraph" ) } } # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -| K_hat = matrix( result $ K_hat, p, p, dimnames = list( colnames_data, colnames_data ) ) last_graph = matrix( result $ G , p, p, dimnames = list( colnames_data, colnames_data ) ) last_K = matrix( result $ K , p, p ) if( save == TRUE ) { if( ( algorithm == "rjmcmc" ) | ( algorithm == "rj-dmh" ) ) K_hat = K_hat / ( iter - burnin ) size_sample_g = result $ size_sample_g sample_graphs = result $ sample_graphs[ 1 : size_sample_g ] graph_weights = result $ graph_weights[ 1 : size_sample_g ] all_graphs = result $ all_graphs + 1 all_weights = result $ all_weights if( ( jump != 1 ) & ( algorithm != "rjmcmc" ) & ( algorithm != "rj-dmh" ) ) { all_weights = all_weights[ 1 : ( result $ counter_all_g ) ] all_graphs = all_graphs[ 1 : ( result $ counter_all_g ) ] } output = list( sample_graphs = sample_graphs, graph_weights = graph_weights, K_hat = K_hat, all_graphs = all_graphs, all_weights = all_weights, last_graph = last_graph, last_K = last_K, data = data, method = method ) }else{ p_links = matrix( result $ p_links, p, p, dimnames = list( colnames_data, colnames_data ) ) if( ( algorithm == "rjmcmc" ) | ( algorithm == "rj-dmh" ) ) { p_links = p_links / ( iter - burnin ) K_hat = K_hat / ( iter - burnin ) } p_links[ lower.tri( p_links ) ] = 0 output = list( p_links = p_links, K_hat = K_hat, last_graph = last_graph, last_K = last_K, data = data, method = method ) } class( output ) = "bdgraph" return( output ) } ## - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - | # Summary for "bdgraph" object | ## - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - | summary.bdgraph = function( object, round = 2, vis = TRUE, ... ) { K_hat = object $ K_hat p_links = object $ p_links if( is.null( p_links ) ) p_links = BDgraph::plinks( object ) selected_g = BDgraph::select( p_links, cut = 0.5 ) if( vis == TRUE ) { if( !is.null( object $ graph_weights ) ) op = graphics::par( mfrow = c( 2, 2 ), pty = "s", omi = c( 0.1, 0.1, 0.1, 0.1 ), mai = c( 0.3, 0.3, 0.3, 0.3 ) ) # - - - plot selected graph sub_g = "Graph with edge posteriors > 0.5" BDgraph::plot.graph( selected_g, main = "Selected Graph", sub = sub_g, ... ) if( !is.null( object $ graph_weights ) ) { sample_graphs = object $ sample_graphs graph_weights = object $ graph_weights sum_gWeights = sum( graph_weights ) # - - - plot posterior distribution of graph graph_prob = graph_weights / sum_gWeights graphics::plot( x = 1 : length( graph_weights ), y = graph_prob, type = "h", col = "gray60", main = "Graph Posteriors", ylab = "Pr(graph|data)", xlab = "Graph", ylim = c( 0, max( graph_prob ) ) ) # - - - plot posterior distribution of graph size sizesample_graphs = sapply( sample_graphs, function( x ) length( which( unlist( strsplit( as.character( x ), "" ) ) == 1 ) ) ) xx <- unique( sizesample_graphs ) weightsg <- vector() for( i in 1 : length( xx ) ) weightsg[ i ] <- sum( graph_weights[ which( sizesample_graphs == xx[ i ] ) ] ) prob_zg = weightsg / sum_gWeights graphics::plot( x = xx, y = prob_zg, type = "h", col = "gray10", main = "Graphs Size's Posteriors", ylab = "Pr(graph size|data)", xlab = "Graph Size", ylim = c( 0, max( prob_zg ) ) ) # - - - plot trace of graph size all_graphs = object $ all_graphs sizeall_graphs = sizesample_graphs[ all_graphs ] graphics::plot( x = 1 : length( all_graphs ), sizeall_graphs, type = "l", col = "lightblue", main = "Trace of Graph Size", ylab = "Graph size", xlab = "Iteration" ) graphics::par( op ) } } if( is.null( K_hat ) ) return( list( selected_g = selected_g, p_links = round( p_links, round ) ) ) else return( list( selected_g = selected_g, p_links = round( p_links, round ), K_hat = round( K_hat, round ) ) ) } ## - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - | # Plot function for "bdgraph" object | ## - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - | plot.bdgraph = function( x, cut = 0.5, number.g = NULL, main = NULL, layout = igraph::layout_with_fr, vertex.size = 2, vertex.color = "orange", vertex.frame.color = "orange", vertex.label = NULL, vertex.label.dist = 0.5, vertex.label.color = "blue", edge.color = "lightblue", ... ) { if( is.null( number.g ) ) { sub = paste0( "Edge posterior probability = ", cut ) BDgraph::plot.graph( x, cut = cut, sub = sub, main = main, layout = layout, vertex.size = vertex.size, vertex.color = vertex.color, vertex.frame.color = vertex.frame.color, vertex.label = vertex.label, vertex.label.dist = vertex.label.dist, vertex.label.color = vertex.label.color, edge.color = edge.color, ... ) }else{ if( is.null( x $ all_graphs ) ) stop( "'x' must be an object of 'bdgraph()' function with option 'save = TRUE'" ) sample_graphs = x $ sample_graphs graph_weights = x $ graph_weights prob_G = graph_weights / sum( graph_weights ) sort_prob_G = sort( prob_G, decreasing = TRUE ) p = nrow( x $ last_graph ) label = colnames( x $ last_graph ) list_G = replicate( number.g, matrix( 0, p, p, dimnames = list( label, label ) ), simplify = FALSE ) vec_G = c( rep( 0, p * ( p - 1 ) / 2 ) ) if( number.g == 2 ) op <- graphics::par( mfrow = c( 1, 2 ), pty = "s" ) if( number.g > 2 & number.g < 7 ) op <- graphics::par( mfrow = c( 2, number.g %% 2 + trunc( number.g / 2 ) ), pty = "s" ) for( i in 1 : number.g ) { if( number.g > 6 ) grDevices::dev.new() indG_i <- sample_graphs[ which( prob_G == sort_prob_G[i] )[1] ] vec_G <- 0 * vec_G vec_G[ which( unlist( strsplit( as.character(indG_i), "" ) ) == 1 ) ] <- 1 list_G[[i]][ upper.tri( list_G[[i]] ) ] <- vec_G main = ifelse( i == 1, "Graph with highest probability", paste( c( i, "th graph" ), collapse = "" ) ) sub = paste( c( "Posterior probability = ", round( sort_prob_G[i], 6 ) ), collapse = "" ) BDgraph::plot.graph( list_G[[i]], main = main, sub = sub, layout = layout, vertex.size = vertex.size, vertex.color = vertex.color, vertex.frame.color = vertex.frame.color, vertex.label.dist = vertex.label.dist, vertex.label.color = vertex.label.color, edge.color = edge.color, ... ) } if( number.g > 1 & number.g < 7 ) graphics::par( op ) } } ## - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - | # Print function for "bdgraph" object | ## - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - | print.bdgraph = function( x, ... ) { p_links = x $ p_links if( is.null( p_links ) ) p_links = BDgraph::plinks( x ) selected_g = BDgraph::select( p_links, cut = 0.5 ) cat( paste( "\n Adjacency matrix of selected graph \n" ), fill = TRUE ) print( selected_g ) cat( paste( "\n Edge posterior probability of the links \n" ), fill = TRUE ) print( round( p_links, 2 ) ) } ## - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - | # predict function for "bdgraph" object | ## - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - | predict.bdgraph = function( object, iter = 1, ... ) { method = object $ method data = object $ data n_data = nrow( data ) p = ncol( data ) K = object $ K_hat if( is.null( K ) ) { if( isSymmetric( data ) ) { S = data }else{ S = t( data ) %*% data } G = BDgraph::select( bdgraph.obj = object ) sample_K = BDgraph::rgwish( n = 500, adj = G, b = 3 + n_data, D = diag( p ) + S ) K = 0 * G for( i in 1:dim( sample_K )[3] ) K = K + sample_K[[i]] K = K / dim( sample_K )[3] } sigma = solve( K ) Z = BDgraph::rmvnorm( n = iter, mean = 0, sigma = sigma ) if( method == "ggm" ) sample = Z if( method == "tgm" ) { mean = 0 nu = 1 tau_gamma = stats::rgamma( n = iter, shape = nu / 2, rate = nu / 2 ) sample = mean + Z / sqrt( tau_gamma ) } if( method == "gcgm" ) { sample = 0 * Z for( j in 1:p ) { sdj = sqrt( 1 / K[ j, j ] ) # 2a: # variance of component j (given the rest!) muj = - sum( Z[ , -j, drop = FALSE ] %*% K[ -j, j, drop = FALSE ] / K[ j, j ] ) table_j = table( data[ , j ] ) cat_y_j = as.numeric( names( table_j ) ) len_cat_y_j = length( cat_y_j ) if( len_cat_y_j > 1 ) { cum_prop_yj = cumsum( table_j[ -len_cat_y_j ] ) / n_data #cut_j = vector( length = len_cat_y_j - 1 ) # for( k in 1:length( cut_j ) ) cut_j[ k ] = stats::qnorm( cum_prop_yj[ k ] ) cut_j = stats::qnorm( cum_prop_yj, mean = 0, sd = 1 ) breaks = c( min( Z[ , j ] ) - 1, cut_j, max( Z[ , j ] ) + 1 ) ind_sj = as.integer( cut( Z[ , j ], breaks = breaks, right = FALSE ) ) sample[ , j ] = cat_y_j[ ind_sj ] }else{ sample[ , j ] = cat_y_j } } } if( method == "dw" ) { q = object $ q.est beta = object $ beta.est mean = rep( 0, p ) Z = tmvtnorm::rtmvnorm( n = iter, mean = mean, sigma = sigma, lower = rep( -5, length = p ), upper = rep( 5, length = p ) ) pnorm_Z = stats::pnorm( Z ) if( is.matrix( q ) && is.matrix( beta ) ) { for( j in 1 : p ) sample[ ,j ] = BDgraph::qdweibull( pnorm_Z[ , j ], q = q[ , j ], beta = beta[ , j ], zero = TRUE ) } if( is.vector( q ) && is.vector( beta ) ) { for( j in 1 : p ) sample[ , j ] = BDgraph::qdweibull( pnorm_Z[ , j ], q = q[ j ], beta = beta[ j ], zero = TRUE ) } } return( sample ) } ## - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - |
/scratch/gouwar.j/cran-all/cranData/BDgraph/R/bdgraph.R
## - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - | # Copyright (C) 2012 - 2022 Reza Mohammadi | # | # This file is part of BDgraph package. | # | # BDgraph is free software: you can redistribute it and/or modify it under | # the terms of the GNU General Public License as published by the Free | # Software Foundation; see <https://cran.r-project.org/web/licenses/GPL-3>.| # | # Maintainer: Reza Mohammadi <[email protected]> | ## - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - | # BDMCMC algorithm for graphical models based on Discrete Weibull | ## - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - | get_bounds_dw = function( data, q, beta, pii, n, p, zero = TRUE ) { lower_bounds = matrix( 0, nrow = n, ncol = p ) upper_bounds = matrix( 0, nrow = n, ncol = p ) if( is.vector( beta ) ) { for ( j in 1:p ) { for( r in sort( unique( data[ , j ] ) ) ) { ir = ( 1:n )[ data[ , j ] == r & !is.na( data[ , j ] ) ] pdw_lb = BDgraph::pdweibull( r - 1, q = q[ j ], beta = beta[ j ], zero = zero ) pdw_ub = BDgraph::pdweibull( r , q = q[ j ], beta = beta[ j ], zero = zero ) lower_bounds[ ir, j ] = stats::qnorm( ( 1 - pii[ j ] ) * ( r != 0 ) + pii[ j ] * pdw_lb ) upper_bounds[ ir, j ] = stats::qnorm( ( 1 - pii[ j ] ) + pii[ j ] * pdw_ub ) } } } if( is.matrix( beta ) ) { for ( j in 1:p ) { for( r in sort( unique( data[ , j ] ) ) ) { ir = ( 1:n )[ data[ , j ] == r & !is.na( data[ , j ] ) ] pdw_lb = BDgraph::pdweibull( r - 1, q = q[ ir, j ], beta = beta[ ir, j ], zero = zero ) pdw_ub = BDgraph::pdweibull( r , q = q[ ir, j ], beta = beta[ ir, j ], zero = zero ) lower_bounds[ ir, j ] = stats::qnorm( ( 1 - pii[ j ] ) * ( r != 0 ) + pii[ j ] * pdw_lb ) upper_bounds[ ir, j ] = stats::qnorm( ( 1 - pii[ j ] ) + pii[ j ] * pdw_ub ) } } } lower_bounds [ lower_bounds == -Inf ] = - .Machine $ double.xmax upper_bounds [ upper_bounds == Inf ] = .Machine $ double.xmax lower_bounds [ lower_bounds == Inf ] = .Machine $ double.xmax upper_bounds [ upper_bounds == -Inf ] = - .Machine $ double.xmax return( list( lower_bounds = lower_bounds, upper_bounds = upper_bounds ) ) } ## - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - | bdgraph.dw = function( data, x = NULL, formula = y ~ ., n = NULL, algorithm = "bdmcmc", iter = 5000, burnin = iter / 2, g.prior = 0.2, df.prior = 3, ZI = FALSE, iter_bdw = 5000, g.start = "empty",jump = NULL, save = FALSE, q = NULL, beta = NULL, pii = NULL, cores = NULL, threshold = 1e-8, verbose = TRUE ) { if( is.matrix( data ) | is.data.frame( data ) ) if( any( data < 0 ) ) stop( "'data' should not have negative values" ) if( df.prior < 3 ) stop( "'prior.df' must be >= 3" ) if( iter < burnin ) stop( "'iter' must be higher than 'burnin'" ) burnin = floor( burnin ) if( is.numeric( verbose ) ) { if( ( verbose < 1 ) | ( verbose > 100 ) ) stop( "'verbose' (for numeric case) must be between ( 1, 100 )" ) trace_mcmc = floor( verbose ) verbose = TRUE }else{ trace_mcmc = ifelse( verbose == TRUE, 10, iter + 1000 ) } list_S_n_p = BDgraph::get_S_n_p( data = data, method = "dw", n = n, not.cont = NULL ) S = list_S_n_p $ S n = list_S_n_p $ n p = list_S_n_p $ p method = list_S_n_p $ method colnames_data = list_S_n_p $ colnames_data if( ( is.null( cores ) ) & ( p < 16 ) ) cours = 1 cores = BDgraph::get_cores( cores = cores, verbose = verbose ) not.cont = list_S_n_p $ not.cont Z = list_S_n_p $ Z data = list_S_n_p $ data gcgm_NA = list_S_n_p $ gcgm_NA sample_marginals = NULL if( is.null( q ) ) if( inherits( data, "sim" ) ) q = data $ q if( is.null( beta ) ) if( inherits( data, "sim" ) ) beta = data $ beta if( is.null( pii ) ) pii = rep( 1, p ) if( is.null( q ) & is.null( beta ) ) { if( length( ZI ) == 1 ) ZI = rep( ZI, p ) if( length( ZI ) != p ) stop( "'ZI', as a vector, must be of length equal to the number of variables, 'ncol( data )'" ) if( is.null( x ) ) { q = NULL beta = NULL pii = NULL sample_marginals = vector( "list", p ) cat( paste( c( " MCMC sampling of DW regression parameters ... in progress: \n" ), collapse = "" ) ) for( j in 1 : p ) { cat( paste( c(" Marginal regression for node ", j, " " ), collapse = "" ) , "\r" ) xy_j = data.frame( y = data[ , j ] ) est_qbeta = BDgraph::bdw.reg( data = xy_j, formula = formula, ZI = ZI[ j ], iter = iter_bdw ) q[ j ] = est_qbeta $ q.est beta[ j ] = est_qbeta $ beta.est pii[ j ] = est_qbeta $ pi.est sample_marginals[[ j ]] = est_qbeta $ sample } } if( !is.null( x ) ) { q = data * 0 beta = data * 0 pii = vector( length = p ) sample_marginals = vector( "list", p ) cat( paste( c( " MCMC sampling of DW regression parameters... in progress: \n" ), collapse = "" ) ) for( j in 1 : p ) { cat( paste( c(" Marginal regression for node ", j," " ), collapse = "" ) , "\r" ) xy_j = data.frame( x, y = data[ , j ] ) est_qbeta = BDgraph::bdw.reg( data = xy_j, formula = formula, ZI = ZI[ j ], iter = iter_bdw) q[ , j ] = est_qbeta $ q.est beta[ , j ] = est_qbeta $ beta.est pii[ j ] = est_qbeta $ pi.est sample_marginals[[ j ]] = est_qbeta $ sample } } } b = df.prior b_star = b + n D = diag( p ) Ds = D + S Ts = chol( solve( Ds ) ) Ti = chol( solve( D ) ) # only for double Metropolis-Hastings algorithms g_prior = BDgraph::get_g_prior( g.prior = g.prior, p = p ) G = BDgraph::get_g_start( g.start = g.start, g_prior = g_prior, p = p ) K = BDgraph::get_K_start( G = G, g.start = g.start, Ts = Ts, b_star = b_star, threshold = threshold ) if( save == TRUE ) { qp1 = ( p * ( p - 1 ) / 2 ) + 1 string_g = paste( c( rep( 0, qp1 ) ), collapse = '' ) sample_graphs = c( rep ( string_g, iter - burnin ) ) # vector of numbers like "10100" graph_weights = c( rep ( 0, iter - burnin ) ) # waiting time for every state all_graphs = c( rep ( 0, iter - burnin ) ) # vector of numbers like "10100" all_weights = c( rep ( 1, iter - burnin ) ) # waiting time for every state size_sample_g = 0 }else{ p_links = matrix( 0, p, p ) } if( ( verbose == TRUE ) && ( save == TRUE ) && ( p > 50 & iter > 20000 ) ) { cat( " WARNING: Memory needed to run this function is around " ) print( ( iter - burnin ) * utils::object.size( string_g ), units = "auto" ) } K_hat = matrix( 0, p, p ) last_graph = K_hat last_K = K_hat if( ( is.null( jump ) ) && ( p > 10 & iter > ( 5000 / p ) ) ) jump = floor( p / 10 ) if( is.null( jump ) ) jump = 1 if( ( p < 10 ) && ( jump > 1 ) ) cat( " WARNING: the value of jump should be 1 " ) if( jump > min( p, sqrt( p * 11 ) ) ) cat( " WARNING: the value of jump should be smaller " ) if( verbose == TRUE ) cat( paste( c( iter, " MCMC sampling ... in progress: \n" ), collapse = "" ) ) bounds = BDgraph::get_bounds_dw( data = data, q = q, beta = beta, pii = pii, n = n, p = p ) lower_bounds = bounds $ lower_bounds upper_bounds = bounds $ upper_bounds # - - main BDMCMC algorithms implemented in C++ - - - - - - - - - - - - - | if( save == TRUE ) { if( ( algorithm == "bdmcmc" ) && ( jump == 1 ) ) { result = .C( "gcgm_dw_bdmcmc_map", as.integer(iter), as.integer(burnin), G = as.integer(G), as.double(g_prior), as.double(Ts), K = as.double(K), as.integer(p), as.double(threshold), as.double(Z), as.integer(data), as.double(lower_bounds), as.double(upper_bounds), as.integer(n), as.integer(gcgm_NA), all_graphs = as.integer(all_graphs), all_weights = as.double(all_weights), K_hat = as.double(K_hat), sample_graphs = as.character(sample_graphs), graph_weights = as.double(graph_weights), size_sample_g = as.integer(size_sample_g), as.integer(b), as.integer(b_star), as.double(D), as.double(Ds), as.integer(trace_mcmc), PACKAGE = "BDgraph" ) } if( ( algorithm == "bdmcmc" ) && ( jump != 1 ) ) { counter_all_g = 0 result = .C( "gcgm_dw_bdmcmc_map_multi_update", as.integer(iter), as.integer(burnin), G = as.integer(G), as.double(g_prior), as.double(Ts), K = as.double(K), as.integer(p), as.double(threshold), as.double(Z), as.integer(data), as.double(lower_bounds), as.double(upper_bounds), as.integer(n), as.integer(gcgm_NA), all_graphs = as.integer(all_graphs), all_weights = as.double(all_weights), K_hat = as.double(K_hat), sample_graphs = as.character(sample_graphs), graph_weights = as.double(graph_weights), size_sample_g = as.integer(size_sample_g), counter_all_g = as.integer(counter_all_g), as.integer(b), as.integer(b_star), as.double(D), as.double(Ds), as.integer(jump), as.integer(trace_mcmc), PACKAGE = "BDgraph" ) } }else{ if( ( algorithm == "bdmcmc" ) && ( jump == 1 ) ) { result = .C( "gcgm_dw_bdmcmc_ma", as.integer(iter), as.integer(burnin), G = as.integer(G), as.double(g_prior), as.double(Ts), K = as.double(K), as.integer(p), as.double(threshold), as.double(Z), as.integer(data), as.double(lower_bounds), as.double(upper_bounds), as.integer(n), as.integer(gcgm_NA), K_hat = as.double(K_hat), p_links = as.double(p_links), as.integer(b), as.integer(b_star), as.double(D), as.double(Ds), as.integer(trace_mcmc), PACKAGE = "BDgraph" ) } if( ( algorithm == "bdmcmc" ) && ( jump != 1 ) ) { result = .C( "gcgm_dw_bdmcmc_ma_multi_update", as.integer(iter), as.integer(burnin), G = as.integer(G), as.double(g_prior), as.double(Ts), K = as.double(K), as.integer(p), as.double(threshold), as.double(Z), as.integer(data), as.double(lower_bounds), as.double(upper_bounds), as.integer(n), as.integer(gcgm_NA), K_hat = as.double(K_hat), p_links = as.double(p_links), as.integer(b), as.integer(b_star), as.double(D), as.double(Ds), as.integer(jump), as.integer(trace_mcmc), PACKAGE = "BDgraph" ) } } # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -| K_hat = matrix( result $ K_hat, p, p, dimnames = list( colnames_data, colnames_data ) ) last_graph = matrix( result $ G , p, p, dimnames = list( colnames_data, colnames_data ) ) last_K = matrix( result $ K , p, p ) if( save == TRUE ) { if( algorithm == "rjmcmc" ) K_hat = K_hat / ( iter - burnin ) size_sample_g = result $ size_sample_g sample_graphs = result $ sample_graphs[ 1 : size_sample_g ] graph_weights = result $ graph_weights[ 1 : size_sample_g ] all_graphs = result $ all_graphs + 1 all_weights = result $ all_weights if( ( algorithm != "rjmcmc" ) & ( jump != 1 ) ) { all_weights = all_weights[ 1 : ( result $ counter_all_g ) ] all_graphs = all_graphs[ 1 : ( result $ counter_all_g ) ] } output = list( sample_graphs = sample_graphs, graph_weights = graph_weights, K_hat = K_hat, all_graphs = all_graphs, all_weights = all_weights, last_graph = last_graph, last_K = last_K, q.est = q, beta.est = beta, pi.est = pii, data = data, method = "dw" ) }else{ p_links = matrix( result $ p_links, p, p, dimnames = list( colnames_data, colnames_data ) ) if( ( algorithm == "rjmcmc" ) | ( algorithm == "rj-dmh" ) ) { p_links = p_links / ( iter - burnin ) K_hat = K_hat / ( iter - burnin ) } p_links[ lower.tri( p_links ) ] = 0 output = list( p_links = p_links, K_hat = K_hat, last_graph = last_graph, last_K = last_K, q.est = q, beta.est = beta, pi.est = pii, data = data, method = "dw" ) } if( !is.null( sample_marginals ) ) output $ sample_marginals = sample_marginals class( output ) = "bdgraph" return( output ) } ## - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - |
/scratch/gouwar.j/cran-all/cranData/BDgraph/R/bdgraph.dw.R
## - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - | # Copyright (C) 2012 - 2022 Reza Mohammadi | # | # This file is part of BDgraph package. | # | # BDgraph is free software: you can redistribute it and/or modify it under | # the terms of the GNU General Public License as published by the Free | # Software Foundation; see <https://cran.r-project.org/web/licenses/GPL-3>.| # | # Maintainer: Reza Mohammadi <[email protected]> | ## - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - | # BDMCMC algorithm for graphical models based on marginal pseudo-likelihood ## - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - | bdgraph.mpl = function( data, n = NULL, method = "ggm", transfer = TRUE, algorithm = "bdmcmc", iter = 5000, burnin = iter / 2, g.prior = 0.2, g.start = "empty", jump = NULL, alpha = 0.5, save = FALSE, cores = NULL, operator = "or", verbose = TRUE ) { if( iter < burnin ) stop( " 'iter' must be higher than 'burnin'" ) burnin = floor( burnin ) if( is.numeric( verbose ) ) { if( ( verbose < 1 ) | ( verbose > 100 ) ) stop( "'verbose' (for numeric case) must be between ( 1, 100 )" ) trace_mcmc = floor( verbose ) verbose = TRUE }else{ trace_mcmc = ifelse( verbose == TRUE, 10, iter + 1000 ) } if( inherits( data, "sim" ) ) data <- data $ data colnames_data = colnames( data ) if( !is.matrix( data ) & !is.data.frame( data ) ) stop( "Data must be a matrix or dataframe" ) if( is.data.frame( data ) ) data <- data.matrix( data ) if( any( is.na( data ) ) ) stop( "'bdgraph.mpl()' does not deal with missing values. You could use 'bdgraph()' function with option method = 'gcgm'" ) p <- ncol( data ) if( p < 3 ) stop( "Number of variables/nodes ('p') must be more than 2" ) if( is.null( n ) ) n <- nrow( data ) if( ( is.null( cores ) ) & ( p < 16 ) ) cours = 1 cores = BDgraph::get_cores( cores = cores, verbose = verbose ) if( method == "ggm" ) { if( isSymmetric( data ) ) { if ( is.null( n ) ) stop( "Please specify the number of observations 'n'" ) cat( "Input is identified as the covariance matrix \n" ) S <- data }else{ S <- t( data ) %*% data } } if( ( method == "dgm" ) || ( method == "dgm-binary" ) ) { if( transfer == TRUE ) data = transfer( r_data = data ) p = ncol( data ) - 1 freq_data = data[ , p + 1 ] data = data[ , -( p + 1 ) ] n = sum( freq_data ) max_range_nodes = apply( data, 2, max ) max_range_nodes = max_range_nodes + 1 length_f_data = length( freq_data ) } if( method == "dgm-binary" ) if( ( min( data ) != 0 ) || ( max( data ) != 1 ) ) stop( "For the case 'method = \"dgm-binary\"', data must be binary, 0 or 1" ) g_prior = BDgraph::get_g_prior( g.prior = g.prior, p = p ) G = BDgraph::get_g_start( g.start = g.start, g_prior = g_prior, p = p ) if( save == TRUE ) { qp1 = ( p * ( p - 1 ) / 2 ) + 1 string_g = paste( c( rep( 0, qp1 ) ), collapse = '' ) sample_graphs = c( rep ( string_g, iter - burnin ) ) # vector of numbers like "10100" graph_weights = c( rep ( 1, iter - burnin ) ) # waiting time for every state all_graphs = c( rep ( 0, iter - burnin ) ) # vector of numbers like "10100" all_weights = c( rep ( 1, iter - burnin ) ) # waiting time for every state size_sample_g = 0 }else{ p_links = matrix( 0, p, p ) } if( ( verbose == TRUE ) && ( save == TRUE ) && ( p > 50 & iter > 20000 ) ) { cat( " WARNING: Memory needs to run this function is around: " ) print( ( iter - burnin ) * utils::object.size( string_g ), units = "auto" ) } last_graph = matrix( 0, p, p ) if( ( is.null( jump ) ) && ( p > 10 & iter > ( 5000 / p ) ) ) jump = floor( p / 10 ) if( is.null( jump ) ) jump = 1 if( ( p < 10 ) && ( jump > 1 ) ) cat( " WARNING: the value of jump should be 1. " ) if( jump > min( p, sqrt( p * 11 ) ) ) cat( " WARNING: the value of jump should be smaller. " ) if( ( verbose == TRUE ) && ( algorithm != "hc" ) ) cat( paste( c( iter, " MCMC sampling ... in progress: \n" ), collapse = "" ) ) print = floor( iter / 20 ) # - - - main BDMCMC algorithms implemented in C++ - - - - - - - - - - - - -| if( save == TRUE ) { if( ( method == "ggm" ) && ( algorithm == "rjmcmc" ) ) { result = .C( "ggm_rjmcmc_mpl_map", as.integer(iter), as.integer(burnin), G = as.integer(G), as.double(g_prior), as.double(S), as.integer(n), as.integer(p), all_graphs = as.integer(all_graphs), all_weights = as.double(all_weights), sample_graphs = as.character(sample_graphs), graph_weights = as.double(graph_weights), size_sample_g = as.integer(size_sample_g), as.integer(trace_mcmc), PACKAGE = "BDgraph" ) } if( ( method == "ggm" ) && ( algorithm == "bdmcmc" ) && ( jump == 1 ) ) { result = .C( "ggm_bdmcmc_mpl_map", as.integer(iter), as.integer(burnin), G = as.integer(G), as.double(g_prior), as.double(S), as.integer(n), as.integer(p), all_graphs = as.integer(all_graphs), all_weights = as.double(all_weights), sample_graphs = as.character(sample_graphs), graph_weights = as.double(graph_weights), size_sample_g = as.integer(size_sample_g), as.integer(trace_mcmc), PACKAGE = "BDgraph" ) } if( ( method == "ggm" ) && ( algorithm == "bdmcmc" ) && ( jump != 1 ) ) { counter_all_g = 0 result = .C( "ggm_bdmcmc_mpl_map_multi_update", as.integer(iter), as.integer(burnin), G = as.integer(G), as.double(g_prior), as.double(S), as.integer(n), as.integer(p), all_graphs = as.integer(all_graphs), all_weights = as.double(all_weights), sample_graphs = as.character(sample_graphs), graph_weights = as.double(graph_weights), size_sample_g = as.integer(size_sample_g), counter_all_g = as.integer(counter_all_g), as.integer(jump), as.integer(trace_mcmc), PACKAGE = "BDgraph" ) } if( ( method == "dgm" ) && ( algorithm == "rjmcmc" ) ) { result = .C( "dgm_rjmcmc_mpl_map", as.integer(iter), as.integer(burnin), G = as.integer(G), as.double(g_prior), as.integer(data), as.integer(freq_data), as.integer(length_f_data), as.integer(max_range_nodes), as.double(alpha), as.integer(n), as.integer(p), all_graphs = as.integer(all_graphs), all_weights = as.double(all_weights), sample_graphs = as.character(sample_graphs), graph_weights = as.double(graph_weights), size_sample_g = as.integer(size_sample_g), as.integer(trace_mcmc), PACKAGE = "BDgraph" ) } if( ( method == "dgm" ) && ( algorithm == "bdmcmc" ) && ( jump == 1 ) ) { result = .C( "dgm_bdmcmc_mpl_map", as.integer(iter), as.integer(burnin), G = as.integer(G), as.double(g_prior), as.integer(data), as.integer(freq_data), as.integer(length_f_data), as.integer(max_range_nodes), as.double(alpha), as.integer(n), as.integer(p), all_graphs = as.integer(all_graphs), all_weights = as.double(all_weights), sample_graphs = as.character(sample_graphs), graph_weights = as.double(graph_weights), size_sample_g = as.integer(size_sample_g), as.integer(trace_mcmc), PACKAGE = "BDgraph" ) } if( ( method == "dgm-binary" ) && ( algorithm == "bdmcmc" ) && ( jump == 1 ) ) { result = .C( "dgm_bdmcmc_mpl_binary_map", as.integer(iter), as.integer(burnin), G = as.integer(G), as.double(g_prior), as.integer(data), as.integer(freq_data), as.integer(length_f_data), as.double(alpha), as.integer(n), as.integer(p), all_graphs = as.integer(all_graphs), all_weights = as.double(all_weights), sample_graphs = as.character(sample_graphs), graph_weights = as.double(graph_weights), size_sample_g = as.integer(size_sample_g), as.integer(trace_mcmc), PACKAGE = "BDgraph" ) } if( ( method == "dgm" ) && ( algorithm == "bdmcmc" ) && ( jump != 1 ) ) { counter_all_g = 0 result = .C( "dgm_bdmcmc_mpl_map_multi_update", as.integer(iter), as.integer(burnin), G = as.integer(G), as.double(g_prior), as.integer(data), as.integer(freq_data), as.integer(length_f_data), as.integer(max_range_nodes), as.double(alpha), as.integer(n), as.integer(p), all_graphs = as.integer(all_graphs), all_weights = as.double(all_weights), sample_graphs = as.character(sample_graphs), graph_weights = as.double(graph_weights), size_sample_g = as.integer(size_sample_g), counter_all_g = as.integer(counter_all_g), as.integer(jump), as.integer(trace_mcmc), PACKAGE = "BDgraph" ) } if( ( method == "dgm-binary" ) && ( algorithm == "bdmcmc" ) && ( jump != 1 ) ) { counter_all_g = 0 result = .C( "dgm_bdmcmc_mpl_binary_map_multi_update", as.integer(iter), as.integer(burnin), G = as.integer(G), as.double(g_prior), as.integer(data), as.integer(freq_data), as.integer(length_f_data), as.double(alpha), as.integer(n), as.integer(p), all_graphs = as.integer(all_graphs), all_weights = as.double(all_weights), sample_graphs = as.character(sample_graphs), graph_weights = as.double(graph_weights), size_sample_g = as.integer(size_sample_g), counter_all_g = as.integer(counter_all_g), as.integer(jump), as.integer(trace_mcmc), PACKAGE = "BDgraph" ) } }else{ if( ( method == "ggm" ) && ( algorithm == "rjmcmc" ) ) { result = .C( "ggm_rjmcmc_mpl_ma", as.integer(iter), as.integer(burnin), G = as.integer(G), as.double(g_prior), as.double(S), as.integer(n), as.integer(p), p_links = as.double(p_links), as.integer(trace_mcmc), PACKAGE = "BDgraph" ) } if( ( method == "ggm" ) && ( algorithm == "bdmcmc" ) && ( jump == 1 ) ) { result = .C( "ggm_bdmcmc_mpl_ma", as.integer(iter), as.integer(burnin), G = as.integer(G), as.double(g_prior), as.double(S), as.integer(n), as.integer(p), p_links = as.double(p_links), as.integer(trace_mcmc), PACKAGE = "BDgraph" ) } if( ( method == "ggm" ) && ( algorithm == "bdmcmc" ) && ( jump != 1 ) ) { result = .C( "ggm_bdmcmc_mpl_ma_multi_update", as.integer(iter), as.integer(burnin), G = as.integer(G), as.double(g_prior), as.double(S), as.integer(n), as.integer(p), p_links = as.double(p_links), as.integer(jump), as.integer(trace_mcmc), PACKAGE = "BDgraph" ) } if( ( method == "dgm" ) && ( algorithm == "rjmcmc" ) ) { result = .C( "dgm_rjmcmc_mpl_ma", as.integer(iter), as.integer(burnin), G = as.integer(G), as.double(g_prior), as.integer(data), as.integer(freq_data), as.integer(length_f_data), as.integer(max_range_nodes), as.double(alpha), as.integer(n), as.integer(p), p_links = as.double(p_links), as.integer(trace_mcmc), PACKAGE = "BDgraph" ) } if( ( method == "dgm" ) && ( algorithm == "bdmcmc" ) && ( jump == 1 ) ) { result = .C( "dgm_bdmcmc_mpl_ma", as.integer(iter), as.integer(burnin), G = as.integer(G), as.double(g_prior), as.integer(data), as.integer(freq_data), as.integer(length_f_data), as.integer(max_range_nodes), as.double(alpha), as.integer(n), as.integer(p), p_links = as.double(p_links), as.integer(trace_mcmc), PACKAGE = "BDgraph" ) } if( ( method == "dgm-binary" ) && ( algorithm == "bdmcmc" ) && ( jump == 1 ) ) { result = .C( "dgm_bdmcmc_mpl_binary_ma", as.integer(iter), as.integer(burnin), G = as.integer(G), as.double(g_prior), as.integer(data), as.integer(freq_data), as.integer(length_f_data), as.double(alpha), as.integer(n), as.integer(p), p_links = as.double(p_links), as.integer(trace_mcmc), PACKAGE = "BDgraph" ) } if( ( method == "dgm" ) && ( algorithm == "bdmcmc" ) && ( jump != 1 ) ) { result = .C( "dgm_bdmcmc_mpl_ma_multi_update", as.integer(iter), as.integer(burnin), G = as.integer(G), as.double(g_prior), as.integer(data), as.integer(freq_data), as.integer(length_f_data), as.integer(max_range_nodes), as.double(alpha), as.integer(n), as.integer(p), p_links = as.double(p_links), as.integer(jump), as.integer(trace_mcmc), PACKAGE = "BDgraph" ) } if( ( method == "dgm-binary" ) && ( algorithm == "bdmcmc" ) && ( jump != 1 ) ) { result = .C( "dgm_bdmcmc_mpl_binary_ma_multi_update", as.integer(iter), as.integer(burnin), G = as.integer(G), as.double(g_prior), as.integer(data), as.integer(freq_data), as.integer(length_f_data), as.double(alpha), as.integer(n), as.integer(p), p_links = as.double(p_links), as.integer(jump), as.integer(trace_mcmc), PACKAGE = "BDgraph" ) } } # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -| if( algorithm != "hc" ) { last_graph = matrix( result $ G, p, p ) colnames( last_graph ) = colnames_data[1:p] if( save == TRUE ) { size_sample_g = result $ size_sample_g sample_graphs = result $ sample_graphs[ 1 : size_sample_g ] graph_weights = result $ graph_weights[ 1 : size_sample_g ] all_graphs = result $ all_graphs + 1 all_weights = result $ all_weights if( ( algorithm != "rjmcmc" ) & ( jump != 1 ) ) { all_weights = all_weights[ 1 : ( result $ counter_all_g ) ] all_graphs = all_graphs[ 1 : ( result $ counter_all_g ) ] } output = list( sample_graphs = sample_graphs, graph_weights = graph_weights, all_graphs = all_graphs, all_weights = all_weights, last_graph = last_graph, data = data, method = method ) }else{ p_links = matrix( result $ p_links, p, p ) if( algorithm == "rjmcmc" ) p_links = p_links / ( iter - burnin ) p_links[ lower.tri( p_links ) ] = 0 colnames( p_links ) = colnames_data[1:p] output = list( p_links = p_links, last_graph = last_graph, data = data, method = method ) } }else{ if( method == "dgm" ) selected_graph = hill_climb_mpl( data = data, freq_data = freq_data, n = n, max_range_nodes = max_range_nodes, alpha = alpha, operator = operator ) if( method == "dgm-binary" ) selected_graph = hill_climb_mpl_binary( data = data, freq_data = freq_data, n = n, alpha = alpha, operator = operator ) colnames( selected_graph ) = colnames_data[ 1:p ] output = list( selected_graph = selected_graph, data = data, method = method ) } # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -| class( output ) = "bdgraph" return( output ) } ## - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - |
/scratch/gouwar.j/cran-all/cranData/BDgraph/R/bdgraph.mpl.R
## - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - | # Copyright (C) 2012 - 2021 Reza Mohammadi | # | # This file is part of BDgraph package. | # | # BDgraph is free software: you can redistribute it and/or modify it under | # the terms of the GNU General Public License as published by the Free | # Software Foundation; see <https://cran.r-project.org/web/licenses/GPL-3>.| # | # Maintainer: Reza Mohammadi <[email protected]> | ## - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - | # Non-parametric transfer function for non-normal data | ## - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - | bdgraph.npn = function( data, npn = "shrinkage", npn.thresh = NULL ) { if( inherits( data, "sim" ) ) data <- data $ data if( !is.matrix( data ) & !is.data.frame( data ) ) stop( "Data must be a matrix or dataframe" ) if( is.data.frame( data ) ) data = data.matrix( data ) if( any( is.na( data ) ) ) stop( "Data must contain no missing values" ) n <- nrow( data ) # - - - shrinkage transfer - - - - - - - - - - - - - - - - - - - - - - - - | if( npn == "shrinkage" ) { data = stats::qnorm( apply( data, 2, rank ) / ( n + 1 ) ) #data = data / stats::sd( data[ , 1 ] ) data = t( ( t( data ) - apply( data, 2, mean ) ) / apply( data, 2, stats::sd ) ) } # - - - truncation transfer - - - - - - - - - - - - - - - - - - - - - - - -| if( npn == "truncation" ) { if( is.null( npn.thresh ) ) npn.thresh = 0.25 * ( n ^ ( -0.25 ) ) * ( pi * log( n ) ) ^ ( -0.5 ) data = stats::qnorm( pmin( pmax( apply( data, 2, rank ) / n, npn.thresh ), 1 - npn.thresh ) ) data = data / stats::sd( data[ , 1 ] ) } # - - - skeptic transfer - - - - - - - - - - - - - - - - - - - - - - - - - | if( npn == "skeptic" ) data = 2 * sin( pi / 6 * stats::cor( data, method = "spearman" ) ) return( data ) } ## - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - |
/scratch/gouwar.j/cran-all/cranData/BDgraph/R/bdgraph.npn.R
## - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - | # Copyright (C) 2012 - 2022 Reza Mohammadi | # | # This file is part of BDgraph package. | # | # BDgraph is free software: you can redistribute it and/or modify it under | # the terms of the GNU General Public License as published by the Free | # Software Foundation; see <https://cran.r-project.org/web/licenses/GPL-3>.| # | # Maintainer: Reza Mohammadi <[email protected]> | ## - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - | # Data generator according to the graph structure | ## - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - | bdgraph.sim = function( p = 10, graph = "random", n = 0, type = "Gaussian", prob = 0.2, size = NULL, mean = 0, class = NULL, cut = 4, b = 3, D = diag( p ), K = NULL, sigma = NULL, q = exp( -1 ), beta = 1, vis = FALSE, rewire = 0.05, range.mu = c( 3, 5 ), range.dispersion = c( 0.01, 0.1 ), nu = 1 ) { if( p < 2 ) stop( "'p' must be greater than 1" ) if( ( prob < 0 ) | ( prob > 1 ) ) stop( "'prob' must be between ( 0, 1 )" ) if( cut < 2 ) stop( "'cut' must be greater than 1" ) if( b <= 2 ) stop( "'b' must be greater than 2" ) if( ( rewire < 0 ) | ( rewire > 1 ) ) stop( "'rewire' must be between ( 0, 1 )" ) if( length( range.mu ) != 2 ) stop( "'range.mu' must be a vector with length 2" ) if( length( range.dispersion ) != 2 ) stop( "'range.dispersion' must be a vector with length 2" ) if( inherits( graph, "graph" ) ) graph = unclass( graph ) if( is.matrix( graph ) & is.matrix( K ) ) if( nrow( graph ) != nrow( K ) ) stop( "'graph' and 'K' have non-conforming size" ) if( !is.null( size ) ) if( ( sum( size ) < 0 ) | ( sum( size ) > ( p * ( p - 1 ) / 2 ) ) ) stop( "'size' must be between ( 0, p*(p-1)/2 )" ) if( is.matrix( K ) ) { if( !isSymmetric( K ) ) stop( "'K' must be a positive definite matrix" ) graph <- "fixed" p <- nrow( K ) } if( type == "normal" ) type = "Gaussian" if( type == "non-normal" ) type = "non-Gaussian" #if( type == "discrete" ) type = "count" if( ( type == "categorical" ) & ( cut == 2 ) ) type = "binary" if( is.matrix( graph ) ) { if( !isSymmetric( graph ) ) stop( "'graph' must be symmetric matrix" ) p = nrow( graph ) if( ( graph != 0 ) && ( graph != 1 ) ) stop( "Elements of matrix 'graph' must be 0 or 1" ) G <- graph graph <- "fixed" } # - - build the graph structure - - - - - - - - - - - - - - - - - - - - - -| if( !any( graph == c( "fixed", "AR1", "AR2", "circle" ) ) ) G <- BDgraph::graph.sim( p = p, graph = graph, prob = prob, size = size, class = class, rewire = rewire ) if( graph == "AR1" ) { sigma = matrix( 0, p, p ) for( i in 1 : ( p - 1 ) ) for( j in ( i + 1 ) : p ) sigma[ i, j ] = ( 0.7 ) ^ abs( i - j ) sigma = sigma + t( sigma ) + diag( p ) K = solve( sigma ) G = 1 * ( abs( K ) > 0.02 ) } if( graph == "AR2" ) { K = stats::toeplitz( c( 1, 0.5, 0.25, rep( 0, p - 3 ) ) ) G = 1 * ( abs( K ) > 0.02 ) } if( graph == "circle" ) { K <- stats::toeplitz( c( 1, 0.5, rep( 0, p - 2 ) ) ) K[ 1, p ] <- 0.4 K[ p, 1 ] <- 0.4 G = 1 * ( abs( K ) > 0.02 ) } # - - generate multivariate data according to the graph structure - - - - -| if( n != 0 ) { if( !is.null( sigma ) ) K <- solve( sigma ) if( is.matrix( K ) ) { G = 1 * ( abs( K ) > 0.02 ) diag( G ) = 0 # if( is.null( sigma ) ) sigma <- solve( K ) if( is.null( sigma ) ) sigma = stats::cov2cor( solve( K ) ) }else{ # - - Generate precision matrix according to the graph structure - | if( !isSymmetric( D ) ) stop( "'D' must be a positive definite matrix" ) Ti = chol( solve( D ) ) diag( G ) = 0 K = matrix( 0, p, p ) threshold = 1e-8 # for "rgwish_c" function in C++ result = .C( "rgwish_c", as.integer(G), as.double(Ti), K = as.double(K), as.integer(b), as.integer(p), as.double(threshold), PACKAGE = "BDgraph" ) K = matrix( result $ K, p, p ) # sigma = solve( K ) sigma = stats::cov2cor( solve( K ) ) K = solve( sigma ) } # - - generate multivariate normal data - - - - - - - - - - - - - - - -| d <- BDgraph::rmvnorm( n = n, mean = mean, sigma = sigma ) # - - generate multivariate mixed data - - - - - - - - - - - - - - - - | not.cont = numeric( p ) if( type == "mixed" ) { # generating mixed data which are 'count', 'ordinal', 'non-Gaussian', # 'binary', and 'Gaussian', respectively. ps = floor( p / 5 ) # generating count data col_number <- c( 1:ps ) prob <- stats::pnorm( d[ , col_number ] ) d[ , col_number ] <- stats::qpois( p = prob, lambda = 10 ) not.cont[ 1:ps ] = 1 # generating ordinal data col_number <- c( ( ps + 1 ):( 2 * ps ) ) prob <- stats::pnorm( d[ , col_number ] ) d[ , col_number ] <- stats::qpois( p = prob, lambda = 2 ) not.cont[ c( ( ps + 1 ):( 2 * ps ) ) ] = 1 # generating non-Gaussian data col_number <- c( ( 2 * ps + 1 ):( 3 * ps ) ) prob <- stats::pnorm( d[ , col_number ] ) d[ ,col_number ] <- stats::qexp( p = prob, rate = 10 ) # for binary data col_number <- c( ( 3 * ps + 1 ):( 4 * ps ) ) prob <- stats::pnorm( d[ , col_number ] ) d[ , col_number ] <- stats::qbinom( p = prob, size = 1, prob = 0.5 ) not.cont[ c( ( 3 * ps + 1 ):( 4 * ps ) ) ] = 1 } # - - generate multivariate continuous non-Gaussian data - - - - - - - | if( type == "non-Gaussian" ) { # generating multivariate continuous non-Gaussian data prob <- stats::pnorm( d ) d <- stats::qexp( p = prob, rate = 10 ) } # - - To generate multivariate data from T-distribution - - - - - - - | if( type == "t" ) { tau_gamma = stats::rgamma( n, shape = nu / 2, rate = nu / 2 ) d = mean + d / sqrt( tau_gamma ) } if ( type == "alternative-t" ) { taugamma = stats::rgamma( n * p, shape = nu / 2, rate = nu / 2 ) taugamma = matrix( taugamma, n, p ) d = mean + d / sqrt( taugamma ) } # - - generate multivariate count data - - - - - - - - - - - - - - - - | if( type == "categorical" ) { not.cont[ 1:p ] = 1 runif_m = matrix( stats::runif( cut * p ), nrow = p, ncol = cut ) marginals = apply( runif_m, 1, function( x ) { stats::qnorm( cumsum( x / sum( x ) )[ -length( x ) ] ) } ) if( cut == 2 ) marginals = matrix( marginals, nrow = 1, ncol = p ) for( j in 1:p ) { breaks <- c( min( d[ , j ] ) - 1, marginals[ , j ], max( d[ , j ] ) + 1 ) d[ , j ] <- as.integer( cut( d[ , j ], breaks = breaks, right = FALSE ) ) } d = d - 1 } if( type == "binary" ) { not.cont[ 1:p ] = 1 if( p > 16 ) stop( "'p' must be less than 16, for option 'type = \"binary\"'" ) ## Generate clique factors clique_factors = generate_clique_factors( ug = G ) d = sample_ug( n = n, ug = G, clique_factors = clique_factors ) d = d - 1 } if( ( type == "dweibull" ) |( type == "dw" ) ) { if( length( q ) == 1 ) q = rep( q , time = p ) if( length( beta ) == 1 ) beta = rep( beta, time = p ) # q & beta can be a vector of length p (one for each Y variable) if( is.vector( q ) && ( length( q ) != p ) ) stop( "'q', as a vector, has non-conforming size with 'p'" ) if( is.vector( beta ) && ( length( beta ) != p ) ) stop( "'beta', as a vector, has non-conforming size with 'p'" ) # or an n x p matrix (in the case of covariates) if( is.matrix( q ) && any( dim( q ) != c( n, p ) ) ) stop( "'q', as a matrix, has non-conforming size with 'n' and 'p'" ) if( is.matrix( beta ) && any( dim( beta ) != c( n, p ) ) ) stop( "'beta', as a matrix, has non-conforming size with 'n' and 'p'" ) not.cont[ 1:p ] = 1 Y_data <- matrix( c( 0, 1 ), nrow = n, ncol = p ) # detect binary variables while( any( apply( Y_data, 2, function( x ) { all( x %in% 0:1 ) } ) ) == TRUE ) { d = matrix( 0, nrow = n, ncol = p ) Z = tmvtnorm::rtmvnorm( n = n, mean = rep( mean, p ), sigma = sigma, lower = rep( -5, length = p ), upper = rep( 5, length = p ) ) pnorm_Z = stats::pnorm( Z ) if( is.matrix( q ) && is.matrix( beta ) ) { for( j in 1 : p ) Y_data[ ,j ] = BDgraph::qdweibull( pnorm_Z[ , j ], q = q[ , j ], beta = beta[ , j ], zero = TRUE ) } if( is.vector( q ) && is.vector( beta ) ) { for( j in 1 : p ) Y_data[ , j ] = BDgraph::qdweibull( pnorm_Z[ , j ], q = q[ j ], beta = beta[ j ], zero = TRUE ) } if( any( apply( Y_data, 2, function( x ) { all( x %in% 0 : 1 ) } ) ) ) cat( " Some of the variables are binary \n" ) } d = Y_data } if( ( type == "nbinom" ) | ( type == "NB" ) ) { not.cont[ 1:p ] = 1 Y.star <- matrix( c( 0, 1 ), nrow = n, ncol = p ) # To detect binary variables while ( any( apply( Y.star, 2, function( x ) { all( x %in% 0:1 ) } ) ) == TRUE ) { d = tmvtnorm::rtmvnorm( n = n, mean = rep( mean, p ), sigma = sigma, lower = rep( -5, length = p ), upper = rep( 5, length = p ) ) #mu <- stats::runif( n = p, min = 0.5, max = 5 ) #size <- stats::runif( n = p, min = 0.1, max = 3 ) mu = stats::runif( n = p, min = range.mu[ 1 ], max = range.mu[ 2 ] ) size = stats::runif( n = p, min = range.dispersion[ 1 ], max = range.dispersion[ 2 ] ) for(j in 1 : p ) Y.star[ , j ] = stats::qnbinom( stats::pnorm( d[ , j ] ), size = size[ j ], mu = mu[ j ], lower.tail = TRUE, log.p = FALSE ) # cat( "any binary variables ", any( apply( Y , 2, function( x ) { all( x %in% 0:1 ) }) ) , "\n" ) } d = Y.star } if( ( type == "pois" ) | ( type == "count" ) ) { not.cont[ 1:p ] = 1 Y.star = matrix( c( 0, 1 ), nrow = n, ncol = p ) while( any( apply( Y.star, 2, function( x ) { all( x %in% 0:1 ) } ) ) == TRUE ) ##detect binary variables { d = tmvtnorm::rtmvnorm( n = n, mean = rep( mean, p ), sigma = sigma, lower = rep( -5, length = p ), upper = rep( 5, length = p ) ) #lambda = stats::runif( n = p, min = 2, max = 3 ) #lambda = stats::runif( n = p, min = 2, max = 5 ) lambda = stats::runif( n = p, min = range.mu[ 1 ], max = range.mu[ 2 ] ) for(j in 1 : p ) Y.star[ , j ] = stats::qpois( stats::pnorm( d[ , j ] ), lambda = lambda[ j ], lower.tail = TRUE, log.p = FALSE ) } d = Y.star } } # - - Saving the result - - - - - - - - - - - - - - - - - - - - - - - - - -| if( n != 0 ) { if( type != "dw" ){ simulation <- list( G = G, graph = graph, data = d, sigma = sigma, K = K, type = type, not.cont = not.cont ) }else{ simulation <- list( G = G, graph = graph, data = d, sigma = sigma, K = K, type = type, not.cont = not.cont, beta = beta, q = q ) } }else{ simulation <- list( G = G, graph = graph ) } # - - graph visualization - - - - - - - - - - - - - - - - - - - - - - - - -| if( vis == TRUE ) BDgraph::plot.graph( G, main = "Graph structure" ) class( simulation ) <- "sim" return( simulation ) } ## - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - | # Print function for simulation data ## - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - | print.sim = function( x, ... ) { p = ncol( x $ G ) sum_G = sum( x $ G ) cat( paste( " graph generated by bdgraph.sim" ), fill = TRUE ) if( !is.null( x $ type ) ) { cat( paste( " Data type =", x $ type ), fill = TRUE ) cat( paste( " Sample size =", nrow( x $ data ) ), fill = TRUE ) } cat( paste( " Graph type =", x $ graph ), fill = TRUE ) cat( paste( " Number of nodes =", p ), fill = TRUE ) cat( paste( " Graph size =", sum_G / 2 ), fill = TRUE ) cat( paste( " Sparsity =", round( BDgraph::sparsity( x ), 4 ) ), fill = TRUE ) } ## - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - | # plot for class "sim" from bdgraph.sim function ## - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - | plot.sim = function( x, ... ) { BDgraph::plot.graph( x, ... ) } ## - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - | # Function for exact sampling from binary data ## - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - | sample_ug = function( n = 1, ug = diag( 3 ), clique_factors = NULL ) { p = ncol( ug ) # p smaller than 17 check if( p > 16 ) stop( "number of nodes must be smaller than 16" ) ug[ lower.tri( ug, diag = TRUE ) ] = 0 if( is.null( clique_factors ) ) clique_factors = generate_clique_factors( ug ) prob = calc_joint_dist( ug, clique_factors ) noc = length( prob ) ind = sample( 1:noc, n, replace = TRUE, prob = prob ) oc = sapply( 1:noc, function( x ){ as.integer( intToBits( x ) ) } ) oc = 2 - t( oc[ 1:p, ] ) data = oc[ ind, ] return( data ) } ## - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - | generate_clique_factors = function( ug ) { ug[ lower.tri( ug, diag = TRUE ) ] = 0 p = ncol( ug ) edges = which( ug == 1, arr.ind = T ) a = igraph::make_undirected_graph( c( t( edges ) ), p ) cliques = igraph::max_cliques( a ) clique_factors = vector( 'list', length( cliques ) ) for ( i in 1:length( cliques ) ) { clq = cliques[[i]] clique_factors[[i]] = stats::runif( 2 ^ length( clq ) ) } return( clique_factors ) } ## - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - | calc_joint_dist = function( ug, clique_factors ) { p = ncol( ug ) oc = sapply( 1:( 2 ^ p ), function( x ){ as.integer( intToBits( x ) ) } ) oc = 2 - t( oc[ 1:p, ] ) edges = which( ug == 1, arr.ind = T ) a = igraph::make_undirected_graph( c( t( edges ) ), p ) joint_dist = rep( 1, 2 ^ p ) cliques = igraph::max_cliques( a ) for ( i in 1:length( cliques ) ) { clq = cliques[[i]] k = length( clq ) temp = sapply( 1:( 2 ^ k ), function( x ){ as.integer( intToBits( x ) ) } ) clq_oc = 2 - t( temp[1:k, ] ) clq_factor = clique_factors[[i]] for ( j in 1:nrow( clq_oc ) ) { oc_col_clq = oc[ , clq ] if( is.null( dim( oc_col_clq ) ) ) oc_col_clq = matrix( oc_col_clq, nrow = length( oc_col_clq ), ncol = 1 ) ind = apply( oc_col_clq, 1, identical, clq_oc[ j, ] ) joint_dist[ind] = joint_dist[ ind ] * clq_factor[ j ] } } joint_dist = joint_dist / sum( joint_dist ) return( joint_dist ) } ## - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - |
/scratch/gouwar.j/cran-all/cranData/BDgraph/R/bdgraph.sim.R
## - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - | # Copyright (C) 2012 - 2022 Reza Mohammadi | # | # This file is part of BDgraph package. | # | # BDgraph is free software: you can redistribute it and/or modify it under | # the terms of the GNU General Public License as published by the Free | # Software Foundation; see <https://cran.r-project.org/web/licenses/GPL-3>.| # | # Maintainer: Reza Mohammadi <[email protected]> | ## - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - | # Bayesian parameter estimation for discrete Weibull regression ## - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - | bdw.reg = function( data, formula = NA, iter = 5000, burnin = NULL, dist.q = dnorm, dist.beta = dnorm, par.q = c( 0, 1 ), par.beta = c( 0, 1 ), par.pi = c( 1, 1 ), initial.q = NULL, initial.beta = NULL, initial.pi = NULL, ZI = FALSE, scale.proposal = NULL, adapt = TRUE, print = TRUE ) { if( is.null( burnin ) ) burnin = round( iter * 0.75 ) if( !is.vector( data ) ) { mf = stats::model.frame( formula, data = data ) y = stats::model.response( mf, "numeric" ) # x = as.matrix( mf ) # x[ , 1 ] = 1 x = stats::model.matrix(formula, data = data) }else{ y = data x = matrix( 1, ncol = 1, nrow = length( y ) ) } n = length( y ) ncol_x = ncol( x ) ind_y0 = ifelse( y == 0, 1, 0 ) #setting initial parameters if( is.null( initial.q ) ) { theta.q = rep( 0, times = ncol_x ) q = 1 - sum( y == 0 ) / n if( q == 1 ) q = 0.999 theta.q[ 1 ] = log( q / ( 1 - q ) ) }else{ theta.q = initial.q } if( is.null( initial.beta ) ) { theta.beta = rep( 0, times = ncol_x ) }else{ theta.beta = initial.beta } if( is.null( scale.proposal ) ) scale.proposal = 2.38 ^ 2 / ( 2 * ncol_x ) if( !ZI ){ pii = 1 z = rep( 1, n ) }else{ pii = ifelse( is.null( initial.pi ), sum( y != 0 ) / n + sum( y == 0 ) / ( n * 2 ), initial.pi ) # z = ifelse( y == 0, 0, 1 ) prob_z = ifelse( y != 0, 1, pii ) z = stats::rbinom( n = n, size = 1, prob = prob_z ) } fit = stats::optim( par = c( theta.q, theta.beta ), fn = BDgraph::log_post_cond_dw, x = x, y = y, z = z, dist.q = dist.q, par.q = par.q, dist.beta = dist.beta, par.beta = par.beta, control = list( "fnscale" = -1, maxit = 10000 ), hessian = TRUE ) #Initial values: initial posterior mode theta.q = fit $ par[ 1 : ncol_x ] theta.beta = fit $ par[ ( ncol_x + 1 ) : ( 2 * ncol_x ) ] para = c( theta.q, theta.beta ) if( ZI ) para = c( para, pii ) #Setting the covariance matrix of the proposal distribution for the regression coefficients fisher_info_inv = BDgraph::near_positive_definite( -fit $ hessian[ 1 : ( 2 * ncol_x ), 1 : ( 2 * ncol_x ) ] ) if( !isSymmetric( fisher_info_inv ) || isTRUE( class( try( solve( fisher_info_inv ), silent = TRUE ) ) == "try-error" ) ) { # sigma_proposal = diag( 0.5, length( para ) ) sigma_proposal = diag( 0.5, 2 * ncol_x ) }else{ fisher_info = solve( fisher_info_inv ) sigma_proposal = scale.proposal * fisher_info } sample = matrix( nrow = iter + 1, ncol = length( para ) ) sample[ 1, ] = para count_accept = 0 for( i_mcmc in 1:iter ) { if( ( print == TRUE ) && ( i_mcmc %% round( iter / 100 ) == 0 ) ) { info = paste( round( i_mcmc / iter * 100 ), '% done, Acceptance rate = ', round( count_accept / iter * 100, 2 ),'%' ) cat( '\r ', info, rep( ' ', 20 ) ) } theta.q = sample[ i_mcmc, 1 : ncol_x ] theta.beta = sample[ i_mcmc, ( ncol_x + 1 ) : ( 2 * ncol_x ) ] if( ZI ) { pii = sample[ i_mcmc, ncol( sample ) ] dens = BDgraph::ddweibull_reg( x, y, theta.q, theta.beta ) prob_z0 = ind_y0 * ( 1 - pii ) prob_z1 = dens * pii prob_z = prob_z1 / ( prob_z1 + prob_z0 ) prob_z[ is.na( prob_z ) ] = 1 #Gibbs sampling for z: sample from posterior distribution given current values of theta.q and theta.beta z = stats::rbinom( n = n, size = 1, prob = prob_z ) #Gibbs sampling pi: sample from z n_z0 = sum( z == 0 ) n_z1 = sum( z == 1 ) ### Sample new pi from posterior distribution pii = stats::rbeta( n = 1, shape1 = par.pi[ 1 ] + n_z1, shape2 = par.pi[ 2 ] + n_z0 ) } #Random Metropolis-Hasting for theta.q and theta.beta (given Z and pi) #Log-posterior at current parameters log_posterior_t = BDgraph::log_post_cond_dw( par = c( theta.q, theta.beta ), par.q = par.q, par.beta = par.beta, dist.q = dist.q, dist.beta = dist.beta, x = x, y = y, z = z ) #Adaptive MH if( adapt ) if( i_mcmc >= 100 && i_mcmc %% 100 == 0 ) sigma_proposal = BDgraph::near_positive_definite( stats::cov( sample[ ( i_mcmc - 99 ) : i_mcmc, 1 : ( 2 * ncol_x ) ] ) ) if( !isSymmetric( sigma_proposal ) || isTRUE( class( try( chol.default( sigma_proposal ), silent = TRUE ) ) == "try-error" ) ) sigma_proposal = diag( 0.5, ncol( fisher_info ) ) b1 = BDgraph::rmvnorm( n = 1, mean = rep( 0, 2 * ncol_x ), sigma = sigma_proposal ) #New proposed values of theta.q and theta.beta value_proposal = sample[ i_mcmc, 1 : ( 2 * ncol_x ) ] + as.vector( b1 ) #Log-posterior at proposed parameters (given the same Z and pi) log_posterior_proposal = BDgraph::log_post_cond_dw( par = value_proposal, par.q = par.q, par.beta = par.beta, dist.q = dist.q, dist.beta = dist.beta, x = x, y = y, z = z ) log_alpha = min( 0, log_posterior_proposal - log_posterior_t ) if( log( stats::runif( 1 ) ) <= log_alpha ) { sample[ i_mcmc + 1, 1 : ( 2 * ncol_x ) ] = value_proposal count_accept = count_accept + 1 }else sample[ i_mcmc + 1, 1 : ( 2 * ncol_x ) ] = sample[ i_mcmc, 1 : ( 2 * ncol_x ) ] if( ZI ) sample[ i_mcmc + 1, ncol( sample ) ] = pii } cat( "\n" ) sample = sample[ ( burnin + 1 ) : ( iter + 1 ), ] sample.mean = apply( sample, 2, mean ) theta.q = sample.mean[ 1 : ncol_x ] theta.beta = sample.mean[ ( ncol_x + 1 ) : ( 2 * ncol_x ) ] if( ZI ) pii = sample.mean[ 2 * ncol_x + 1 ] q_reg = 1 / ( 1 + exp( - x %*% theta.q ) ) beta_reg = exp( x %*% theta.beta ) if( ncol_x == 1 ) { q_reg = q_reg[ 1 ] beta_reg = beta_reg[ 1 ] } return( list( sample = sample, q.est = q_reg, beta.est = beta_reg, pi.est = pii, accept.rate = count_accept / iter ) ) } ## - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - | # Discrete Weibull density based on regression ## - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - | ddweibull_reg = function( x, y, theta.q, theta.beta ) { q_reg = 1 / ( 1 + exp( - x %*% theta.q ) ) beta_reg = exp( x %*% theta.beta ) density = q_reg ^ ( y ^ beta_reg ) - q_reg ^ ( ( y + 1 ) ^ beta_reg ) return( density ) } ## - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - | ## Posterior of q and beta given Y & Z: P( X, Y | Z ) P( Z ) P( q ) P( beta ) ## - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - | log_post_cond_dw = function( par, x, y, z, dist.q, par.q, dist.beta, par.beta ) { ncol_x = ncol( x ) theta.q = par[ 1 : ncol_x ] theta.beta = par[ ( ncol_x + 1 ) : ( 2 * ncol( x ) ) ] dens_dw_z1 = BDgraph::ddweibull_reg( x = as.matrix( x[ z == 1, ] ), y = y[ z == 1 ], theta.q = theta.q, theta.beta = theta.beta ) # log_lik = sum( log( dens_dw_z1[ dens_dw_z1 != 0 ] ) ) dens_dw_z1[ dens_dw_z1 == 0 ] = .Machine $ double.xmin log_lik = sum( log( dens_dw_z1 ) ) log_prior_q = sum( dist.q( theta.q, par.q[ 1 ], par.q[ 2 ], log = TRUE ) ) log_prior_b = sum( dist.beta( theta.beta, par.beta[ 1 ], par.beta[ 2 ], log = TRUE ) ) log_post = log_lik + log_prior_q + log_prior_b return( log_post ) } ## - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - | near_positive_definite = function( m ) { # Copyright 2003-05 Korbinian Strimmer # Rank, condition, and positive definiteness of a matrix; Method by Higham 1988 d = ncol( m ) eigen_m = eigen( m ) eigen_vectors = eigen_m $ vectors eigen_values = eigen_m $ values delta = 2 * d * max( abs( eigen_values ) ) * .Machine $ double.eps # factor two is just to make sure the resulting # matrix passes all numerical tests of positive definiteness tau = pmax( 0, delta - eigen_values ) dm = eigen_vectors %*% diag( tau, d ) %*% t( eigen_vectors ) return( m + dm ) } ## - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - |
/scratch/gouwar.j/cran-all/cranData/BDgraph/R/bdw.reg.R
## - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - | # Copyright (C) 2012 - 2021 Reza Mohammadi | # | # This file is part of BDgraph package. | # | # BDgraph is free software: you can redistribute it and/or modify it under | # the terms of the GNU General Public License as published by the Free | # Software Foundation; see <https://cran.r-project.org/web/licenses/GPL-3>.| # | # Maintainer: Reza Mohammadi <[email protected]> | ## - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - | # Computing the Bayes factor between two graph structures | ## - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - | bf = function( num, den, bdgraph.obj, log = TRUE ) { G_1 = BDgraph::get_graph( num ) G_2 = BDgraph::get_graph( den ) if( ( inherits( bdgraph.obj, "bdgraph" ) ) | ( inherits( bdgraph.obj, "ssgraph" ) ) ) { p_links = bdgraph.obj $ p_links if( is.null( p_links ) ) p_links = BDgraph::plinks( bdgraph.obj, round = 15 ) min_plinks = 1 - p_links p_links[ p_links == 0 ] = .Machine $ double.xmin min_plinks[ min_plinks == 0 ] = .Machine $ double.xmin g1_min_g2 = G_1 - G_2 upper_plinks = p_links[ upper.tri( p_links ) ] upper_min_plinks = min_plinks[ upper.tri( min_plinks ) ] upper_g1_min_g2 = g1_min_g2[ upper.tri( g1_min_g2 ) ] log_vec_bf = 0 * upper_plinks log_vec_bf[ upper_g1_min_g2 == 1 ] = upper_plinks[ upper_g1_min_g2 == 1 ] / upper_min_plinks[ upper_g1_min_g2 == 1 ] log_vec_bf[ upper_g1_min_g2 == -1 ] = upper_min_plinks[ upper_g1_min_g2 == -1 ] / upper_plinks[ upper_g1_min_g2 == -1 ] log_vec_bf = log_vec_bf[ log_vec_bf != 0 ] if( log == TRUE ) { bf = sum( log( log_vec_bf ) ) }else{ bf = prod( log_vec_bf ) } } return( bf ) } ## - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - |
/scratch/gouwar.j/cran-all/cranData/BDgraph/R/bf.R
## - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - | # Copyright (C) 2012 - 2021 Reza Mohammadi | # | # This file is part of BDgraph package. | # | # BDgraph is free software: you can redistribute it and/or modify it under | # the terms of the GNU General Public License as published by the Free | # Software Foundation; see <https://cran.r-project.org/web/licenses/GPL-3>.| # | # Maintainer: Reza Mohammadi <[email protected]> | ## - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - | # Reports the measures to assess the performance of estimated graphs | ## - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - | compare = function( pred, actual, main = NULL, vis = FALSE ) { if( !inherits( pred, "list" ) ) pred = list( pred ) length_pred = length( pred ) G = BDgraph::get_graph( actual ) p = ncol( G ) result = matrix( 1, 8, length_pred + 1 ) result[ 1 , 1 ] = sum( G[ upper.tri( G ) == 1 ] ) result[ 2 , 1 ] = p * ( p - 1 ) / 2 - result[ 1, 1 ] result[ c( 3, 4 ), 1 ] = 0 for( i in 1:length_pred ) { est_g = BDgraph::get_graph( pred[[i]] ) result[ , i + 1 ] = compute_measures( est_G = est_g, G = G ) } result[ is.na( result ) ] = 0 rownames( result ) <- c( "True Positive", "True Negative", "False Positive", "False Negative", "F1-score", "Specificity", "Sensitivity", "MCC" ) if( is.null( main ) ) { main = c( "Actual" ) for( i in 1:length_pred ) main = c( main, paste0( "pred ", i ) ) } colnames( result ) = main if( vis == TRUE ) { if( length_pred == 1 ) mfrow = c( 1, 2 ) if( ( length_pred > 1 ) & ( length_pred < 4 ) ) mfrow = c( 2, 2 ) if( ( length_pred > 3 ) & ( length_pred < 6 ) ) mfrow = c( 3, 2 ) if( ( length_pred > 5 ) & ( length_pred < 9 ) ) mfrow = c( 3, 3 ) if( ( length_pred > 8 ) & ( length_pred < 12 ) ) mfrow = c( 4, 3 ) if( ( length_pred > 11 ) & ( length_pred < 16 ) ) mfrow = c( 4, 4 ) op = graphics::par( mfrow = mfrow, pty = "s", omi = c( 0.3, 0.3, 0.3, 0.3 ), mai = c( 0.3, 0.3, 0.3, 0.3 ) ) BDgraph::plot.graph( G , main = main[ 1 ] ) for( i in 1:length_pred ) BDgraph::plot.graph( pred[[i]], main = main[ i + 1 ] ) graphics::par( op ) } return( round( result, 3 ) ) } ## - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - | # To compare measures the performance of estimated graphs based on true graph ## - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - | compute_measures = function( est_G, G ) { if( sum( dim( G ) == dim( est_G ) ) != 2 ) stop( "'pred' and 'actual' have non-conforming size" ) upper_G = G[ upper.tri( G ) ] upper_est_G = est_G[ upper.tri( est_G ) ] tp = sum( ( upper_G == 1 ) * ( upper_est_G == 1 ) ) # True Positive tn = sum( ( upper_G == 0 ) * ( upper_est_G == 0 ) ) # True Negative fp = sum( ( upper_G == 0 ) * ( upper_est_G == 1 ) ) # False Positive fn = sum( ( upper_G == 1 ) * ( upper_est_G == 0 ) ) # False Negative # harmonic mean of precision and recall, called F-measure or balanced F-score F1score = ( 2 * tp ) / ( 2 * tp + fp + fn ) specificity = tn / ( tn + fp ) sensitivity = tp / ( tp + fn ) # Matthews Correlation Coefficients (MCC) mcc = ( ( tp * tn ) - ( fp * fn ) ) / ( sqrt( ( tp + fp ) * ( tp + fn ) ) * sqrt( ( tn + fp ) * ( tn + fn ) ) ) return( c( tp, tn, fp, fn, F1score, specificity, sensitivity, mcc ) ) } ## - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - |
/scratch/gouwar.j/cran-all/cranData/BDgraph/R/compare.R
## - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - | # Copyright (C) 2012 - 2021 Reza Mohammadi | # | # This file is part of 'BDgraph' package. | # | # BDgraph is free software: you can redistribute it and/or modify it under | # the terms of the GNU General Public License as published by the Free | # Software Foundation; see <https://cran.r-project.org/web/licenses/GPL-3>.| # | # Maintainer: Reza Mohammadi <[email protected]> | ## - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - | # Create a Confusion Matrix ## - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - | conf.mat = function( pred, actual, cutoff = 0.5, proportion = FALSE, dnn = c( "Prediction", "Actual" ), ... ) { if( is.matrix( actual ) ) if( ( sum( actual == 0 ) + sum( actual == 1 ) ) != ( nrow( actual ) ^ 2 ) ) stop( "Elements of matrix 'actual' must be 0 or 1" ) if( inherits( actual, "sim" ) ) actual = actual $ G if( is.matrix( pred ) ) if( any( pred < 0 ) || any( pred > 1 ) ) stop( "Elements of matrix 'pred' must be between ( 0, 1 )" ) if( ( inherits( pred, "bdgraph" ) ) | ( inherits( pred, "ssgraph" ) ) ) { pred = pred $ p_links if( is.null( pred ) ) pred = BDgraph::plinks( pred, round = 15 ) } pred = pred[ upper.tri( pred ) ] actual = actual[ upper.tri( actual ) ] if( length( pred ) != length( actual ) ) stop( "'prod' and 'actual' lengths differ" ) if( ( cutoff < 0 ) || ( cutoff > 1 ) ) stop( "'cutoff' must be between 0 and 1" ) pred = ifelse( pred >= cutoff, 1, 0 ) conf_mat = table( pred, actual, dnn = dnn, ... ) if( proportion == TRUE ) conf_mat = round( conf_mat / sum( conf_mat ), 3 ) return( conf_mat ) } ## - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - |
/scratch/gouwar.j/cran-all/cranData/BDgraph/R/conf.mat.R
## - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - | # Copyright (C) 2012 - 2021 Reza Mohammadi | # | # This file is part of 'BDgraph' package. | # | # BDgraph is free software: you can redistribute it and/or modify it under | # the terms of the GNU General Public License as published by the Free | # Software Foundation; see <https://cran.r-project.org/web/licenses/GPL-3>.| # | # Maintainer: Reza Mohammadi <[email protected]> | ## - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - | # Plot a Confusion Matrix ## - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - | conf.mat.plot = function( pred, actual, cutoff = 0.5, conf.level = 0, margin = 1, color = c( "#ff83a8", "#83ff9b" ), ... ) { conf_mat = BDgraph::conf.mat( pred = pred, actual = actual, cutoff = cutoff ) graphics::fourfoldplot( conf_mat, conf.level = conf.level, margin = margin, color = color, ... ) } ## - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - |
/scratch/gouwar.j/cran-all/cranData/BDgraph/R/conf.mat.plot.R
## - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - | # Copyright (C) 2012 - 2021 Reza Mohammadi | # | # This file is part of BDgraph package. | # | # BDgraph is free software: you can redistribute it and/or modify it under | # the terms of the GNU General Public License as published by the Free | # Software Foundation; see <https://cran.r-project.org/web/licenses/GPL-3>.| # | # Maintainer: Reza Mohammadi <[email protected]> | ## - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - | # Computing estimated covariance matrix | ## - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - | covariance = function( bdgraph.obj, round = 2 ) { if( ( !inherits( bdgraph.obj, "bdgraph" ) ) && ( !inherits( bdgraph.obj, "ssgraph" ) ) ) stop( "Input 'bdgraph.obj' must be an object from functions 'bdgraph()', 'bdgraph.mpl()', or 'ssgraph()'" ) K_hat = bdgraph.obj $ K_hat if( is.null( K_hat ) ) stop( "Input 'bdgraph.obj' must be an object from functions 'bdgraph()' or 'ssgraph()'" ) cov = solve( K_hat ) return( round( cov, round ) ) } ## - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - |
/scratch/gouwar.j/cran-all/cranData/BDgraph/R/covariance.R
## - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - | # Copyright (C) 2012 - 2021 Reza Mohammadi | # | # This file is part of BDgraph package. | # | # BDgraph is free software: you can redistribute it and/or modify it under | # the terms of the GNU General Public License as published by the Free | # Software Foundation; see <https://cran.r-project.org/web/licenses/GPL-3>.| # | # Maintainer: Reza Mohammadi <[email protected]> | ## - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - | # The Discrete Weibull Distribution ( Type 1 ) | ## - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - | ddweibull = function( x, q = exp( -1 ), beta = 1, zero = TRUE ) { if( any( x != floor( x ) ) ) stop( "'x' must be an integer" ) if( max( q ) > 1 | min( q ) < 0 ) stop( "'q' must be between 0 and 1" ) if( min( beta ) <= 0 ) stop( "'beta' must be a positive value" ) if( zero == FALSE ) x = x - 1 return( q ^ x ^ beta - q ^ ( x + 1 ) ^ beta ) } ## - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - | pdweibull = function( x, q = exp( -1 ), beta = 1, zero = TRUE ) { if( max( q ) > 1 | min( q ) < 0 ) stop( "'q' must be between 0 and 1" ) if( min( beta ) <= 0 ) stop( "'beta' must be a positive value" ) if( zero == FALSE ) x = x - 1 p_dw = 1 - q ^ ( x + 1 ) ^ beta p_dw[ x < 0 ] = 0 return( p_dw ) } ## - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - | qdweibull = function( p, q = exp( -1 ), beta = 1, zero = TRUE ) { if( max( q ) > 1 | min( q ) < 0 ) stop( "'q' must be between 0 and 1" ) if( min( beta ) <= 0 ) stop( "'beta' must be a positive value" ) if( zero ) return( ceiling( ( log( 1 - p ) / log( q ) ) ^ ( 1 / beta ) - 1 ) ) else return( ceiling( ( log( 1 - p ) / log( q ) ) ^ ( 1 / beta ) ) ) } ## - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - | rdweibull = function( n, q = exp( -1 ), beta = 1, zero = TRUE ) { if( max( q ) > 1 | min( q ) < 0 ) stop( "'q' must be between 0 and 1" ) if( min( beta ) <= 0 ) stop( "'beta' must be a positive value" ) r_unif = stats::runif( n ) if( zero ) return( ceiling( ( log( 1 - r_unif ) / log( q ) ) ^ ( 1 / beta ) ) - 1 ) else return( ceiling( ( log( 1 - r_unif ) / log( q ) ) ^ ( 1 / beta ) ) ) } ## - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - |
/scratch/gouwar.j/cran-all/cranData/BDgraph/R/ddweibull.R
## - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - | # Copyright (C) 2012 - 2022 Reza Mohammadi | # | # This file is part of BDgraph package. | # | # BDgraph is free software: you can redistribute it and/or modify it under | # the terms of the GNU General Public License as published by the Free | # Software Foundation; see <https://cran.r-project.org/web/licenses/GPL-3>.| # | # Maintainer: Reza Mohammadi <[email protected]> | ## - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - | get_cores = function( cores = NULL, verbose = TRUE ) { verbose_core = as.numeric( verbose ) num_machine_cores = BDgraph::detect_cores() if( is.null( cores ) ) cores = num_machine_cores - 1 if( cores == "all" ) cores = num_machine_cores if( cores > num_machine_cores ) cores = num_machine_cores .C( "omp_set_num_cores", as.integer( cores ), as.integer( verbose_core ), PACKAGE = "BDgraph" ) return( cores ) } ## - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - | detect_cores = function( all.tests = FALSE, logical = TRUE ) { if( .Platform $ OS.type == "windows" ) { if( logical ) { res <- Sys.getenv( "NUMBER_OF_PROCESSORS", "1" ) as.numeric( res ) }else{ x = system( "WMIC CPU Get DeviceID,NumberOfCores", intern = TRUE ) sum( utils::read.table( text = x, header = TRUE ) $ NumberOfCores ) } }else{ systems = list( linux = if( logical ) "grep processor /proc/cpuinfo 2>/dev/null | wc -l" else "cat /proc/cpuinfo | grep 'cpu cores'| uniq | cut -f2 -d:", darwin = if( logical ) "/usr/sbin/sysctl -n hw.logicalcpu 2>/dev/null" else "/usr/sbin/sysctl -n hw.physicalcpu 2>/dev/null", solaris = if( logical ) "/usr/sbin/psrinfo -v | grep 'Status of.*processor' | wc -l" else "/bin/kstat -p -m cpu_info | grep :core_id | cut -f2 | uniq | wc -l", freebsd = "/sbin/sysctl -n hw.ncpu 2>/dev/null", openbsd = "/sbin/sysctl -n hw.ncpu 2>/dev/null", irix = c( "hinv | grep Processors | sed 's: .*::'", "hinv | grep '^Processor '| wc -l" ) ) for( i in seq( systems ) ) { if( all.tests || length( grep( paste0( "^", names( systems )[i] ), R.version $ os ) ) ) for( cmd in systems[i] ) { a = try( suppressWarnings( system( cmd, TRUE ) ), silent = TRUE ) if( inherits( a, "try-error" ) ) next a <- gsub( "^ +", "", a[1] ) if( length( grep( "^[1-9]", a ) ) ) return( as.integer( a ) ) } } NA_integer_ } } ## - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - |
/scratch/gouwar.j/cran-all/cranData/BDgraph/R/get_cores.R
## - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - | # Copyright (C) 2012 - 2021 Reza Mohammadi | # | # This file is part of BDgraph package. | # | # BDgraph is free software: you can redistribute it and/or modify it under | # the terms of the GNU General Public License as published by the Free | # Software Foundation; see <https://cran.r-project.org/web/licenses/GPL-3>.| # | # Maintainer: Reza Mohammadi <[email protected]> | ## - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - | ## - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - | # Get graph from class objects "sim", "graph", "bdgraph", "ssgraph", or "select" ## - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - | get_graph = function( obj_G, cut = 0.5 ) { if( is.matrix( obj_G ) ) { if( nrow( obj_G ) != ncol( obj_G ) ) stop( "Adjacency matrix must be squere" ) if( ( sum( obj_G == 0 ) + sum( obj_G == 1 ) ) != ( ncol( obj_G ) ^ 2 ) ) stop( "Elements of adjacency matrix must be 0 or 1" ) G = unclass( obj_G ) }else{ if( inherits( obj_G, "sim" ) ) G <- unclass( obj_G $ G ) if( inherits( obj_G, "graph" ) ) G <- unclass( obj_G ) if( ( inherits( obj_G, "bdgraph" ) ) | ( inherits( obj_G, "ssgraph" ) ) ) G <- BDgraph::select( obj_G, cut = cut ) if( inherits( obj_G, "select" ) ) G <- obj_G $ refit G = as.matrix( G ) } return( G ) } ## - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - | get_g_prior = function( g.prior, p ) { if( is.data.frame( g.prior ) ) g.prior <- data.matrix( g.prior ) if( inherits( g.prior, "dtCMatrix" ) ) g.prior = as.matrix( g.prior ) if( ( inherits( g.prior, "bdgraph" ) ) | ( inherits( g.prior, "ssgraph" ) ) ) g.prior <- BDgraph::plinks( g.prior ) if( inherits( g.prior, "sim" ) ) { K = as.matrix( g.prior $ K ) g.prior = abs( K / diag( K ) ) } if( !is.matrix( g.prior ) ) { if( ( g.prior <= 0 ) | ( g.prior >= 1 ) ) stop( "'g.prior' must be between 0 and 1" ) g.prior = matrix( g.prior, p, p ) }else{ if( ( nrow( g.prior ) != p ) | ( ncol( g.prior ) != p ) ) stop( "'g.prior' and 'data' have non-conforming size" ) if( any( g.prior < 0 ) || any( g.prior > 1 ) ) stop( "Elements of matrix 'g.prior' must be between 0 and 1" ) } g.prior[ lower.tri( g.prior, diag = TRUE ) ] <- 0 g.prior = g.prior + t( g.prior ) return( g.prior ) } ## - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - | get_g_start = function( g.start, g_prior, p ) { if( is.matrix( g.start ) ) { if( ( sum( g.start == 0 ) + sum( g.start == 1 ) ) != ( p ^ 2 ) ) stop( "Elements of matrix 'g.start' must be 0 or 1" ) G = g.start } if( inherits( g.start, "sim" ) ) G <- unclass( g.start $ G ) if( inherits( g.start, "graph" ) ) G <- unclass( g.start ) if( ( inherits( g.start, "bdgraph" ) ) | ( inherits( g.start, "ssgraph" ) ) ) G <- g.start $ last_graph if( ( inherits( g.start, "character" ) ) && ( g.start == "empty" ) ) G = matrix( 0, p, p ) if( ( inherits( g.start, "character" ) ) && ( g.start == "full" ) ) G = matrix( 1, p, p ) if( ( nrow( G ) != p ) | ( ncol( G ) != p ) ) stop( "'g.start' and 'data' have non-conforming size" ) G[ g_prior == 1 ] = 1 G[ g_prior == 0 ] = 0 G[ lower.tri( G, diag( TRUE ) ) ] <- 0 G = G + t( G ) return( G = G ) } ## - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - | get_K_start = function( G, g.start, Ts, b_star, threshold ) { p = ncol( G ) if( ( inherits( g.start, "bdgraph" ) ) | ( inherits( g.start, "ssgraph" ) ) ) K <- g.start $ last_K if( inherits( g.start, "sim" ) ) K <- g.start $ K if( ( !inherits( g.start, "bdgraph" ) ) && ( !inherits( g.start, "ssgraph" ) ) && ( !inherits( g.start, "sim" ) ) ) { K = G result = .C( "rgwish_c", as.integer(G), as.double(Ts), K = as.double(K), as.integer(b_star), as.integer(p), as.double(threshold), PACKAGE = "BDgraph" ) K = matrix( result $ K, p, p ) } return( K = K ) } ## - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - | get_S_n_p = function( data, method, n, not.cont = NULL ) { if( inherits( data, "sim" ) ) { not.cont <- data $ not.cont # Do not change the order of these links data <- data $ data } if( !is.matrix( data ) & !is.data.frame( data ) ) stop( "'data' must be a matrix or dataframe" ) if( is.data.frame( data ) ) data <- data.matrix( data ) if( any( is.na( data ) ) ) { if( method == "dw" ) stop( "'bdgraph.dw()' does not deal with missing values" ) if( method == "ggm" ) stop( "'ggm' method does not deal with missing values. You could choose option 'method = \"gcgm\"'" ) if( method == "tgm" ) stop( "'tgm' method does not deal with missing values. You could choose option 'method = \"gcgm\"'" ) gcgm_NA = 1 }else{ gcgm_NA = 0 } if( isSymmetric( data ) ) { if( method == "gcgm" ) stop( "'method = \"gcgm\"' requires all data" ) if( method == "dw" ) stop( "'method = \"dw\"' requires all data" ) if( method == "tgm" ) stop( "'method = \"tgm\"' requires all data" ) if( is.null( n ) ) stop( "Please specify the number of observations 'n'" ) } p <- ncol( data ) if( p < 3 ) stop( "Number of variables/nodes ('p') must be more than 2" ) if( is.null( n ) ) n <- nrow( data ) if( method == "ggm" ) { if( isSymmetric( data ) ) { cat( "Input is identified as the covariance matrix \n" ) S <- data }else{ S <- t( data ) %*% data } } if( method == "gcgm" ) { if( is.null( not.cont ) ) { not.cont = c( rep( 1, p ) ) for( j in 1:p ) if( length( unique( data[ , j ] ) ) > min( n / 2 ) ) not.cont[ j ] = 0 }else{ if( !is.vector( not.cont ) ) stop( "'not.cont' must be a vector with length of number of variables" ) if( length( not.cont ) != p ) stop( "'not.cont' must be a vector with length of number of variables" ) if( ( sum( not.cont == 0 ) + sum( not.cont == 1 ) ) != p ) stop( "Elements of vector 'not.cont' must be 0 or 1" ) } R <- 0 * data for( j in 1:p ) if( not.cont[ j ] ) R[ , j ] = match( data[ , j ], sort( unique( data[ , j ] ) ) ) R[ is.na( R ) ] = -1000 # dealing with missing values # copula for continuous non-Gaussian data if( ( gcgm_NA == 0 ) && ( min( apply( R, 2, max ) ) > ( n - 5 * n / 100 ) ) ) { # copula transfer data = stats::qnorm( apply( data, 2, rank ) / ( n + 1 ) ) data = t( ( t( data ) - apply( data, 2, mean ) ) / apply( data, 2, stats::sd ) ) method = "ggm" }else{ # for non-Gaussian data Z <- stats::qnorm( apply( data, 2, rank, ties.method = "random" ) / ( n + 1 ) ) Zfill <- matrix( stats::rnorm( n * p ), n, p ) # for missing values Z[ is.na( data ) ] <- Zfill[ is.na( data ) ] # for missing values Z <- t( ( t( Z ) - apply( Z, 2, mean ) ) / apply( Z, 2, stats::sd ) ) S <- t( Z ) %*% Z } } if( method == "dw" ) { if( is.null( not.cont ) ) { not.cont = c( rep( 1, p ) ) }else{ if( !is.vector( not.cont ) ) stop( "'not.cont' must be a vector with length of number of variables" ) if( length( not.cont ) != p ) stop( "'not.cont' must be a vector with length of number of variables" ) if( ( sum( not.cont == 0 ) + sum( not.cont == 1 ) ) != p ) stop( "Elements of vector 'not.cont' must be 0 or 1" ) } # for non-Gaussian data Z <- stats::qnorm( apply( data, 2, rank, ties.method = "random" ) / ( n + 1 ) ) Zfill <- matrix( stats::rnorm( n * p ), n, p ) # for missing values Z[ is.na( data ) ] <- Zfill[ is.na( data ) ] # for missing values Z <- t( ( t( Z ) - apply( Z, 2, mean ) ) / apply( Z, 2, stats::sd ) ) S <- t( Z ) %*% Z } if( method == "tgm" ) S <- t( data ) %*% data list_out = list( method = method, S = S, n = n, p = p, colnames_data = colnames( data ), data = data ) if( method == "gcgm" ) { list_out$not.cont = not.cont list_out$gcgm_NA = gcgm_NA list_out$Z = Z list_out$R = R } if( method == "dw" ) { list_out$not.cont = not.cont list_out$gcgm_NA = gcgm_NA list_out$Z = Z } return( list_out ) } ## - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - | ## - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - | get_Ds_tgm_R = function( data, tu, mu, D, n, p, in_C = TRUE ) { if( in_C == TRUE ) { S = matrix( 0, p, p ) Ds = matrix( 0, p, p ) # void get_Ds_tgm( double data[], double D[], double mu[], double tu[], double Ds[], double S[], int *n, int *p ) result = .C( "get_Ds_tgm", as.double(data), as.double(D), as.double (mu), as.double(tu), Ds = as.double(Ds), S = as.double(S), as.integer(n), as.integer(p), PACKAGE = "BDgraph" ) S = matrix( result $ S , p, p ) Ds = matrix( result $ Ds, p, p ) }else{ #X_new = matrix( nrow = n, ncol = p ) #for( i in 1:n ){ # sqrt_tu_i = sqrt( tu[ i ] ); # for( j in 1:p ) X_new[ i, j ] = sqrt_tu_i * ( data[ i, j ] - mu[ j ] ); #} #S = t( X_new ) %*% X_new S = matrix( 0, p, p ) for( i in 1:p ) for( j in 1:p ) for( k in 1:n ) S[ i, j ] = S[ i, j ] + tu[ k ] * ( data[ k, i ] - mu[ i ] ) * ( data[ k, j ] - mu[ j ] ); Ds = D + S } return( list( S = S, Ds = Ds ) ) } ## - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - | get_Ts_R = function( Ds, in_C = TRUE ) { if( in_C == TRUE ) { p = ncol( Ds ) Ts = matrix( 0, p, p ) inv_Ds = matrix( 0, p, p ) copy_Ds = matrix( 0, p, p ) # void get_Ts( double Ds[], double Ts[], double inv_Ds[], double copy_Ds[], int *p ) result = .C( "get_Ts", as.double(Ds), Ts = as.double(Ts), as.double(inv_Ds), as.double(copy_Ds), as.integer(p), PACKAGE = "BDgraph" ) Ts = matrix( result $ Ts, p, p ) }else{ invDs = solve( Ds ) Ts = chol( invDs ) } return( Ts ) } ## - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - | update_tu_R = function( tu, data, K, mu, nu, n, p, in_C = TRUE ) { if( in_C == TRUE ) { Ts = matrix( 0, p, p ) inv_Ds = matrix( 0, p, p ) copy_Ds = matrix( 0, p, p ) # void update_tu( double data[], double K[], double tu[], double mu[], double *nu, int *n, int *p ) result = .C( "update_tu", as.double(data), as.double(K), tu = as.double(tu), as.double(mu), as.double(nu), as.integer(n), as.integer(p), PACKAGE = "BDgraph" ) tu = c( result $ tu ) }else{ d_mu_i = numeric( p ) for( i in 1:n ) { for( j in 1:p ) d_mu_i[ j ] = data[ i, j ] - mu[ j ]; #d_mu_i_x_K = d_mu_i %*% K; #delta_y_i = sum( d_mu_i_x_K * d_mu_i ); delta_y_i = 0.0; for( k in 1:p ) for( l in 1:p ) delta_y_i = delta_y_i + d_mu_i[ l ] * K[ l, k ] * d_mu_i[ k ]; shape_tu_i = ( nu + p ) / 2.0; rate_tu_i = ( nu + delta_y_i ) / 2.0; tu[ i ] = stats::rgamma( 1, shape = shape_tu_i, scale = 1.0 / rate_tu_i ) } } return( tu ) } ## - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - | update_mu_R = function( data, mu, tu, n, p, in_C = TRUE ) { if( in_C == TRUE ) { # void update_mu( double data[], double mu[], double tu[], int *n, int *p ) result = .C( "update_mu", as.double(data), mu = as.double(mu), as.double(tu), as.integer(n), as.integer(p), PACKAGE = "BDgraph" ) mu = c( result $ mu ) }else{ mu = c( tu %*% data / sum( tu ) ) } return( mu ) } ## - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - |
/scratch/gouwar.j/cran-all/cranData/BDgraph/R/get_things.R
## - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - | # Copyright (C) 2012 - 2021 Reza Mohammadi | # | # This file is part of BDgraph package. | # | # BDgraph is free software: you can redistribute it and/or modify it under | # the terms of the GNU General Public License as published by the Free | # Software Foundation; see <https://cran.r-project.org/web/licenses/GPL-3>.| # | # Maintainer: Reza Mohammadi <[email protected]> | ## - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - | # To compute the normalizing constant of G-Wishart distribution based on | # Monte Carlo algorithm according to below paper | ## - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - | # Atay-Kayis & Massam (2005). A monte carlo method for computing the | # marginal likelihood in nondecomposable Gaussian graphical models, Biometrika| ## - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - | gnorm = function( adj, b = 3, D = diag( ncol( adj ) ), iter = 100 ) { if ( b < 3 ) stop( "'b' must be more than 2" ) if( is.null( adj ) ) stop( "'adj' must be determined" ) G <- unclass( adj ) G <- as.matrix( G ) p <- nrow( G ) if( p != ncol( G ) ) stop( "'adj' must be a square matrix" ) if( ( sum( G == 0 ) + sum( G == 1 ) ) != ( nrow( G ) ^ 2 ) ) stop( "Elements of matrix 'adj' must be 0 or 1" ) G[ lower.tri( G, diag = TRUE ) ] <- 0 Ti = chol( solve( D ) ) H = Ti / t( matrix( rep( diag( Ti ), p ), p, p ) ) check_H = identical( H, diag( p ) ) * 1 nu = rowSums( G ) size_graph = sum( G ) # For the case, G is a full graph if( size_graph == ( p * ( p - 1 ) / 2 ) ) { logIg = ( size_graph / 2 ) * log( pi ) + ( p * ( b + p - 1 ) / 2 ) * log( 2 ) + sum( lgamma( ( b + nu ) / 2 ) ) - ( ( b + p - 1 ) / 2 ) * log( det( D ) ) } # For the case, G is an empty graph if( size_graph == 0 ) logIg = ( p * b / 2 ) * log( 2 ) + p * lgamma( b / 2 ) - ( b / 2 ) * sum( log( diag( D ) ) ) if( ( size_graph != ( p * ( p - 1 ) / 2 ) ) & ( size_graph != 0 ) ) { # For the case G is NOT full graph # - - Monte Carlo glorithm which is implemented in C++ - - - - - - - -| f_T = c( rep( 0, iter ) ) result = .C( "log_exp_mc", as.integer( G ), as.integer( nu ), as.integer( b ), as.double( H ), as.integer( check_H ), as.integer( iter ), as.integer( p ), f_T = as.double( f_T ), PACKAGE = "BDgraph" ) f_T = c( result $ f_T ) log_Ef_T = log( mean( exp( - f_T / 2 ) ) ) # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -| c_dT = ( size_graph / 2 ) * log( pi ) + ( p * b / 2 + size_graph ) * log( 2 ) + sum( lgamma( ( b + nu ) / 2 ) ) + sum( ( b + nu + colSums( G ) ) * log( diag( Ti ) ) ) logIg = c_dT + log_Ef_T } return( logIg ) } ## - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - |
/scratch/gouwar.j/cran-all/cranData/BDgraph/R/gnorm.R
## - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - | # Copyright (C) 2012 - 2021 Reza Mohammadi | # | # This file is part of BDgraph package. | # | # BDgraph is free software: you can redistribute it and/or modify it under | # the terms of the GNU General Public License as published by the Free | # Software Foundation; see <https://cran.r-project.org/web/licenses/GPL-3>.| # | # Maintainer: Reza Mohammadi <[email protected]> | ## - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - | # Graph generator | ## - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - | graph.sim = function( p = 10, graph = "random", prob = 0.2, size = NULL, class = NULL, vis = FALSE, rewire = 0.05 ) { if( p < 2 ) stop( "'p' must be more than 1" ) if( ( prob < 0 ) || ( prob > 1 ) ) stop( "'prob' must be between ( 0, 1 )" ) if( ( rewire < 0 ) | ( rewire > 1 ) ) stop( "Value of 'rewire' must be between ( 0, 1 )" ) G <- matrix( 0, p, p ) # - - build the graph structure - - - - - - - - - - - - - - - - - - - - - | if( ( graph == "random" ) | ( graph == "Random" ) ) { if( is.null( size ) ) { G[ upper.tri( G ) ] <- stats::rbinom( p * ( p - 1 ) / 2, 1, prob ) }else{ if( ( size < 0 ) | ( size > p * ( p - 1 ) / 2 ) ) stop( "'size' must be between ( 0, p * ( p - 1 ) / 2 )" ) smp <- sample( 1 : ( p * ( p - 1 ) / 2 ), size, replace = FALSE ) G[ upper.tri( G ) ][ smp ] <- 1 } } if( ( graph == "scale-free" ) | ( graph == "Scale-free" ) ) { resultGraph = .C( "scale_free", G = as.integer( G ), as.integer( p ), PACKAGE = "BDgraph" ) G = matrix( resultGraph $ G, p, p ) #j = sample( 1:p, 1 ) #for( i in ( c( 1:p )[ -j ] ) ) { G[ i, j ] = 1; G[ j, i ] = 1 } } if( ( graph == "cluster" ) | ( graph == "Cluster" ) ) { # partition variables if( is.null( class ) ) { #class = NULL if( !is.null( size ) ) class = length( size ) if( length( prob ) > 1 ) class = length( prob ) if( is.null( class ) ) class = max( 2, ceiling( p / 20 ) ) #if( !is.null( size ) ) class <- length( size ) else class <- max( 2, ceiling( p / 20 ) ) } g.large <- p %% class g.small <- class - g.large n.small <- floor( p / class ) n.large <- n.small + 1 vp <- c( rep( n.small, g.small ), rep( n.large, g.large ) ) if( is.null( size ) ) { if( length( prob ) != class ) prob = rep( prob, class ) for( i in 1 : class ) { tmp <- if( i == 1 ) ( 1 : vp[ 1 ] ) else ( ( sum( vp[ 1 : ( i - 1 ) ] ) + 1 ) : sum( vp[ 1 : i ] ) ) gg <- matrix( 0, vp[ i ], vp[ i ] ) gg[ upper.tri( gg ) ] <- stats::rbinom( vp[ i ] * ( vp[ i ] - 1 ) / 2, 1, prob[ i ] ) G[ tmp, tmp ] <- gg } }else{ if( class != length( size ) ) stop( "Number of graph sizes is not match with number of clusters" ) if( ( sum( size ) < 0 ) | ( sum( size ) > p * ( p - 1 ) / 2 ) ) stop( "Total graph sizes must be between ( 0, p * ( p - 1 ) / 2 )" ) for( i in 1 : class ) { tmp <- if( i == 1 ) ( 1 : vp[ 1 ] ) else ( ( sum( vp[ 1 : ( i - 1 ) ] ) + 1 ) : sum( vp[ 1 : i ] ) ) gg <- matrix( 0, vp[ i ], vp[ i ] ) smp <- sample( 1 : ( vp[ i ] * ( vp[ i ] - 1 ) / 2 ), size[ i ], replace = FALSE ) gg[ upper.tri( gg ) ][ smp ] <- 1 G[ tmp, tmp ] <- gg } } } if( ( graph == "hub" ) | ( graph == "Hub" ) ) { if( is.null( size ) ) size = ceiling( p / 20 ) if( ( size < 0 ) | ( size > ( p - 1 ) ) ) stop( "'size' must be between ( 0, p - 1 ), for option 'graph = \"hub\"'" ) hub = sample( 1:p, size = size, replace = FALSE ) for( i in 1:size ) { G[ hub[ i ], ] <- 1 G[ , hub[ i ] ] <- 1 } } if( ( graph == "star" ) | ( graph == "Star" ) ) { hub = sample( 1:p, size = 1, replace = FALSE ) G[ hub, ] <- 1 G[ , hub ] <- 1 } if( ( graph == "circle" ) | ( graph == "Circle" ) ) { if( p < 3 ) stop( "'p' must be more than 2, for option 'graph = \"circle\"'" ) G <- stats::toeplitz( c( 0, 1, rep( 0, p - 2 ) ) ) G[ 1, p ] <- 1 } if( ( graph == "smallworld" ) | ( graph == "Smallworld" ) | ( graph == "small-world" ) | ( graph == "Small-world" ) ) { G_igraph = igraph::sample_smallworld( dim = 1, # One dimension size = p, # Number of variables nei = round( size / p ), # Neighborhood p = rewire ) G = as.matrix( igraph::as_adj( G_igraph ) ) # Rewiring probability } if( ( graph == "lattice" ) | ( graph == "grid" ) ) { if( is.null( size ) ) { length_row = round( sqrt( p ) ) length_col = round( sqrt( p ) ) }else{ if( length( size ) == 1 ) { length_row = size length_col = size }else{ length_row = size[ 1 ] length_col = size[ 2 ] } } for( row in 1:length_row ) { for( col in 1:length_col ) { if( ( row != length_row ) & ( col != length_col ) ) G[ col + ( row - 1 ) * length_col, c( col + ( row - 1 ) * length_col + 1, col + row * length_col ) ] = 1 if( ( row == length_row ) & ( col != length_col ) ) G[ col + ( row - 1 ) * length_col, col + ( row - 1 ) * length_col + 1 ] = 1 if( ( row != length_row ) & ( col == length_col ) ) G[ col + ( row - 1 ) * length_col, col + row * length_col ] = 1 } } } G[ lower.tri( G, diag = TRUE ) ] = 0 G = G + t( G ) # - - graph visualization - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -| if( vis == TRUE ) BDgraph::plot.graph( G, main = "Graph structure" ) class( G ) <- "graph" return( G ) } ## - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - | # plot for class "graph" from graph.sim function ## - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - | plot.graph = function( x, cut = 0.5, mode = "undirected", diag = FALSE, main = NULL, layout = igraph::layout_with_fr, vertex.size = 2, vertex.color = "orange", vertex.frame.color = "orange", vertex.label = NULL, vertex.label.dist = 0.5, vertex.label.color = "blue", edge.color = "lightblue", ... ) { graph = BDgraph::get_graph( x, cut = cut ) if( is.null( vertex.label ) ) vertex.label = colnames( graph ) graph_ig <- igraph::graph.adjacency( graph, mode = mode, diag = diag ) igraph::plot.igraph( graph_ig, main = main, layout = layout, vertex.size = vertex.size, vertex.color = vertex.color, vertex.frame.color = vertex.frame.color, vertex.label = vertex.label, vertex.label.dist = vertex.label.dist, vertex.label.color = vertex.label.color, edge.color = edge.color, ... ) } ## - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - |
/scratch/gouwar.j/cran-all/cranData/BDgraph/R/graph.sim.R
## - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - | # Copyright (C) 2012 - 2022 Reza Mohammadi | # | # This file is part of BDgraph package. | # | # BDgraph is free software: you can redistribute it and/or modify it under | # the terms of the GNU General Public License as published by the Free | # Software Foundation; see <https://cran.r-project.org/web/licenses/GPL-3>.| # | # Maintainer: Reza Mohammadi <[email protected]> | ## - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - | # A divide-and-conquer type greedy hill climb algorithm | # for undirected graphcial models and count data. | ## - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - | # The Hill-Climb algorithm (function "hill_climb_mpl") consists for two part: # PART 1: Local Marginal Pseudo-likelihood optimization to discovers the # Markov blanket of each node ( function "local_mb_hc" ). # PART 2: Neighborhood search algorithm for global Marginal Pseudo-likelihood # optimization ( function "global_hc" ). # See "Marginal pseudo-likelihood learning of Markov network structures" by # Pensar et al. for more details. ## - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - | # INPUT: * data ( n x p ) matrix, as a count dataset with n observations and p variables. # The outcome space of each variable must be in the form 0, 1, ..., r. # * alpha: The parameter of the prior distribution # OUTPUT: * selected_G - adjacency matrix for the selected graph ## - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - | hill_climb_mpl = function( data, freq_data, n, max_range_nodes, alpha = 0.5, operator = "or" ) { p = ncol( data ) G = matrix( 0, p, p ) for( i in 1:p ) { mes = paste( c( " PART 1: Local search for node ", i ), collapse = "" ) cat( mes, "\r" ) utils::flush.console() mb_i = local_mb_hc( node = i, data = data, freq_data = freq_data, max_range_nodes = max_range_nodes, p = p, n = n, alpha = alpha ) G[mb_i, i] = 1 } G_local = matrix( 0, p, p ) if( operator == "or" ) G_local[ ( G + t( G ) ) > 0 ] = 1 if( operator == "and" ) G_local = G * t( G ) if( sum( G_local ) != 0 ) { selected_G = global_hc( G_local = G_local, data = data, freq_data = freq_data, max_range_nodes = max_range_nodes, p = p, n = n, alpha = alpha ) }else{ selected_G = G_local } return( selected_G ) } ## - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - | # Local Marginal Pseudo-likelihood optimization to discovers the Markov # blanket of each node ## - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - | local_mb_hc = function( node, data, freq_data, max_range_nodes, p, n, alpha = 0.5 ) { temp = seq_len( p ) mb_potential = temp[ - node ] l_mb_potential = p - 1 mb_hat = numeric() log_prob_mb_hat = log_mpl_disrete( node, mb_hat, data, freq_data, max_range_nodes, p, n, alpha = alpha ) cont = TRUE while( cont == TRUE ) { cont = FALSE log_prob_mb_candidates = numeric( l_mb_potential ) for( i in seq_len( l_mb_potential ) ) log_prob_mb_candidates[i] = log_mpl_disrete( node = node, mb_node = c( mb_hat, mb_potential[i] ), data = data, freq_data = freq_data, max_range_nodes = max_range_nodes, p = p, n = p, alpha = alpha ) log_prob_mb_candidate_top = max( log_prob_mb_candidates ) if( log_prob_mb_candidate_top > log_prob_mb_hat ) { mb_cand_top_loc = which.max( log_prob_mb_candidates ) mb_hat = c( mb_hat, mb_potential[ mb_cand_top_loc ] ) mb_potential = mb_potential[ - mb_cand_top_loc ] l_mb_potential = l_mb_potential - 1 log_prob_mb_hat = log_prob_mb_candidate_top cont = TRUE } length_mb_hat = length( mb_hat ) if( ( length_mb_hat > 2 ) & ( cont == TRUE ) ) { delete = TRUE while( delete == TRUE ) { delete = FALSE log_prob_mb_candidates = numeric( length_mb_hat ) for( i in 1:length_mb_hat ) log_prob_mb_candidates[i] = log_mpl_disrete( node = node, mb_node = mb_hat[ -i ], data = data, freq_data = freq_data, max_range_nodes = max_range_nodes, p = p, n = n, alpha = alpha ) log_prob_mb_candidate_top = max( log_prob_mb_candidates ) if( log_prob_mb_candidate_top > log_prob_mb_hat ) { mb_cand_top_loc = which.max( log_prob_mb_candidates ) mb_hat = mb_hat[ - mb_cand_top_loc ] length_mb_hat = length( mb_hat ) log_prob_mb_hat = log_prob_mb_candidate_top if( length_mb_hat > 2 ) delete = TRUE } } } } return( mb_hat ) } ## - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - | # Neighborhood search algorithm for global Marginal Pseudo-likelihood optimization ## - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - | global_hc = function( G_local, data, freq_data, max_range_nodes, p, n, alpha = 0.5 ) { print( "PART 2, running global search algorithm" ) ug = matrix( 0, p, p ) n_edges = sum( G_local ) / 2 temp = which( G_local == 1, arr.ind = T ) edges = temp[temp[, 1] < temp[, 2], ] curr_scores = numeric( p ) for( i in 1:p ) curr_scores[ i ] = log_mpl_disrete( i, which( ug[i, ] == 1 ), data = data, freq_data = freq_data, max_range_nodes, p = p, n = n, alpha = alpha ) edge_change_imp = matrix( 0, n_edges, 2 ) edge_change = matrix( TRUE, n_edges, 2 ) cont = TRUE while( cont == TRUE ) { cont = FALSE edge_change_ind = which( edge_change[, 1 ] == TRUE ) for( i in 1:length( edge_change_ind ) ) { edge = edges[ edge_change_ind[ i ], ] node = edge[ 1 ] mb = which( ug[node, ] == 1 ) if( ug[ edge[ 1 ], edge[ 2 ] ] == 0 ) { swoe1 = curr_scores[ node ] mb = c( mb, edge[ 2 ] ) swe1 = log_mpl_disrete( node, mb, data = data, freq_data = freq_data, max_range_nodes, p = p, n = n, alpha = alpha ) edge_change_imp[ edge_change_ind[ i ], 1 ] = swe1 - swoe1; edge_change[ edge_change_ind[ i ], 1 ] = FALSE }else{ swe1 = curr_scores[ node ] mb = mb[ mb != edge[ 2 ] ] swoe1 = log_mpl_disrete( node, mb, data = data, freq_data = freq_data, max_range_nodes, p = p, n = n, alpha = alpha ) edge_change_imp[ edge_change_ind[ i ], 1 ] = swoe1 - swe1; edge_change[ edge_change_ind[ i ], 1 ] = FALSE } } edge_change_ind = which( edge_change[ , 2 ] == 1 ) for( i in 1:length( edge_change_ind ) ) { edge = edges[ edge_change_ind[ i ], ] node = edge[ 2 ] mb = which( ug[ node, ] == 1 ) if( ug[ edge[ 1 ], edge[ 2 ] ] == 0 ) { swoe2 = curr_scores[ node ] mb = c( mb, edge[ 1 ] ) swe2 = log_mpl_disrete( node, mb, data = data, freq_data = freq_data, max_range_nodes, p = p, n = n, alpha = alpha ) edge_change_imp[ edge_change_ind[ i ], 2 ] = swe2 - swoe2; edge_change[ edge_change_ind[ i ], 2 ] = FALSE }else{ swe2 = curr_scores[ node ] mb = mb[ mb != edge[ 1 ] ] swoe2 = log_mpl_disrete( node, mb, data = data, freq_data = freq_data, max_range_nodes, p = p, n = n, alpha = alpha ) edge_change_imp[ edge_change_ind[ i ], 2 ] = swoe2 - swe2; edge_change[ edge_change_ind[ i ], 2 ] = FALSE } } imp = apply( edge_change_imp, 1, sum ) max_imp = max( imp ) max_imp_loc = which.max( imp ) if( max_imp > 0 ) { edge = edges[max_imp_loc, ] if( ug[edge[1], edge[2]] == 0 ) { ug[edge[1], edge[2]] = 1 ug[edge[2], edge[1]] = 1 }else{ ug[edge[1], edge[2]] = 0 ug[edge[2], edge[1]] = 0 } curr_scores[edge[1]] = log_mpl_disrete( edge[1], which( ug[edge[1], ] == 1 ), data = data, freq_data = freq_data, max_range_nodes, p = p, n = n, alpha = alpha ) curr_scores[edge[2]] = log_mpl_disrete( edge[2], which( ug[edge[2], ] == 1 ), data = data, freq_data = freq_data, max_range_nodes, p = p, n = n, alpha = alpha ) edge_change[edges[, 1] == edge[1]|edges[, 1] == edge[2], 1] = TRUE edge_change[edges[, 2] == edge[1]|edges[, 2] == edge[2], 2] = TRUE cont = TRUE } } return( ug ) } ## - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - | # Computing the Marginal pseudo-likelihood for count data ## - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - | log_mpl_disrete = function( node, mb_node, data, freq_data, max_range_nodes, p, n, alpha = 0.5 ) { length_freq_data = length( freq_data ) size_node = length( mb_node ) node = node - 1 mb_node = mb_node - 1 log_mpl_node = 0.0 result = .C( "log_mpl_dis", as.integer(node), as.integer(mb_node), as.integer(size_node), log_mpl_node = as.double(log_mpl_node), as.integer(data), as.integer(freq_data), as.integer(length_freq_data), as.integer(max_range_nodes), as.double(alpha), as.integer(n), PACKAGE = "BDgraph" ) log_mpl_node = result $ log_mpl_node return( log_mpl_node ) } ## - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - |
/scratch/gouwar.j/cran-all/cranData/BDgraph/R/hill_climb_algorithm.R
## - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - | # Copyright (C) 2012 - 2022 Reza Mohammadi | # | # This file is part of BDgraph package. | # | # BDgraph is free software: you can redistribute it and/or modify it under | # the terms of the GNU General Public License as published by the Free | # Software Foundation; see <https://cran.r-project.org/web/licenses/GPL-3>.| # | # Maintainer: Reza Mohammadi <[email protected]> | ## - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - | # A divide-and-conquer type greedy hill climb algorithm # for undirected graphcial models with dicrete data ## - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - | # The Hill-Climb algorithm ( function "hill_climb_mpl" ) consists for two part: # PART 1: Local Marginal Pseudo-likelihood optimization to discovers the Markov # blanket of each node ( function "local_mb_hc" ). # PART 2: Neighborhood search algorithm for global Marginal Pseudo-likelihood # optimization ( function "global_hc" ). # See "Marginal pseudo-likelihood learning of Markov network structures" by # Pensar et al. for more details. ## - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - | # INPUT: * data (n x p) matrix, as a count dataset with n observations and p variables. # The outcome space of each variable must be in the form 0, 1, ..., r. # * alpha: The parameter of the prior distribution # OUTPUT: * selected_G - adjacency matrix for the selected graph ## - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - | hill_climb_mpl_binary = function( data, freq_data, n, alpha = 0.5, operator = "or" ) { p = ncol( data ) G = matrix( 0, p, p ) for( i in 1:p ) { mes = paste( c( " PART 1: Local search for node ", i ), collapse = "" ) cat( mes, "\r" ) utils::flush.console() mb_i = local_mb_hc_binary( node = i, data = data, freq_data = freq_data, p = p, n = n, alpha = alpha ) G[mb_i, i] = 1 } G_local = matrix( 0, p, p ) if( operator == "or" ) G_local[ ( G + t( G ) ) > 0 ] = 1 if( operator == "and" ) G_local = G * t( G ) if( sum( G_local ) != 0 ) { selected_G = global_hc_binary( G_local = G_local, data = data, freq_data = freq_data, p = p, n = n, alpha = alpha ) }else{ selected_G = G_local } return( selected_G ) } ## - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - | # Local Marginal Pseudo-likelihood optimization to discovers the Markov # blanket of each node ## - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - | local_mb_hc_binary = function( node, data, freq_data, p, n, alpha = 0.5 ) { temp = seq_len( p ) mb_potential = temp[ - node ] l_mb_potential = p - 1 mb_hat = numeric() log_prob_mb_hat = log_mpl_binary( node, mb_hat, data, freq_data, p, n, alpha = alpha ) cont = TRUE while( cont == TRUE ) { cont = FALSE log_prob_mb_candidates = numeric( l_mb_potential ) for( i in seq_len( l_mb_potential ) ) log_prob_mb_candidates[i] = log_mpl_binary( node = node, mb_node = c( mb_hat, mb_potential[i] ), data = data, freq_data = freq_data, p = p, n = p, alpha = alpha ) log_prob_mb_candidate_top = max( log_prob_mb_candidates ) if( log_prob_mb_candidate_top > log_prob_mb_hat ) { mb_cand_top_loc = which.max( log_prob_mb_candidates ) mb_hat = c( mb_hat, mb_potential[ mb_cand_top_loc ] ) mb_potential = mb_potential[ - mb_cand_top_loc ] l_mb_potential = l_mb_potential - 1 log_prob_mb_hat = log_prob_mb_candidate_top cont = TRUE } length_mb_hat = length( mb_hat ) if( ( length_mb_hat > 2 ) & ( cont == TRUE ) ) { delete = TRUE while( delete == TRUE ) { delete = FALSE log_prob_mb_candidates = numeric( length_mb_hat ) for( i in 1:length_mb_hat ) log_prob_mb_candidates[i] = log_mpl_binary( node = node, mb_node = mb_hat[ -i ], data = data, freq_data = freq_data, p = p, n = n, alpha = alpha ) log_prob_mb_candidate_top = max( log_prob_mb_candidates ) if( log_prob_mb_candidate_top > log_prob_mb_hat ) { mb_cand_top_loc = which.max( log_prob_mb_candidates ) mb_hat = mb_hat[ - mb_cand_top_loc ] length_mb_hat = length( mb_hat ) log_prob_mb_hat = log_prob_mb_candidate_top if( length_mb_hat > 2 ) delete = TRUE } } } } return( mb_hat ) } ## - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - | # Neighborhood search algorithm for global Marginal Pseudo-likelihood optimization ## - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - | global_hc_binary = function( G_local, data, freq_data, p, n, alpha = 0.5 ) { print( "PART 2, running global search algorithm" ) ug = matrix( 0, p, p ) n_edges = sum( G_local ) / 2 temp = which( G_local == 1, arr.ind = T ) edges = temp[temp[, 1] < temp[, 2], ] curr_scores = numeric( p ) for( i in 1:p ) curr_scores[i] = log_mpl_binary( node = i, which( ug[i, ] == 1 ), data = data, freq_data = freq_data, p = p, n = n, alpha = alpha ) edge_change_imp = matrix( 0, n_edges, 2 ) edge_change = matrix( TRUE, n_edges, 2 ) cont = TRUE while( cont == TRUE ) { cont = FALSE edge_change_ind = which( edge_change[, 1] == TRUE ) for( i in 1:length( edge_change_ind ) ) { edge = edges[edge_change_ind[i], ] node = edge[1] mb = which( ug[node, ] == 1 ) if( ug[ edge[1], edge[2] ] == 0 ) { swoe1 = curr_scores[node] mb = c( mb, edge[2] ) swe1 = log_mpl_binary( node = node, mb, data = data, freq_data = freq_data, p = p, n = n, alpha = alpha ) edge_change_imp[edge_change_ind[i], 1] = swe1 - swoe1; edge_change[edge_change_ind[i], 1] = FALSE }else{ swe1 = curr_scores[node] mb = mb[ mb != edge[2] ] swoe1 = log_mpl_binary( node = node, mb, data = data, freq_data = freq_data, p = p, n = n, alpha = alpha ) edge_change_imp[edge_change_ind[i], 1] = swoe1 - swe1; edge_change[edge_change_ind[i], 1] = FALSE } } edge_change_ind = which( edge_change[, 2] == 1 ) for( i in 1:length( edge_change_ind ) ) { edge = edges[edge_change_ind[i], ] node = edge[2] mb = which( ug[node, ] == 1 ) if( ug[edge[1], edge[2]] == 0 ) { swoe2 = curr_scores[node] mb = c( mb, edge[1] ) swe2 = log_mpl_binary( node = node, mb, data = data, freq_data = freq_data, p = p, n = n, alpha = alpha ) edge_change_imp[edge_change_ind[i], 2] = swe2 - swoe2; edge_change[edge_change_ind[i], 2] = FALSE }else{ swe2 = curr_scores[node] mb = mb[mb != edge[1]] swoe2 = log_mpl_binary( node = node, mb, data = data, freq_data = freq_data, p = p, n = n, alpha = alpha ) edge_change_imp[edge_change_ind[i], 2] = swoe2 - swe2; edge_change[edge_change_ind[i], 2] = FALSE } } imp = apply( edge_change_imp, 1, sum ) max_imp = max( imp ) max_imp_loc = which.max( imp ) if( max_imp > 0 ) { edge = edges[max_imp_loc, ] if( ug[edge[1], edge[2]] == 0 ) { ug[edge[1], edge[2]] = 1 ug[edge[2], edge[1]] = 1 }else{ ug[edge[1], edge[2]] = 0 ug[edge[2], edge[1]] = 0 } curr_scores[edge[1]] = log_mpl_binary( node = edge[1], which( ug[edge[1], ] == 1 ), data = data, freq_data = freq_data, p = p, n = n, alpha = alpha ) curr_scores[edge[2]] = log_mpl_binary( node = edge[2], which( ug[edge[2], ] == 1 ), data = data, freq_data = freq_data, p = p, n = n, alpha = alpha ) edge_change[edges[, 1] == edge[1]|edges[, 1] == edge[2], 1] = TRUE edge_change[edges[, 2] == edge[1]|edges[, 2] == edge[2], 2] = TRUE cont = TRUE } } return( ug ) } ## - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - | # Computing the Marginal pseudo-likelihood for count data ## - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - | log_mpl_binary = function( node, mb_node, data, freq_data, p, n, alpha = 0.5 ) { mb_node = as.vector( mb_node ) alpha_ijl = alpha length_freq_data = length( freq_data ) size_node = length( mb_node ) node = node - 1 mb_node = mb_node - 1 log_mpl_node = 0.0 result = .C( "log_mpl_binary_parallel_hc", as.integer(node), as.integer(mb_node), as.integer(size_node), log_mpl_node = as.double(log_mpl_node), as.integer(data), as.integer(freq_data), as.integer(length_freq_data), as.double(alpha_ijl), as.integer(n), PACKAGE = "BDgraph" ) log_mpl_node = result $ log_mpl_node return( log_mpl_node ) } ## - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - |
/scratch/gouwar.j/cran-all/cranData/BDgraph/R/hill_climb_binary.R
## - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - | # Copyright (C) 2012 - 2021 Reza Mohammadi | # | # This file is part of BDgraph package. | # | # BDgraph is free software: you can redistribute it and/or modify it under | # the terms of the GNU General Public License as published by the Free | # Software Foundation; see <https://cran.r-project.org/web/licenses/GPL-3>.| # | # Maintainer: Reza Mohammadi <[email protected]> | ## - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - | # Creating an adjacency matrix based on links | ## - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - | link2adj = function( link, p = NULL ) { if( !is.matrix( link ) & !is.data.frame( link ) ) stop( "Input 'link' must be a matrix or dataframe" ) if( is.data.frame( link ) ) link <- data.matrix( link ) if( ncol( link ) != 2 ) stop( "'link' must have only 2 columns" ) if( nrow( link ) < 1 ) stop( "'link' must have at least one row" ) if( !is.null( p ) ) if( max( link ) > p ) stop( "'p' is not matched with input 'link'" ) if( is.null( p ) ) p = max( link ) adj = matrix( 0, p, p ) for( i in 1:nrow( link ) ) adj[ link[ i, 1 ], link[ i, 2 ] ] = 1 return( adj ) } ## - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - |
/scratch/gouwar.j/cran-all/cranData/BDgraph/R/link2adj.R
## - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - | # Copyright (C) 2012 - 2021 Reza Mohammadi | # | # This file is part of BDgraph package. | # | # BDgraph is free software: you can redistribute it and/or modify it under | # the terms of the GNU General Public License as published by the Free | # Software Foundation; see <https://cran.r-project.org/web/licenses/GPL-3>.| # | # Maintainer: Reza Mohammadi <[email protected]> | ## - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - | # Computing the probability of all possible graphs or one specific graph | ## - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - | pgraph = function( bdgraph.obj, number.g = 4, adj = NULL ) { if( !is.null( bdgraph.obj $ p_links ) ) stop( "It needs object of 'bdgraph' with option 'save = TRUE'" ) sample_graphs = bdgraph.obj $ sample_graphs graph_weights = bdgraph.obj $ graph_weights sort_gWeights = sort( graph_weights, decreasing = TRUE ) if( is.null( adj ) ) { p <- nrow( bdgraph.obj $ last_graph ) list_g <- list() vec_g <- c( rep( 0, p * ( p - 1 ) / 2 ) ) for ( i in 1 : number.g ) { vec_g <- 0 * vec_g indG_i = sample_graphs[ which( graph_weights == sort_gWeights[ i ] ) ] vec_g[ which( unlist( strsplit( as.character( indG_i ), "" ) ) == 1 ) ] <- 1 list_g[[i]] <- matrix( 0, p, p ) list_g[[i]][ upper.tri( list_g[[i]] ) ] <- vec_g #list_g[[i]] <- Matrix::Matrix( list_g[[i]], sparse = TRUE ) } return( list( selected_g = list_g, prob_g = sort_gWeights[ 1 : number.g ] / sum( graph_weights ) ) ) }else{ if ( inherits( adj, "sim" ) ) G <- as.matrix( adj $ G ) if ( inherits( adj, "graph" ) ) G <- unclass( adj ) indG = paste( G[ upper.tri( G ) ], collapse = '' ) wh = which( sample_graphs == indG ) prob_g = ifelse( length( wh ) == 0, 0, graph_weights[ wh ] / sum( graph_weights ) ) return( prob_g ) } } ## - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - |
/scratch/gouwar.j/cran-all/cranData/BDgraph/R/pgraph.R
## - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - | # Copyright (C) 2012 - 2021 Reza Mohammadi | # | # This file is part of BDgraph package. | # | # BDgraph is free software: you can redistribute it and/or modify it under | # the terms of the GNU General Public License as published by the Free | # Software Foundation; see <https://cran.r-project.org/web/licenses/GPL-3>.| # | # Maintainer: Reza Mohammadi <[email protected]> | ## - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - | # Computing posterior probabilities of all possible links | ## - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - | plinks = function( bdgraph.obj, round = 2, burnin = NULL ) { if( ( !inherits( bdgraph.obj, "bdgraph" ) ) && ( !inherits( bdgraph.obj, "ssgraph" ) ) ) stop( "'bdgraph.obj' must be an object of functions 'bdgraph()', 'bdgraph.mpl()', 'bdgraph.dw()', or 'ssgraph()'" ) if( inherits( bdgraph.obj, "bdgraph" ) ) { if( is.null( bdgraph.obj $ sample_graphs ) ) { p_links = bdgraph.obj $ p_links }else{ p <- nrow( bdgraph.obj $ last_graph ) vec_G <- numeric( length = ( p * ( p - 1 ) / 2 ) ) sample_graphs <- bdgraph.obj $ sample_graphs graph_weights <- bdgraph.obj $ graph_weights if( is.null( burnin ) ) { for( i in 1 : length( sample_graphs ) ) { inp <- which( unlist( strsplit( as.character( sample_graphs[ i ] ), "" ) ) == 1 ) vec_G[ inp ] <- vec_G[ inp ] + graph_weights[ i ] } sum_graph_weights = sum( graph_weights ) }else{ all_graphs <- bdgraph.obj $ all_graphs all_weights <- bdgraph.obj $ all_weights sum_graph_weights <- 0 for( i in ( burnin + 1 ) : length( all_graphs ) ) { inp <- which( unlist( strsplit( as.character( sample_graphs[ all_graphs[ i ] ] ), "" ) ) == 1 ) vec_G[ inp ] <- vec_G[ inp ] + all_weights[ i ] sum_graph_weights <- sum_graph_weights + all_weights[ i ] } } label <- colnames( bdgraph.obj $ last_graph ) p_links <- matrix( 0, p, p, dimnames = list( label, label ) ) p_links[ upper.tri( p_links ) ] <- vec_G / sum_graph_weights } } if( inherits( bdgraph.obj, "ssgraph" ) ) p_links = bdgraph.obj $ p_links return( round( p_links, round ) ) } ## - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - |
/scratch/gouwar.j/cran-all/cranData/BDgraph/R/plinks.R
## - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - | # Copyright (C) 2012 - 2021 Reza Mohammadi | # | # This file is part of BDgraph package. | # | # BDgraph is free software: you can redistribute it and/or modify it under | # the terms of the GNU General Public License as published by the Free | # Software Foundation; see <https://cran.r-project.org/web/licenses/GPL-3>.| # | # Maintainer: Reza Mohammadi <[email protected]> | ## - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - | # To check the convergency of the BDMCMC algorithm | ## - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - | plotcoda = function( bdgraph.obj, thin = NULL, control = TRUE, main = NULL, verbose = TRUE, ... ) { if( ( inherits( bdgraph.obj, "bdgraph" ) ) | ( inherits( bdgraph.obj, "ssgraph" ) ) ) { if( is.null( bdgraph.obj $ all_graphs ) ) stop( "'bdgraph.obj' must be an object of function 'bdgraph()' or 'ssgraph()' with option 'save = TRUE'" ) if( is.null( bdgraph.obj $ all_graphs ) ) stop( "'bdgraph.obj' must be an object of function 'bdgraph()' or 'ssgraph()' with option 'save = TRUE'" ) }else{ stop( "'bdgraph.obj' must be an object of functions 'bdgraph()', 'bdgraph.mpl()', or 'ssgraph()'" ) } if( is.null( thin ) ) thin = ceiling( length( bdgraph.obj $ all_graphs ) / 1000 ) if( !is.numeric( thin ) ) stop( "'thin' must be a number" ) if( is.matrix( thin ) ) stop( "'thin' must be a number" ) sample_graphs = bdgraph.obj $ sample_graphs p = nrow( bdgraph.obj $ last_graph ) qp = p * ( p - 1 ) / 2 all_weights = bdgraph.obj $ all_weights all_graphs = bdgraph.obj $ all_graphs allG_new = all_graphs[ c( thin * ( 1 : floor( length( all_graphs ) / thin ) ) ) ] all_weights_new = all_weights[ c( thin * ( 1 : floor( length( all_weights ) / thin ) ) ) ] length_allG_new = length( allG_new ) result = matrix( 0, qp, length_allG_new ) vec_result = 0 * result[ , 1] for ( g in 1 : length_allG_new ) { if( verbose == TRUE ) { mes = paste( c( "Calculation ... in progress : ", floor( 100 * g / length_allG_new ), "%" ), collapse = "" ) cat( mes, "\r" ) utils::flush.console() } which_edge = which( unlist( strsplit( as.character( sample_graphs[ allG_new[ g ] ] ), "" ) ) == 1 ) vec_result[ which_edge ] = vec_result[ which_edge ] + all_weights_new[ g ] result[ ,g ] = vec_result / sum( all_weights_new[ c( 1 : g ) ] ) } if ( control ) if ( p > 15 ) { randomLinks = sample( x = 1:qp, size = ( qp - 100 ), replace = FALSE ) result[ randomLinks, ] = 0 } if( verbose == TRUE ) { mes = paste( c( "Calculation ... done. " ), collapse = "" ) cat( mes, "\r" ) cat( "\n" ) utils::flush.console() } graphics::matplot( x = thin * ( 1 : length_allG_new ), y = t( result ), type = "l", lty = 1, col = "blue", xlab = "Iteration", ylab = "Posterior link probability", cex.lab = 1.3, cex.axis = 1.2 ) if ( is.null( main ) ) main = "Trace of the Posterior Probabilities of the Links." graphics::title( main = main, cex.main = 1.2 ) } ## - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - |
/scratch/gouwar.j/cran-all/cranData/BDgraph/R/plotcoda.R
## - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - | # Copyright (C) 2012 - 2021 Reza Mohammadi | # | # This file is part of BDgraph package. | # | # BDgraph is free software: you can redistribute it and/or modify it under | # the terms of the GNU General Public License as published by the Free | # Software Foundation; see <https://cran.r-project.org/web/licenses/GPL-3>.| # | # Maintainer: Reza Mohammadi <[email protected]> | ## - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - | # To plot ROC curve | ## - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - | plotroc = function( pred, actual, cut = 200, smooth = FALSE, calibrate = TRUE, linetype = NULL, color = NULL, size = 1, main = "ROC Curve", xlab = "False Postive Rate", ylab = "True Postive Rate", legend = TRUE, legend.size = 17, legend.position = c( 0.7, 0.3 ), labels = NULL, auc = TRUE, theme = ggplot2::theme_minimal() ) { if( !inherits( pred, "list" ) ) pred = list( pred ) length_pred = length( pred ) if( is.null( color ) ) color = 1:length_pred if( is.null( linetype ) ) linetype = 1:length_pred if( !is.vector( actual ) ) { adj_G = BDgraph::get_graph( actual ) actual = adj_G[ upper.tri( adj_G ) ] } if( legend && is.null( labels ) ) { labels = numeric( length = length_pred ) for( i in 1:length_pred ) labels[ i ] = paste0( "pred ", i ) } fp_roc = vector() tp_roc = vector() length_fp_i = numeric( length = length_pred ) for( i in 1:length_pred ) { output_tp_fp = compute_tp_fp( pred = pred[[i]], actual = actual, cut = cut, smooth = smooth, calibrate = calibrate ) length_fp_i[ i ] = length( output_tp_fp $ fp ) fp_roc = c( fp_roc, sort( c( output_tp_fp $ fp ) ) ) tp_roc = c( tp_roc, sort( c( output_tp_fp $ tp ) ) ) } if( legend && auc ) { auc_s = BDgraph::auc( pred = pred, actual = actual, cut = cut, calibrate = calibrate ) labels = paste( labels, "; AUC=", round( auc_s, 3 ) ) } df_gg = data.frame( pred = rep( as.factor( 1:length_pred ), length_fp_i ), fp_roc = fp_roc, tp_roc = tp_roc ) ggplot2::ggplot( df_gg, ggplot2::aes( x = fp_roc, y = tp_roc ) ) + ggplot2::geom_line( ggplot2::aes( group = pred, colour = pred, linetype = pred ), show.legend = legend, size = size ) + ggplot2::scale_color_manual( values = color, labels = labels ) + ggplot2::scale_linetype_manual( values = linetype, labels = labels ) + ggplot2::labs( x = xlab, y = ylab ) + ggplot2::ggtitle( main ) + theme + ggplot2::theme( legend.title = ggplot2::element_blank(), legend.position = legend.position, text = ggplot2::element_text( size = legend.size ) ) + ggplot2::theme( legend.key.width = ggplot2::unit( 2, "line" ) ) } ## - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - | # Function to compute tp (true positive) and fp (false positive) for ROC plot ## - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - | compute_tp_fp = function( pred, actual, cut, smooth, calibrate = TRUE ) { if( !is.vector( actual ) ) { adj_G = BDgraph::get_graph( actual ) actual = adj_G[ upper.tri( adj_G ) ] } if( ( inherits( pred, "bdgraph" ) ) | ( inherits( pred, "ssgraph" ) ) ) pred = BDgraph::plinks( pred, round = 15 ) if( is.matrix( pred ) ) { if( any( round( pred ) < 0 ) || any( round( pred ) > 1 ) ) stop( "Elements of 'pred' must be between [ 0, 1 ]" ) pred = pred[ upper.tri( pred ) ] } sum_one = sum( actual ) sum_zero = length( actual ) - sum_one if( !inherits( pred, "huge" ) ) { tp = c( 1, rep( 0, cut ) ) fp = tp cut_points = ( 0 : cut ) / cut if( calibrate == FALSE ) w_roc = 1 for( i in 2 : cut ) { if( calibrate == TRUE ) w_roc = abs( pred - cut_points[ i ] ) tp[ i ] = sum( w_roc * ( actual == 1 ) * ( pred > cut_points[ i ] ) ) / sum_one fp[ i ] = sum( w_roc * ( actual == 0 ) * ( pred > cut_points[ i ] ) ) / sum_zero } } if( inherits( pred, "huge" ) ) { path = pred $ path tp = numeric( length( path ) ) fp = tp for( i in 1 : length( path ) ) { est_G = as.matrix( path[[ i ]] ) pred_i = est_G[ upper.tri( est_G ) ] tp[ i ] = sum( ( actual == 1 ) * ( pred_i == 1 ) ) / sum_one fp[ i ] = sum( ( actual == 0 ) * ( pred_i == 1 ) ) / sum_zero } tp = c( tp, 1 ) fp = c( fp, 1 ) } if ( smooth == TRUE ) { fit = stats::smooth.spline( x = fp, y = tp ) fp = c( 0, fit $ x ) tp = c( 0, fit $ y ) } return( list( tp = tp, fp = fp ) ) } ## - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - |
/scratch/gouwar.j/cran-all/cranData/BDgraph/R/plotroc.R
## - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - | # Copyright (C) 2012 - 2022 Reza Mohammadi | # | # This file is part of BDgraph package. | # | # BDgraph is free software: you can redistribute it and/or modify it under | # the terms of the GNU General Public License as published by the Free | # Software Foundation; see <https://cran.r-project.org/web/licenses/GPL-3>.| # | # Maintainer: Reza Mohammadi <[email protected]> | ## - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - | # posterior predict function for "bdgraph" object | ## - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - | posterior.predict = function( object, iter = 1, ... ) { if( is.null( object $ all_graphs ) ) stop( "'bdgraph.obj' must be an object of function 'bdgraph()' or 'ssgraph()' with option 'save = TRUE'" ) method = object $ method data = object $ data n_data = nrow( data ) p = ncol( data ) if( isSymmetric( data ) ) { S = data }else{ S = t( data ) %*% data } sample_graphs = object $ sample_graphs all_graphs = object $ all_graphs graph_weights = object $ graph_weights sample_G = sample( x = sample_graphs, size = iter, replace = TRUE, prob = graph_weights ) G_i = matrix( 0, nrow = p, ncol = p ) upper_G_i = G_i[ upper.tri( G_i ) ] Z = matrix( 0, nrow = iter, ncol = p ) for( i in 1:iter ) { upper_G_i = upper_G_i * 0 upper_G_i[ which( unlist( strsplit( as.character( sample_G[i] ), "" ) ) == 1 ) ] = 1 G_i[ upper.tri( G_i ) ] = upper_G_i K_i = BDgraph::rgwish( n = 1, adj = G_i, b = 3 + n_data, D = diag( p ) + S ) sigma_i = solve( K_i ) Z[ i, ] = BDgraph::rmvnorm( n = 1, mean = 0, sigma = sigma_i ) } if( method == "ggm" ) sample = Z if( method == "tgm" ) { mean = 0 nu = 1 tau_gamma = stats::rgamma( n = iter, shape = nu / 2, rate = nu / 2 ) sample = mean + Z / sqrt( tau_gamma ) } if( method == "gcgm" ) { K = object $ K_hat if( is.null( K ) ) { G = BDgraph::select( bdgraph.obj = object ) sample_K = BDgraph::rgwish( n = 500, adj = G, b = 3 + n_data, D = diag( p ) + S ) K = 0 * G for( i in 1:dim( sample_K )[3] ) K = K + sample_K[[i]] K = K / dim( sample_K )[3] } sample = 0 * Z for( j in 1:p ) { sdj = sqrt( 1 / K[ j, j ] ) # 2a: # variance of component j (given the rest!) muj = - sum( Z[ , -j, drop = FALSE ] %*% K[ -j, j, drop = FALSE ] / K[ j, j ] ) table_j = table( data[ , j ] ) cat_y_j = as.numeric( names( table_j ) ) len_cat_y_j = length( cat_y_j ) if( len_cat_y_j > 1 ) { cum_prop_yj = cumsum( table_j[ -len_cat_y_j ] ) / n_data #cut_j = vector( length = len_cat_y_j - 1 ) # for( k in 1:length( cut_j ) ) cut_j[ k ] = stats::qnorm( cum_prop_yj[ k ] ) cut_j = stats::qnorm( cum_prop_yj, mean = 0, sd = 1 ) breaks = c( min( Z[ , j ] ) - 1, cut_j, max( Z[ , j ] ) + 1 ) ind_sj = as.integer( cut( Z[ , j ], breaks = breaks, right = FALSE ) ) sample[ , j ] = cat_y_j[ ind_sj ] }else{ sample[ , j ] = cat_y_j } } } if( method == "dw" ) { q = object $ q.est beta = object $ beta.est mean = rep( 0, p ) #Z = tmvtnorm::rtmvnorm( n = iter, mean = mean, sigma = sigma, lower = rep( -5, length = p ), upper = rep( 5, length = p ) ) pnorm_Z = stats::pnorm( Z ) if( is.matrix( q ) && is.matrix( beta ) ) { for( j in 1 : p ) sample[ ,j ] = BDgraph::qdweibull( pnorm_Z[ , j ], q = q[ , j ], beta = beta[ , j ], zero = TRUE ) } if( is.vector( q ) && is.vector( beta ) ) { for( j in 1 : p ) sample[ , j ] = BDgraph::qdweibull( pnorm_Z[ , j ], q = q[ j ], beta = beta[ j ], zero = TRUE ) } } return( sample ) } ## - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - |
/scratch/gouwar.j/cran-all/cranData/BDgraph/R/posterior.predict.R
## - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - | # Copyright (C) 2012 - 2021 Reza Mohammadi | # | # This file is part of BDgraph package. | # | # BDgraph is free software: you can redistribute it and/or modify it under | # the terms of the GNU General Public License as published by the Free | # Software Foundation; see <https://cran.r-project.org/web/licenses/GPL-3>.| # | # Maintainer: Reza Mohammadi <[email protected]> | ## - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - | # Computing estimated precision matrix | ## - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - | precision = function( bdgraph.obj, round = 2 ) { if( ( !inherits( bdgraph.obj, "bdgraph" ) ) && ( !inherits( bdgraph.obj, "ssgraph" ) ) ) stop( "'bdgraph.obj' must be an object from functions 'bdgraph()', 'bdgraph.mpl()', or 'ssgraph()'" ) K_hat = bdgraph.obj $ K_hat if( is.null( K_hat ) ) stop( "Input 'object' must be from functions 'bdgraph()' or 'ssgraph()'" ) return( round( K_hat, round ) ) } ## - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - |
/scratch/gouwar.j/cran-all/cranData/BDgraph/R/precision.R
## - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - | # Copyright (C) 2012 - 2021 Reza Mohammadi | # | # This file is part of BDgraph package. | # | # BDgraph is free software: you can redistribute it and/or modify it under | # the terms of the GNU General Public License as published by the Free | # Software Foundation; see <https://cran.r-project.org/web/licenses/GPL-3>.| # | # Maintainer: Reza Mohammadi <[email protected]> | ## - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - | # Sampling from G-Wishart distribution | ## - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - | rgwish = function( n = 1, adj = NULL, b = 3, D = NULL, threshold = 1e-8 ) { if( b <= 2 ) stop( "'b' must be more than 2" ) if( is.null( adj ) ) stop( "'adj' must be determined" ) if( is.matrix( adj ) ) G <- unclass( adj ) # if( inherits( adj, "graph" ) ) G <- unclass( adj ) if( inherits( adj, "sim" ) ) G <- unclass( adj $ G ) if( inherits( adj, "bdgraph" ) ) G <- BDgraph::select( adj ) if( inherits( adj, "ssgraph" ) ) G <- BDgraph::select( adj ) if( ( sum( G == 0 ) + sum( G == 1 ) ) != ( nrow( G ) ^ 2 ) ) stop( "Elements of matrix 'adj' must be 0 or 1" ) G <- as.matrix( G ) diag( G ) <- 0 if( !isSymmetric( G ) ) { G[ lower.tri( G ) ] <- 0 G <- G + t( G ) } p <- nrow( G ) if( p < 1 ) stop( "'p' must be more than or equal with 1" ) if( is.null( D ) ) D <- diag( p ) if( !isSymmetric( D ) ) stop( "'D' must be a positive definite matrix" ) if( nrow( D ) != p ) stop( "'G' and 'D' dimentions differ" ) if( p == 1 ) return( rwish( n = n, p = p, b = b, D = D ) ) if( sum( G ) == ( p * ( p - 1 ) ) ) return( rwish( n = n, p = p, b = b, D = D ) ) Ti = chol( solve( D ) ) K = matrix( 0, p, p ) if( n > 1 ) { samples = array( 0, c( p, p, n ) ) for( i in 1 : n ) { result = .C( "rgwish_c", as.integer(G), as.double(Ti), K = as.double(K), as.integer(b), as.integer(p), as.double(threshold), PACKAGE = "BDgraph" ) samples[ , , i ] = matrix( result $ K, p, p ) } }else{ result = .C( "rgwish_c", as.integer(G), as.double(Ti), K = as.double(K), as.integer(b), as.integer(p), as.double(threshold), PACKAGE = "BDgraph" ) samples = matrix( result $ K, p, p ) } return( samples ) } ## - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - |
/scratch/gouwar.j/cran-all/cranData/BDgraph/R/rgwish.R
## - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - | # Copyright (C) 2012 - 2021 Reza Mohammadi | # | # This file is part of BDgraph package. | # | # BDgraph is free software: you can redistribute it and/or modify it under | # the terms of the GNU General Public License as published by the Free | # Software Foundation; see <https://cran.r-project.org/web/licenses/GPL-3>.| # | # Maintainer: Reza Mohammadi <[email protected]> | ## - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - | # Data generator from multivarate normal distribution | ## - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - | rmvnorm = function( n = 10, mean = rep( 0, length = ncol( sigma ) ), sigma = diag( length( mean ) ) ) { if( !isSymmetric( sigma, tol = sqrt( .Machine $ double.eps ), check.attributes = FALSE ) ) stop( "'sigma' must be a symmetric matrix" ) sigma = as.matrix( sigma ) p = nrow( sigma ) if( length( mean ) == 1 ) mean = rep( mean, p ) if( length( mean ) != nrow( sigma ) ) stop( "'mean' and 'sigma' have non-conforming size" ) # - - generate multivariate normal data - - - - - - - - - - - - - - - - - -| chol_sig = chol( sigma ) z = matrix( stats::rnorm( p * n ), p, n ) data = t( chol_sig ) %*% z + mean data = t( data ) if( n == 1 ) data = as.vector( data ) return( data ) } ## - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - |
/scratch/gouwar.j/cran-all/cranData/BDgraph/R/rmvnorm.R
## - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - | # Copyright (C) 2012 - 2021 Reza Mohammadi | # | # This file is part of BDgraph package. | # | # BDgraph is free software: you can redistribute it and/or modify it under | # the terms of the GNU General Public License as published by the Free | # Software Foundation; see <https://cran.r-project.org/web/licenses/GPL-3>.| # | # Maintainer: Reza Mohammadi <[email protected]> | ## - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - | # Reports the measures to assess the performance of estimated graphs | ## - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - | roc = function( pred, actual, auc = TRUE, smooth = FALSE, plot = FALSE, quiet = TRUE, ... ) { if( ( inherits( pred, "bdgraph" ) ) | ( inherits( pred, "ssgraph" ) ) ) pred = BDgraph::plinks( pred, round = 15 ) if( inherits( actual, "sim" ) ) actual = actual $ G if( is.matrix( pred ) ) pred = pred[ upper.tri( pred ) ] if( is.matrix( actual ) ) actual = actual[ upper.tri( actual ) ] if( any( round( pred ) < 0 ) || any( round( pred ) > 1 ) ) stop( "Elements of 'pred' must be between ( 0, 1 )" ) if( ( sum( actual == 0 ) + sum( actual == 1 ) ) != length( actual ) ) stop( "Elements of 'actual' must be 0 or 1" ) pROC::roc( response = actual, predictor = pred, levels = c( 0, 1 ), quiet = quiet, smooth = smooth, plot = plot, ... ) } ## - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - |
/scratch/gouwar.j/cran-all/cranData/BDgraph/R/roc.R
## - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - | # Copyright (C) 2012 - 2021 Reza Mohammadi | # | # This file is part of BDgraph package. | # | # BDgraph is free software: you can redistribute it and/or modify it under | # the terms of the GNU General Public License as published by the Free | # Software Foundation; see <https://cran.r-project.org/web/licenses/GPL-3>.| # | # Maintainer: Reza Mohammadi <[email protected]> | ## - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - | # Sampling from Wishart distribution | ## - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - | rwish = function( n = 1, p = 2, b = 3, D = diag( p ) ) { if( p < 1 ) stop( "'p' must be more than or equal with 1" ) if( b <= 2 ) stop( "'b' must be more than 2" ) if( !isSymmetric( D ) ) stop( "'D' must be a positive definite matrix" ) if( n < 1 ) stop( "'n' must be more than or equal with 1" ) if( ncol( D ) != p ) stop( "'p' and 'D' have non-conforming size" ) Ti = chol( solve( D ) ) K = matrix( 0, p, p ) if( n > 1 ) { samples = array( 0, c( p, p, n ) ) for ( i in 1 : n ) { result = .C( "rwish_c", as.double(Ti), K = as.double(K), as.integer(b), as.integer(p), PACKAGE = "BDgraph" ) samples[,,i] = matrix( result $ K, p, p ) } }else{ result = .C( "rwish_c", as.double(Ti), K = as.double(K), as.integer(b), as.integer(p), PACKAGE = "BDgraph" ) samples = matrix( result $ K, p, p ) } return( samples ) } ## - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - |
/scratch/gouwar.j/cran-all/cranData/BDgraph/R/rwish.R
## - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - | # Copyright (C) 2012 - 2021 Reza Mohammadi | # | # This file is part of BDgraph package. | # | # BDgraph is free software: you can redistribute it and/or modify it under | # the terms of the GNU General Public License as published by the Free | # Software Foundation; see <https://cran.r-project.org/web/licenses/GPL-3>.| # | # Maintainer: Reza Mohammadi <[email protected]> | ## - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - | # To select the graph in which the edge posterior probabilities are more # than "cut" value OR if cut is NULL to select the best graph ( graph with # the highest posterior probability ) ## - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - | select = function( bdgraph.obj, cut = NULL, vis = FALSE ) { if( is.matrix( bdgraph.obj ) ) { if( any( bdgraph.obj < 0 ) || any( bdgraph.obj > 1 ) ) stop( "Values of matrix 'bdgraph.obj' must be between 0 and 1" ) p_links = unclass( bdgraph.obj ) p = ncol( p_links ) }else{ if( ( !inherits( bdgraph.obj, "bdgraph" ) ) && ( !inherits( bdgraph.obj, "ssgraph" ) ) ) stop( "'bdgraph.obj' must be a matrix or an object from functions 'bdgraph()', 'bdgraph.mpl()', or 'ssgraph()'" ) if( ( inherits( bdgraph.obj, "bdgraph" ) ) | ( inherits( bdgraph.obj, "ssgraph" ) ) ) p_links = bdgraph.obj $ p_links if( inherits( bdgraph.obj, "bdgraph" ) ) p = ncol( bdgraph.obj $ last_graph ) if( inherits( bdgraph.obj, "ssgraph" ) ) p = ncol( bdgraph.obj $ K_hat ) } if( ( is.null( p_links ) ) && ( is.null( cut ) ) ) { sample_graphs <- bdgraph.obj $ sample_graphs graph_weights <- bdgraph.obj $ graph_weights indG_max <- sample_graphs[ which( graph_weights == max( graph_weights ) )[1] ] vec_G <- c( rep( 0, p * ( p - 1 ) / 2 ) ) vec_G[ which( unlist( strsplit( as.character( indG_max ), "" ) ) == 1 ) ] <- 1 dimlab <- colnames( bdgraph.obj $ last_graph ) selected_g <- matrix( 0, p, p, dimnames = list( dimlab, dimlab ) ) selected_g[ upper.tri( selected_g ) ] <- vec_G }else{ if( is.null( cut ) ) cut = 0.5 if( ( cut < 0 ) || ( cut > 1 ) ) stop( "'cut' must be between 0 and 1" ) if( is.null( p_links ) ) p_links = BDgraph::plinks( bdgraph.obj, round = 10 ) selected_g = 0 * p_links selected_g[ p_links > cut ] = 1 selected_g[ p_links <= cut ] = 0 } if( vis ) { main = ifelse( is.null( cut ), "Graph with highest posterior probability.", paste( c( "Graph with links posterior probabilities > ", cut ), collapse = "" ) ) BDgraph::plot.graph( selected_g, main = main ) } return( selected_g ) } ## - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - |
/scratch/gouwar.j/cran-all/cranData/BDgraph/R/select.R
## - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - | # Copyright (C) 2012 - 2021 Reza Mohammadi | # | # This file is part of BDgraph package. | # | # BDgraph is free software: you can redistribute it and/or modify it under | # the terms of the GNU General Public License as published by the Free | # Software Foundation; see <https://cran.r-project.org/web/licenses/GPL-3>.| # | # Maintainer: Reza Mohammadi <[email protected]> | ## - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - | # Compute the sparsity of an adjacency matrix | ## - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - | # Compute the proportion of non-links (non-zero elements) in the adj matrix sparsity = function( adj ) { G = BDgraph::get_graph( adj ) p = ncol( G ) sum_E = sum( G ) / 2 D = p * ( p - 1 ) / 2 sparsity_g = 1 - sum_E / D return( sparsity_g ) } ## - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - |
/scratch/gouwar.j/cran-all/cranData/BDgraph/R/sparsity.R
## - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - | # Copyright (C) 2012 - 2021 Reza Mohammadi | # | # This file is part of BDgraph package. | # | # BDgraph is free software: you can redistribute it and/or modify it under | # the terms of the GNU General Public License as published by the Free | # Software Foundation; see <https://cran.r-project.org/web/licenses/GPL-3>.| # | # Maintainer: Reza Mohammadi <[email protected]> | ## - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - | # Plot of graph size to check the convergency of BDMCMC algorithm | ## - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - | traceplot = function( bdgraph.obj, acf = FALSE, pacf = FALSE, main = NULL, ... ) { if( ( inherits( bdgraph.obj, "bdgraph" ) ) | ( inherits( bdgraph.obj, "ssgraph" ) ) ) { if( is.null( bdgraph.obj $ all_graphs ) ) stop( "'bdgraph.obj' must be an object of function 'bdgraph()' or 'ssgraph()' with option 'save = TRUE'" ) sample_graphs = bdgraph.obj $ sample_graphs all_graphs = bdgraph.obj $ all_graphs graph_weights = bdgraph.obj $ graph_weights sizesample_graphs = sapply( sample_graphs, function(x) length( which( unlist( strsplit( as.character(x), "" ) ) == 1 ) ) ) sizeall_graphs = sizesample_graphs[ all_graphs ] which_G_max = which( max( graph_weights ) == graph_weights ) size_selected_g = sizeall_graphs[ which_G_max ] sample_mcmc = sizeall_graphs if( is.null( main ) ) main = "Trace of graph size" ylab = "Graph size" }else{ if( !is.vector( bdgraph.obj ) ) stop( "'bdgraph.obj' must be an object of functions 'bdgraph()', 'bdgraph.mpl()', or 'ssgraph()' or a vector" ) sample_mcmc = bdgraph.obj if( is.null( main ) ) main = "Trace of MCMC sample" ylab = "" } if( acf == FALSE & pacf == FALSE ) op = graphics::par( mfrow = c( 1, 1 ), pty = "s" ) if( acf == TRUE & pacf == TRUE ) op = graphics::par( mfrow = c( 2, 2 ), pty = "s" ) if( acf == TRUE & pacf == FALSE ) op = graphics::par( mfrow = c( 1, 2 ), pty = "s" ) if( acf == FALSE & pacf == TRUE ) op = graphics::par( mfrow = c( 1, 2 ), pty = "s" ) x_vec = 1 : length( sample_mcmc ) graphics::plot( x = x_vec, y = sample_mcmc, type = "l", main = main, col = "lightblue", ylab = ylab, xlab = "Iteration", ... ) if( !is.vector( bdgraph.obj ) ) graphics::lines( x = x_vec, y = rep( size_selected_g, length( sample_mcmc ) ), col = "blue" ) if( acf == TRUE ) acf( sample_mcmc, main = "ACF for graph size" ) if( pacf == TRUE ) pacf( sample_mcmc, main = "PACF for graph size" ) graphics::par( op ) } ## - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - |
/scratch/gouwar.j/cran-all/cranData/BDgraph/R/traceplot.R
## - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - | # Copyright (C) 2012 - 2021 Reza Mohammadi | # | # This file is part of BDgraph package. | # | # BDgraph is free software: you can redistribute it and/or modify it under | # the terms of the GNU General Public License as published by the Free | # Software Foundation; see <https://cran.r-project.org/web/licenses/GPL-3>.| # | # Maintainer: Reza Mohammadi <[email protected]> | ## - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - | # For count data: to transfer raw data for the algorithm | ## - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - | transfer = function( r_data ) { if( inherits( r_data, "sim" ) ) r_data <- r_data $ data n = dim( r_data )[ 1 ] p = dim( r_data )[ 2 ] data = matrix( 0, nrow = n, ncol = p + 1 ) size_unique_data = 0 result = .C( "transfer_data", as.integer(r_data), data = as.integer(data), as.integer(n), as.integer(p), size_unique_data = as.integer(size_unique_data), PACKAGE = "BDgraph" ) size_unique_data = result $ size_unique_data label = colnames( r_data ) if( is.null( label ) ) label = 1:p data = matrix ( result $ data, n, p + 1, dimnames = list( NULL, c( label, "ferq" ) ) ) data = data[ (1:size_unique_data), ] return( data ) } ## - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - |
/scratch/gouwar.j/cran-all/cranData/BDgraph/R/transfer.R
## ----opts, echo = FALSE, message = FALSE, warning = FALSE--------------------- knitr::opts_chunk $ set( collapse = TRUE, comment = " ", fig.width = 7, fig.height = 7, fig.align = "center" ) ## ----eval = FALSE------------------------------------------------------------- # install.packages( "BDgraph" ) ## ----loadpkg, message = FALSE, warning = FALSE-------------------------------- library( BDgraph ) ## ----fig.align = 'center'----------------------------------------------------- set.seed( 20 ) data.sim = bdgraph.sim( n = 200, p = 15, graph = "scale-free", vis = TRUE ) ## ----------------------------------------------------------------------------- bdgraph.obj = bdgraph( data = data.sim, method = "ggm", iter = 5000, verbose = FALSE ) ## ----fig.align = 'center', fig.width = 3, fig.height = 3---------------------- conf.mat( actual = data.sim, pred = bdgraph.obj, cutoff = 0.5 ) conf.mat.plot( actual = data.sim, pred = bdgraph.obj, cutoff = 0.5 ) ## ----fig.align = 'center'----------------------------------------------------- compare( data.sim, bdgraph.obj, main = c( "Target", "BDgraph" ), vis = TRUE ) ## ----fig.align = 'center', fig.width = 3, fig.height = 3---------------------- bdgraph.mpl.obj = bdgraph.mpl( data = data.sim, method = "ggm", iter = 5000, verbose = FALSE ) conf.mat( actual = data.sim, pred = bdgraph.mpl.obj ) conf.mat.plot( actual = data.sim, pred = bdgraph.mpl.obj ) ## ----fig.align = 'center'----------------------------------------------------- compare( list( bdgraph.obj, bdgraph.mpl.obj ), data.sim, main = c( "Target", "BDgraph", "BDgraph.mpl" ), vis = TRUE ) ## ----fig.align = 'center'----------------------------------------------------- plotroc( list( bdgraph.obj, bdgraph.mpl.obj ), data.sim, cut = 200, labels = c( "BDgraph", "BDgraph.mpl" ), color = c( "blue", "red" ) ) ## ----fig.align = 'center'----------------------------------------------------- set.seed( 2 ) data.sim = bdgraph.sim( n = 300, p = 10, type = "mixed", graph = "random", vis = TRUE ) ## ----------------------------------------------------------------------------- bdgraph.obj = bdgraph( data = data.sim, method = "gcgm", iter = 5000, verbose = FALSE ) ## ----fig.align = 'center'----------------------------------------------------- compare( bdgraph.obj, data.sim, main = c( "Target", "BDgraph" ), vis = TRUE ) ## ----fig.align = 'center'----------------------------------------------------- plotroc( bdgraph.obj, data.sim, labels = "BDgraph", color = "blue" )
/scratch/gouwar.j/cran-all/cranData/BDgraph/inst/doc/BDgraph-Examples.R
--- title: "<center> BDgraph with Simple Examples <center>" author: "Reza Mohammadi (https://orcid.org/0000-0001-9538-0648)" date: "`r Sys.Date()`" output: rmarkdown::html_vignette: toc: true number_sections: false fig_caption: yes fig_width: 3.5 fig_height: 3.5 dpi: 72 dev.args: list( pointsize = 11 ) vignette: > %\VignetteIndexEntry{BDgraph with Simple Examples} %\VignetteEncoding{UTF-8} %\VignetteEngine{knitr::rmarkdown} editor_options: markdown: wrap: 72 --- ```{r opts, echo = FALSE, message = FALSE, warning = FALSE} knitr::opts_chunk $ set( collapse = TRUE, comment = " ", fig.width = 7, fig.height = 7, fig.align = "center" ) ``` The `R` package **BDgraph** provides statistical tools for Bayesian structure learning for undirected graphical models with *continuous*, *count*, *binary*, and *mixed data*. The package is implemented the recent improvements in the Bayesian graphical models' literature, including [Mohammadi and Wit (2015)](https://projecteuclid.org/euclid.ba/1422468425), [Mohammadi et al. (2021)](https://doi.org/10.1080/01621459.2021.1996377), [Mohammadi et al. (2017)](https://rss.onlinelibrary.wiley.com/doi/full/10.1111/rssc.12171), and [Dobra and Mohammadi (2018)](https://projecteuclid.org/euclid.aoas/1532743478). Besides, the package contains several functions for simulation and visualization, as well as several multivariate datasets taken from the literature. Install **BDgraph** using ```{r eval = FALSE} install.packages( "BDgraph" ) ``` First, we load **BDgraph** package ```{r loadpkg, message = FALSE, warning = FALSE} library( BDgraph ) ``` Here are two simple examples to show how to use the functionality of the package. # Example 1: Gaussian Graphical Models Here is a simple example to see the performance of the package for the Gaussian graphical models. First, by using the function `bdgraph.sim()`, we simulate 200 observations (n = 200) from a multivariate Gaussian distribution with 15 variables (p = 15) and "scale-free" graph structure, as follows ```{r fig.align = 'center'} set.seed( 20 ) data.sim = bdgraph.sim( n = 200, p = 15, graph = "scale-free", vis = TRUE ) ``` Since the generated data are Gaussian, we run the `bdgraph()` function by choosing `method = "ggm"`, as follows ```{r} bdgraph.obj = bdgraph( data = data.sim, method = "ggm", iter = 5000, verbose = FALSE ) ``` To report confusion matrix with cutoff point 0.5: ```{r fig.align = 'center', fig.width = 3, fig.height = 3} conf.mat( actual = data.sim, pred = bdgraph.obj, cutoff = 0.5 ) conf.mat.plot( actual = data.sim, pred = bdgraph.obj, cutoff = 0.5 ) ``` To compare the result with the true graph ```{r fig.align = 'center'} compare( data.sim, bdgraph.obj, main = c( "Target", "BDgraph" ), vis = TRUE ) ``` Now, as an alternative, we run the `bdgraph.mpl()` function which is based on the GGMs and marginal pseudo-likelihood, as follows ```{r fig.align = 'center', fig.width = 3, fig.height = 3} bdgraph.mpl.obj = bdgraph.mpl( data = data.sim, method = "ggm", iter = 5000, verbose = FALSE ) conf.mat( actual = data.sim, pred = bdgraph.mpl.obj ) conf.mat.plot( actual = data.sim, pred = bdgraph.mpl.obj ) ``` We could compare the results of both algorithms with the true graph as follows ```{r fig.align = 'center'} compare( list( bdgraph.obj, bdgraph.mpl.obj ), data.sim, main = c( "Target", "BDgraph", "BDgraph.mpl" ), vis = TRUE ) ``` To see the performance of the BDMCMC algorithm we could plot the ROC curve as follows ```{r fig.align = 'center'} plotroc( list( bdgraph.obj, bdgraph.mpl.obj ), data.sim, cut = 200, labels = c( "BDgraph", "BDgraph.mpl" ), color = c( "blue", "red" ) ) ``` # Example 2: Gaussian Copula Graphical Models Here is a simple example to see the performance of the package for the mixed data using Gaussian copula graphical models. First, by using the function `bdgraph.sim()`, we simulate 300 observations (n = 300) from mixed data (`type = "mixed"`) with 10 variables (p = 10) and "random" graph structure, as follows ```{r fig.align = 'center'} set.seed( 2 ) data.sim = bdgraph.sim( n = 300, p = 10, type = "mixed", graph = "random", vis = TRUE ) ``` Since the generated data are mixed data, we are using run the `bdgraph()` function by choosing `method = "gcgm"`, as follows: ```{r} bdgraph.obj = bdgraph( data = data.sim, method = "gcgm", iter = 5000, verbose = FALSE ) ``` To compare the result with the true graph, we could run ```{r fig.align = 'center'} compare( bdgraph.obj, data.sim, main = c( "Target", "BDgraph" ), vis = TRUE ) ``` ```{r fig.align = 'center'} plotroc( bdgraph.obj, data.sim, labels = "BDgraph", color = "blue" ) ``` For more examples see [Mohammadi and Wit (2019)](https://www.jstatsoft.org/article/view/v089i03).
/scratch/gouwar.j/cran-all/cranData/BDgraph/inst/doc/BDgraph-Examples.Rmd
## ----opts, echo = FALSE, message = FALSE, warning = FALSE--------------------- knitr::opts_chunk $ set( collapse = TRUE, comment = " ", fig.width = 7, fig.height = 7, fig.align = "center" ) ## ----eval = FALSE------------------------------------------------------------- # install.packages( "BDgraph" ) # # library( BDgraph ) ## ----pressure, echo = FALSE, out.width = '85%'-------------------------------- knitr::include_graphics( "Figure_1.png" ) ## ----eval = FALSE------------------------------------------------------------- # bdgraph( data, n = NULL, method = "ggm", algorithm = "bdmcmc", iter = 5000, # burnin = iter / 2, not.cont = NULL, g.prior = 0.5, df.prior = 3, # g.start = "empty", jump = NULL, save = FALSE, # cores = NULL, threshold = 1e-8, verbose = TRUE ) ## ----eval = FALSE------------------------------------------------------------- # plinks( bdgraph.obj, round = 2, burnin = NULL ) ## ----eval = FALSE------------------------------------------------------------- # select( bdgraph.obj, cut = NULL, vis = FALSE ) ## ----eval = FALSE------------------------------------------------------------- # plotcoda( bdgraph.obj, thin = NULL, control = TRUE, main = NULL, # verbose = TRUE, ... ) ## ----eval = FALSE------------------------------------------------------------- # traceplot( bdgraph.obj, acf = FALSE, pacf = FALSE, main = NULL, ... ) ## ----eval = FALSE------------------------------------------------------------- # compare( pred, actual, main = NULL, vis = FALSE ) ## ----eval = FALSE------------------------------------------------------------- # plotroc = function( pred, actual, cut = 20, smooth = FALSE, ... ) ## ----eval = FALSE------------------------------------------------------------- # bdgraph.sim( p = 10, graph = "random", n = 0, type = "Gaussian", prob = 0.2, # size = NULL, mean = 0, class = NULL, cut = 4, b = 3, # D = diag( p ), K = NULL, sigma = NULL, # q = exp(-1), beta = 1, vis = FALSE, rewire = 0.05, # range.mu = c( 3, 5 ), range.dispersion = c( 0.01, 0.1 ) ) ## ----eval = FALSE------------------------------------------------------------- # graph.sim( p = 10, graph = "random", prob = 0.2, size = NULL, class = NULL, # vis = FALSE, rewire = 0.05 ) ## ----------------------------------------------------------------------------- library( BDgraph ) set.seed( 5 ) data.sim <- bdgraph.sim( n = 60, p = 8, graph = "scale-free", type = "Gaussian" ) round( head( data.sim $ data, 4 ), 2 ) ## ----eval = TRUE-------------------------------------------------------------- sample.bdmcmc <- bdgraph( data = data.sim, method = "ggm", algorithm = "bdmcmc", iter = 5000, save = TRUE, verbose = FALSE ) ## ----------------------------------------------------------------------------- summary( sample.bdmcmc ) ## ----------------------------------------------------------------------------- sample.rjmcmc <- bdgraph( data = data.sim, method = "ggm", algorithm = "rjmcmc", iter = 5000, save = TRUE, verbose = FALSE ) ## ----eval = FALSE------------------------------------------------------------- # plotroc( list( sample.bdmcmc, sample.rjmcmc ), data.sim, smooth = TRUE, # labels = c( "BDMCMC", "RJMCMC" ), color = c( "blue", "red" ) ) ## ----------------------------------------------------------------------------- compare( list( sample.bdmcmc, sample.rjmcmc ), data.sim, main = c( "True graph", "BDMCMC", "RJMCMC" ), vis = TRUE ) ## ----------------------------------------------------------------------------- plotcoda( sample.bdmcmc, verbose = FALSE ) plotcoda( sample.rjmcmc, verbose = FALSE )
/scratch/gouwar.j/cran-all/cranData/BDgraph/inst/doc/Introduction-BDgraph.R
--- title: "<center> Introduction to BDgraph <center>" author: "Reza Mohammadi (https://orcid.org/0000-0001-9538-0648)" date: "`r Sys.Date()`" output: rmarkdown::html_vignette: toc: true number_sections: true fig_caption: yes fig_width: 3.5 fig_height: 3.5 dpi: 72 dev.args: list( pointsize = 11 ) vignette: > %\VignetteIndexEntry{Introduction to BDgraph} %\VignetteEncoding{UTF-8} %\VignetteEngine{knitr::rmarkdown} editor_options: markdown: wrap: 72 --- ```{r opts, echo = FALSE, message = FALSE, warning = FALSE} knitr::opts_chunk $ set( collapse = TRUE, comment = " ", fig.width = 7, fig.height = 7, fig.align = "center" ) ``` This introduction to the `R` package **BDgraph** is a modified version of [Mohammadi and Wit (2019)](https://www.jstatsoft.org/article/view/v089i03), published in the Journal of Statistical Software. The `R` package **BDgraph** provides statistical tools for Bayesian structure learning for undirected graphical models with *continuous*, *count*, *binary*, and *mixed data*. The package is implemented the recent improvements in the Bayesian graphical models' literature, including [Mohammadi and Wit (2015)](https://projecteuclid.org/euclid.ba/1422468425), [Mohammadi et al. (2021)](https://doi.org/10.1080/01621459.2021.1996377), [Mohammadi et al. (2017)](https://rss.onlinelibrary.wiley.com/doi/full/10.1111/rssc.12171), [Dobra and Mohammadi (2018)](https://projecteuclid.org/euclid.aoas/1532743478), and [Vinciotti et al. (2022)](https://doi.org/10.48550/arXiv.2203.10118). Besides, the package contains several functions for simulation and visualization, as well as several multivariate datasets taken from the literature. # User interface In the `R` environment, one can access and load the **BDgraph** package by using the following commands: Install **BDgraph** using ```{r eval = FALSE} install.packages( "BDgraph" ) library( BDgraph ) ``` To speed up computations, we efficiently implement the **BDgraph** package by linking the `C++` code to `R`. The computationally extensive tasks of the package are implemented in parallel in `C++` using **OpenMP**. For the `C++` code, we use the highly optimized LAPACK and BLAS, as linear algebra libraries on systems that provide them. The use of these libraries significantly improves program speed. We design the **BDgraph** package to provide a Bayesian framework for undirected graph estimation of different types of datasets such as continuous, discrete or mixed data. The package facilitates a pipeline for analysis by four functional modules as follows ```{r pressure, echo = FALSE, out.width = '85%'} knitr::include_graphics( "Figure_1.png" ) ``` **Module 1. Data simulation:** Function `bdgraph.sim()` simulates multivariate Gaussian, discrete, binary, and mixed data with different undirected graph structures, including *"random"*, *"cluster"*, *"scale-free"*, *"lattice"*, *"hub"*, *"star"*, *"circle"*, *"AR(1)"*, *"AR(2)"*, and *"fixed"* graphs. Users can determine the sparsity of the graph structure and can generate mixed data, including *"count"*, *"ordinal"*, *"binary"*, *"Gaussian"*, and *"non-Gaussian"* variables. **Module 2. Methods:** The function `bdgraph()`, `bdgraph.mpl()`, and `bdgraph.dw()` provide several estimation methods regarding to the type of data: * Bayesian graph estimation for the multivariate data that follow the Gaussianity assumption, based on the Gaussian graphical models (GGMs); see [Mohammadi and Wit (2015)](https://projecteuclid.org/euclid.ba/1422468425). * Bayesian graph estimation for multivariate non-Gaussian, discrete, and mixed data, based on Gaussian copula graphical models (GCGMs); see [Mohammadi et al. (2017)](https://rss.onlinelibrary.wiley.com/doi/full/10.1111/rssc.12171) and [Vinciotti et al. (2022)](https://doi.org/10.48550/arXiv.2203.10118). * Bayesian graph estimation for multivariate discrete and binary data, based on discrete graphical models (DGMs); see [Dobra and Mohammadi (2018)](https://projecteuclid.org/euclid.aoas/1532743478). **Module 3. Algorithms:** The function `bdgraph()` and `bdgraph.mpl()` provide several sampling algorithms: * Birth-death MCMC (BDMCMC) sampling algorithms described in [Mohammadi et al. (2021)](https://doi.org/10.1080/01621459.2021.1996377) and [Mohammadi and Wit (2015)](https://projecteuclid.org/euclid.ba/1422468425). * Reversible jump MCMC (RJMCMC) sampling algorithms described in [Dobra et al. (2011)](https://doi.org/10.1198/jasa.2011.tm10465). * Hill-climbing (HC) search algorithm described in [Pensar et al. (2017)](https://doi.org/10.1214/16-ba1032). **Module 4. Results:** Includes four types of functions: * *Graph selection*: The functions `select()`, `plinks()`, and `pgraph()` provide the selected graph, the posterior link inclusion probabilities and the posterior probability of each graph, respectively. * *Convergence check*: The functions `plotcoda()` and `traceplot()` provide several visualization plots to monitor the convergence of the sampling algorithms. * *Comparison and goodness-of-fit*: The functions `compare()` and `plotroc()` provide several comparison measures and an ROC plot for model comparison. * *Visualization*: The plotting functions `plot.bdgraph()` and `plot.sim()` provide visualizations of the simulated data and estimated graphs. # The BDgraph environment The **BDgraph** package provides a set of comprehensive tools related to Bayesian graphical models; we describe below the essential functions available in the package. ## Posterior sampling We design the function `bdgraph()`, as the main function of the package, to take samples from the posterior distributions based on both of our Bayesian frameworks (GGMs and GCGMs). By default, the `bdgraph()` function is based on underlying sampling algorithm defined in [Mohammadi et al. (2021)](https://doi.org/10.1080/01621459.2021.1996377). Moreover, as an alternative to those BDMCMC sampling algorithms, we implement RJMCMC sampling algorithms for both the Gaussian and non-Gaussian frameworks. By using the following function ```{r eval = FALSE} bdgraph( data, n = NULL, method = "ggm", algorithm = "bdmcmc", iter = 5000, burnin = iter / 2, not.cont = NULL, g.prior = 0.5, df.prior = 3, g.start = "empty", jump = NULL, save = FALSE, cores = NULL, threshold = 1e-8, verbose = TRUE ) ``` we obtain a sample from our target joint posterior distribution. `bdgraph()` returns an object of `S3` class type *bdgraph*. The functions `plot()`, `print()`, and `summary()` are working with the object *bdgraph*. The input `data` can be an ($n \times p$) *matrix* or a *data.frame* or a covariance ($p \times p$) matrix ($n$ is the sample size and $p$ is the dimension); it can also be an object of class *sim*, which is the output of function `bdgraph.sim()`. The argument `method` determines the type of methods, GGMs, GCGMs. Option *"ggm"* is based on Gaussian graphical models that is designed for multivariate Gaussian data. Option *"gcgm"* is based on the GCGMs that is designed for non-Gaussian data such as, non-Gaussian continuous, discrete or mixed data. The argument `algorithm` refers the type of sampling algorithms which could be based on BDMCMC or RJMCMC. Option *"bdmcmc"* (as default) is for the BDMCMC sampling algorithms. Option *"rjmcmc"* is for the RJMCMC sampling algorithms, which are alternative algorithms. See [Mohammadi and Wit (2015)](https://projecteuclid.org/euclid.ba/1422468425). The argument `g.start` specifies the initial graph for our sampling algorithm. It could be *"empty"* (default) or *"full"*. Option *"empty"* means the initial graph is an empty graph and *"full"* means a full graph. It also could be an object with `S3` class \code{"bdgraph"}, which allows users to run the sampling algorithm from the last objects of the previous run. The argument `jump` determines the number of links that are simultaneously updated in the BDMCMC algorithm. For parallel computation in `C++` which is based on **OpenMP**, user can use argument `cores` which specifies the number of cores to use for parallel execution. Note, the package **BDgraph** has two other sampling functions, `bdgraph.mpl()` and `bdgraph.dwl()` which are designed in the similar framework as the function `bdgraph()`. The function `bdgraph.mpl()` is for Bayesian model determination in undirected graphical models based on marginal pseudo-likelihood, for both continuous and discrete variables; For more details see \cite{dobra2018}. The function `bdgraph.dwl()` is for Bayesian model determination for count data; See [Vinciotti et al. (2022)](https://doi.org/10.48550/arXiv.2203.10118). ## Posterior graph selection We design the **BDgraph** package in such a way that posterior graph selection can be done based on both Bayesian model averaging (BMA), as default, and maximum a posterior probability (MAP). The functions `select()` and `plinks()` are designed for the objects of class *bdgraph* to provide BMA and MAP estimations for posterior graph selection. The function ```{r eval = FALSE} plinks( bdgraph.obj, round = 2, burnin = NULL ) ``` provides estimated posterior link inclusion probabilities for all possible links, which is based on BMA estimation. In cases where the sampling algorithm is based on BDMCMC, these probabilities for all possible links $e=(i,j)$ in the graph can be estimated using a Rao-Blackwellized estimate based on \begin{eqnarray} \label{posterior-link} Pr( e \in E | data )= \frac{\sum_{t=1}^{N}{1(e \in E^{(t)}) W(K^{(t)}) }}{\sum_{t=1}^{N}{W(K^{(t)})}}, \end{eqnarray} where $N$ is the number of iteration and $W(K^{(t)})$ are the weights of the graph $G^{(t)}$ with the precision matrix $K^{(t)}$. The function ```{r eval = FALSE} select( bdgraph.obj, cut = NULL, vis = FALSE ) ``` provides the inferred graph based on both BMA (as default) and MAP estimators. The inferred graph based on BMA estimation is a graph with links for which the estimated posterior probabilities are greater than a certain cut-point (as default `cut=0.5`). The inferred graph based on MAP estimation is a graph with the highest posterior probability. Note, for posterior graph selection based on MAP estimation we should save all adjacency matrices by using the option `save = TRUE` in the function `bdgraph()`. Saving all the adjacency matrices could, however, cause memory problems. ## Convergence check In general, convergence in MCMC approaches can be difficult to evaluate. From a theoretical point of view, the sampling distribution will converge to the target joint posterior distribution as the number of iteration increases to infinity. Because we normally have little theoretical insight about how quickly MCMC algorithms converge to the target stationary distribution we therefore rely on post hoc testing of the sampled output. In general, the sample is divided into two parts: a ``burn-in'' part of the sample and the remainder, in which the chain is considered to have converged sufficiently close to the target posterior distribution. Two questions then arise: How many samples are sufficient? How long should the burn-in period be? The `plotcoda()` and `traceplot()` are two visualization functions for the objects of class *bdgraph* that make it possible to check the convergence of the search algorithms in **BDgraph**. The function ```{r eval = FALSE} plotcoda( bdgraph.obj, thin = NULL, control = TRUE, main = NULL, verbose = TRUE, ... ) ``` provides the trace of estimated posterior probability of all possible links to check convergence of the search algorithms. Option \code{control} is designed for the case where if `control=TRUE` (as default) and the dimension ($p$) is greater than $15$, then $100$ links are randomly selected for visualization. The function ```{r eval = FALSE} traceplot( bdgraph.obj, acf = FALSE, pacf = FALSE, main = NULL, ... ) ``` provides the trace of graph size to check convergence of the search algorithms. Option `acf` is for visualization of the autocorrelation functions for graph size; option `pacf` visualizes the partial autocorrelations. ## Comparison and goodness-of-fit The functions `compare()` and `plotroc()` are designed to evaluate and compare the performance of the selected graph. These functions are particularly useful for simulation studies. With the function ```{r eval = FALSE} compare( pred, actual, main = NULL, vis = FALSE ) ``` we can evaluate the performance of the Bayesian methods available in our **BDgraph** package and compare them with alternative approaches. This function provides several measures such as the balanced $F$-score measure, which is defined as follows: \begin{eqnarray} \label{f1} F_1\mbox{-score} = \frac{2 \mbox{TP}}{2 \mbox{TP + FP + FN}}, \end{eqnarray} where TP, FP and FN are the number of true positives, false positives and false negatives, respectively. The $F_1$-score lies between $0$ and $1$, where $1$ stands for perfect identification and $0$ for no true positives. The function ```{r eval = FALSE} plotroc = function( pred, actual, cut = 20, smooth = FALSE, ... ) ``` provides a ROC plot for visualization comparison based on the estimated posterior link inclusion probabilities. See also function `roc()` for a ROC curve specifically for graph structure learning. ## Data simulation The function `bdgraph.sim()` is designed to simulate different types of datasets with various graph structures. The function ```{r eval = FALSE} bdgraph.sim( p = 10, graph = "random", n = 0, type = "Gaussian", prob = 0.2, size = NULL, mean = 0, class = NULL, cut = 4, b = 3, D = diag( p ), K = NULL, sigma = NULL, q = exp(-1), beta = 1, vis = FALSE, rewire = 0.05, range.mu = c( 3, 5 ), range.dispersion = c( 0.01, 0.1 ) ) ``` can simulate multivariate Gaussian, non-Gaussian, discrete, binary and mixed data with different undirected graph structures, including *"random"*, *"cluster"*, *"scale-free"*, *"lattice"*, *"hub"*, *"star"*, *"circle"*, *"AR(1)"*, *"AR(2)"*, and *"fixed"* graphs. Users can specify the type of multivariate data by option `type` and the graph structure by option `graph`. They can determine the sparsity level of the obtained graph by using option `prob`. With this function users can generate mixed data from *"count"*, *"ordinal"*, *"binary"*, *"Gaussian"* and *"non-Gaussian"* distributions. `bdgraph.sim()` returns an object of the `S3` class type "sim". Functions `plot()` and `print()` work with this object type. There is another function in the **BDgraph** package with the name `graph.sim()` which is designed to simulate different types of graph structures. The function ```{r eval = FALSE} graph.sim( p = 10, graph = "random", prob = 0.2, size = NULL, class = NULL, vis = FALSE, rewire = 0.05 ) ``` can simulate different undirected graph structures, including *"random"*, *"cluster"*, *"scale-free"*, *"lattice"*, *"hub"*, *"star"*, and *"circle"* graphs. Users can specify the type of graph structure by option `graph`. They can determine the sparsity level of the obtained graph by using option `prob`. `bdgraph.sim()` returns an object of the `S3` class type "graph". Functions `plot()` and `print()` work with this object type. # An example on simulated data We illustrate the user interface of the **BDgraph** package by use of a simple simulation. By using the function `bdgraph.sim()` we simulate $60$ observations ($n=60$) from a multivariate Gaussian distribution with $8$ variables ($p=8$) and ``scale-free'' graph structure, as below. ```{r} library( BDgraph ) set.seed( 5 ) data.sim <- bdgraph.sim( n = 60, p = 8, graph = "scale-free", type = "Gaussian" ) round( head( data.sim $ data, 4 ), 2 ) ``` Since the generated data are Gaussian, we run the BDMCMC algorithm which is based on Gaussian graphical models. For this we choose `method = "ggm"`, as follows: ```{r eval = TRUE} sample.bdmcmc <- bdgraph( data = data.sim, method = "ggm", algorithm = "bdmcmc", iter = 5000, save = TRUE, verbose = FALSE ) ``` We choose option `save = TRUE` to save the samples in order to check convergence of the algorithm. Running this function takes less than one second, as the computational intensive tasks are performed in `C++` and interfaced with `R`. Since the function `bdgraph()` returns an object of class `S3`, users can see the summary result as follows ```{r} summary( sample.bdmcmc ) ``` The summary results are the adjacency matrix of the selected graph (`selected_g`) based on BMA estimation, the estimated posterior probabilities of all possible links (`p_links`) and the estimated precision matrix (`K_hat`). In addition, the function `summary()` reports a visualization summary of the results as we can see above. At the top-left is the graph with the highest posterior probability. The plot at the top-right gives the estimated posterior probabilities of all the graphs which are visited by the BDMCMC algorithm; it indicates that our algorithm visits more than $2000$ different graphs. The plot at the bottom-left gives the estimated posterior probabilities of the size of the graphs; it indicates that our algorithm visited mainly graphs with sizes between $4$ and $18$ links. At the bottom-right is the trace of our algorithm based on the size of the graphs. The function `compare()` provides several measures to evaluate the performance of our algorithms and compare them with alternative approaches with respect to the true graph structure. To evaluate the performance of the BDMCMC algorithm and compare it with that of an alternative algorithm, we also run the RJMCMC algorithm under the same conditions as below. ```{r} sample.rjmcmc <- bdgraph( data = data.sim, method = "ggm", algorithm = "rjmcmc", iter = 5000, save = TRUE, verbose = FALSE ) ``` where the sampling algorithm from the joint posterior distribution is based on the RJMCMC algorithm. Users can compare the performance of these two algorithms by using the code ```{r eval = FALSE} plotroc( list( sample.bdmcmc, sample.rjmcmc ), data.sim, smooth = TRUE, labels = c( "BDMCMC", "RJMCMC" ), color = c( "blue", "red" ) ) ``` which visualizes an ROC plot for both algorithms, BDMCMC and RJMCMC. We can also compare the performance of those algorithms by using the `compare()` function as follows: ```{r} compare( list( sample.bdmcmc, sample.rjmcmc ), data.sim, main = c( "True graph", "BDMCMC", "RJMCMC" ), vis = TRUE ) ``` The results show that for this specific simulated example both algorithms have more or less the same performance; See [Mohammadi et al. (2021)](https://doi.org/10.1080/01621459.2021.1996377) for a comprehensive simulation study. In this simulation example, we run both BDMCMC and RJMCMC algorithms for $5,000$ iterations, $2,500$ of them as burn-in. To check whether the number of iterations is enough and to monitoring the convergence of our both algorithm, we run ```{r} plotcoda( sample.bdmcmc, verbose = FALSE ) plotcoda( sample.rjmcmc, verbose = FALSE ) ``` The results indicate that the BDMCMC algorithm converges faster with compare with RJMCMC algorithm. # References Mohammadi, R. and Wit, E. C. (2019). **BDgraph**: An *R* Package for Bayesian Structure Learning in Graphical Models, *Journal of Statistical Software*, 89(3):1-30, [doi:10.18637/jss.v089.i03](https://www.jstatsoft.org/article/view/v089i03). Mohammadi, A. and Wit, E. C. (2015). Bayesian Structure Learning in Sparse Gaussian Graphical Models, *Bayesian Analysis*, 10(1):109-138, [doi:10.1214/14-BA889](https://projecteuclid.org/euclid.ba/1422468425). Mohammadi, R., Massam, H. and Letac, G. (2021). Accelerating Bayesian Structure Learning in Sparse Gaussian Graphical Models, *Journal of the American Statistical Association*, [doi:10.1080/01621459.2021.1996377](https://doi.org/10.1080/01621459.2021.1996377) Mohammadi, A., et al (2017). Bayesian modelling of Dupuytren disease by using Gaussian copula graphical models, *Journal of the Royal Statistical Society: Series C*, 66(3):629-645, [doi:10.1111/rssc.12171](https://rss.onlinelibrary.wiley.com/doi/full/10.1111/rssc.12171) Dobra, A. and Mohammadi, R. (2018). Loglinear Model Selection and Human Mobility, *Annals of Applied Statistics*, 12(2):815-845, [doi:10.1214/18-AOAS1164](https://projecteuclid.org/euclid.aoas/1532743478) Vinciotti, V., Behrouzi, P., and Mohammadi, R. (2022) Bayesian structural learning of microbiota systems from count metagenomic data, *arXiv preprint*, [doi:10.48550/arXiv.2203.10118](https://doi.org/10.48550/arXiv.2203.10118) Dobra, A. and Lenkoski, A. (2011). Copula Gaussian graphical models and their application to modeling functional disability data, *The Annals of Applied Statistics*, 5(2A):969-93 Dobra, A., et al. (2011). Bayesian inference for general Gaussian graphical models with application to multivariate lattice data. *Journal of the American Statistical Association*, 106(496):1418-33, [doi:10.1198/jasa.2011.tm10465](https://doi.org/10.1198/jasa.2011.tm10465) Mohammadi, A. and Dobra, A. (2017). The `R` Package **BDgraph** for Bayesian Structure Learning in Graphical Models, *ISBA Bulletin*, 24(4):11-16 Lenkoski, A. (2013). A direct sampler for G-Wishart variates, *Stat*, 2(1):119-28, [doi:10.1002/sta4.23](https://doi.org/10.1002/sta4.23) Pensar, J. et al (2017) Marginal pseudo-likelihood learning of discrete Markov network structures, *Bayesian Analysis*, 12(4):1195-215, [doi:10.1214/16-BA1032](https://doi.org/10.1214/16-ba1032).
/scratch/gouwar.j/cran-all/cranData/BDgraph/inst/doc/Introduction-BDgraph.Rmd
--- title: "<center> BDgraph with Simple Examples <center>" author: "Reza Mohammadi (https://orcid.org/0000-0001-9538-0648)" date: "`r Sys.Date()`" output: rmarkdown::html_vignette: toc: true number_sections: false fig_caption: yes fig_width: 3.5 fig_height: 3.5 dpi: 72 dev.args: list( pointsize = 11 ) vignette: > %\VignetteIndexEntry{BDgraph with Simple Examples} %\VignetteEncoding{UTF-8} %\VignetteEngine{knitr::rmarkdown} editor_options: markdown: wrap: 72 --- ```{r opts, echo = FALSE, message = FALSE, warning = FALSE} knitr::opts_chunk $ set( collapse = TRUE, comment = " ", fig.width = 7, fig.height = 7, fig.align = "center" ) ``` The `R` package **BDgraph** provides statistical tools for Bayesian structure learning for undirected graphical models with *continuous*, *count*, *binary*, and *mixed data*. The package is implemented the recent improvements in the Bayesian graphical models' literature, including [Mohammadi and Wit (2015)](https://projecteuclid.org/euclid.ba/1422468425), [Mohammadi et al. (2021)](https://doi.org/10.1080/01621459.2021.1996377), [Mohammadi et al. (2017)](https://rss.onlinelibrary.wiley.com/doi/full/10.1111/rssc.12171), and [Dobra and Mohammadi (2018)](https://projecteuclid.org/euclid.aoas/1532743478). Besides, the package contains several functions for simulation and visualization, as well as several multivariate datasets taken from the literature. Install **BDgraph** using ```{r eval = FALSE} install.packages( "BDgraph" ) ``` First, we load **BDgraph** package ```{r loadpkg, message = FALSE, warning = FALSE} library( BDgraph ) ``` Here are two simple examples to show how to use the functionality of the package. # Example 1: Gaussian Graphical Models Here is a simple example to see the performance of the package for the Gaussian graphical models. First, by using the function `bdgraph.sim()`, we simulate 200 observations (n = 200) from a multivariate Gaussian distribution with 15 variables (p = 15) and "scale-free" graph structure, as follows ```{r fig.align = 'center'} set.seed( 20 ) data.sim = bdgraph.sim( n = 200, p = 15, graph = "scale-free", vis = TRUE ) ``` Since the generated data are Gaussian, we run the `bdgraph()` function by choosing `method = "ggm"`, as follows ```{r} bdgraph.obj = bdgraph( data = data.sim, method = "ggm", iter = 5000, verbose = FALSE ) ``` To report confusion matrix with cutoff point 0.5: ```{r fig.align = 'center', fig.width = 3, fig.height = 3} conf.mat( actual = data.sim, pred = bdgraph.obj, cutoff = 0.5 ) conf.mat.plot( actual = data.sim, pred = bdgraph.obj, cutoff = 0.5 ) ``` To compare the result with the true graph ```{r fig.align = 'center'} compare( data.sim, bdgraph.obj, main = c( "Target", "BDgraph" ), vis = TRUE ) ``` Now, as an alternative, we run the `bdgraph.mpl()` function which is based on the GGMs and marginal pseudo-likelihood, as follows ```{r fig.align = 'center', fig.width = 3, fig.height = 3} bdgraph.mpl.obj = bdgraph.mpl( data = data.sim, method = "ggm", iter = 5000, verbose = FALSE ) conf.mat( actual = data.sim, pred = bdgraph.mpl.obj ) conf.mat.plot( actual = data.sim, pred = bdgraph.mpl.obj ) ``` We could compare the results of both algorithms with the true graph as follows ```{r fig.align = 'center'} compare( list( bdgraph.obj, bdgraph.mpl.obj ), data.sim, main = c( "Target", "BDgraph", "BDgraph.mpl" ), vis = TRUE ) ``` To see the performance of the BDMCMC algorithm we could plot the ROC curve as follows ```{r fig.align = 'center'} plotroc( list( bdgraph.obj, bdgraph.mpl.obj ), data.sim, cut = 200, labels = c( "BDgraph", "BDgraph.mpl" ), color = c( "blue", "red" ) ) ``` # Example 2: Gaussian Copula Graphical Models Here is a simple example to see the performance of the package for the mixed data using Gaussian copula graphical models. First, by using the function `bdgraph.sim()`, we simulate 300 observations (n = 300) from mixed data (`type = "mixed"`) with 10 variables (p = 10) and "random" graph structure, as follows ```{r fig.align = 'center'} set.seed( 2 ) data.sim = bdgraph.sim( n = 300, p = 10, type = "mixed", graph = "random", vis = TRUE ) ``` Since the generated data are mixed data, we are using run the `bdgraph()` function by choosing `method = "gcgm"`, as follows: ```{r} bdgraph.obj = bdgraph( data = data.sim, method = "gcgm", iter = 5000, verbose = FALSE ) ``` To compare the result with the true graph, we could run ```{r fig.align = 'center'} compare( bdgraph.obj, data.sim, main = c( "Target", "BDgraph" ), vis = TRUE ) ``` ```{r fig.align = 'center'} plotroc( bdgraph.obj, data.sim, labels = "BDgraph", color = "blue" ) ``` For more examples see [Mohammadi and Wit (2019)](https://www.jstatsoft.org/article/view/v089i03).
/scratch/gouwar.j/cran-all/cranData/BDgraph/vignettes/BDgraph-Examples.Rmd
--- title: "<center> Introduction to BDgraph <center>" author: "Reza Mohammadi (https://orcid.org/0000-0001-9538-0648)" date: "`r Sys.Date()`" output: rmarkdown::html_vignette: toc: true number_sections: true fig_caption: yes fig_width: 3.5 fig_height: 3.5 dpi: 72 dev.args: list( pointsize = 11 ) vignette: > %\VignetteIndexEntry{Introduction to BDgraph} %\VignetteEncoding{UTF-8} %\VignetteEngine{knitr::rmarkdown} editor_options: markdown: wrap: 72 --- ```{r opts, echo = FALSE, message = FALSE, warning = FALSE} knitr::opts_chunk $ set( collapse = TRUE, comment = " ", fig.width = 7, fig.height = 7, fig.align = "center" ) ``` This introduction to the `R` package **BDgraph** is a modified version of [Mohammadi and Wit (2019)](https://www.jstatsoft.org/article/view/v089i03), published in the Journal of Statistical Software. The `R` package **BDgraph** provides statistical tools for Bayesian structure learning for undirected graphical models with *continuous*, *count*, *binary*, and *mixed data*. The package is implemented the recent improvements in the Bayesian graphical models' literature, including [Mohammadi and Wit (2015)](https://projecteuclid.org/euclid.ba/1422468425), [Mohammadi et al. (2021)](https://doi.org/10.1080/01621459.2021.1996377), [Mohammadi et al. (2017)](https://rss.onlinelibrary.wiley.com/doi/full/10.1111/rssc.12171), [Dobra and Mohammadi (2018)](https://projecteuclid.org/euclid.aoas/1532743478), and [Vinciotti et al. (2022)](https://doi.org/10.48550/arXiv.2203.10118). Besides, the package contains several functions for simulation and visualization, as well as several multivariate datasets taken from the literature. # User interface In the `R` environment, one can access and load the **BDgraph** package by using the following commands: Install **BDgraph** using ```{r eval = FALSE} install.packages( "BDgraph" ) library( BDgraph ) ``` To speed up computations, we efficiently implement the **BDgraph** package by linking the `C++` code to `R`. The computationally extensive tasks of the package are implemented in parallel in `C++` using **OpenMP**. For the `C++` code, we use the highly optimized LAPACK and BLAS, as linear algebra libraries on systems that provide them. The use of these libraries significantly improves program speed. We design the **BDgraph** package to provide a Bayesian framework for undirected graph estimation of different types of datasets such as continuous, discrete or mixed data. The package facilitates a pipeline for analysis by four functional modules as follows ```{r pressure, echo = FALSE, out.width = '85%'} knitr::include_graphics( "Figure_1.png" ) ``` **Module 1. Data simulation:** Function `bdgraph.sim()` simulates multivariate Gaussian, discrete, binary, and mixed data with different undirected graph structures, including *"random"*, *"cluster"*, *"scale-free"*, *"lattice"*, *"hub"*, *"star"*, *"circle"*, *"AR(1)"*, *"AR(2)"*, and *"fixed"* graphs. Users can determine the sparsity of the graph structure and can generate mixed data, including *"count"*, *"ordinal"*, *"binary"*, *"Gaussian"*, and *"non-Gaussian"* variables. **Module 2. Methods:** The function `bdgraph()`, `bdgraph.mpl()`, and `bdgraph.dw()` provide several estimation methods regarding to the type of data: * Bayesian graph estimation for the multivariate data that follow the Gaussianity assumption, based on the Gaussian graphical models (GGMs); see [Mohammadi and Wit (2015)](https://projecteuclid.org/euclid.ba/1422468425). * Bayesian graph estimation for multivariate non-Gaussian, discrete, and mixed data, based on Gaussian copula graphical models (GCGMs); see [Mohammadi et al. (2017)](https://rss.onlinelibrary.wiley.com/doi/full/10.1111/rssc.12171) and [Vinciotti et al. (2022)](https://doi.org/10.48550/arXiv.2203.10118). * Bayesian graph estimation for multivariate discrete and binary data, based on discrete graphical models (DGMs); see [Dobra and Mohammadi (2018)](https://projecteuclid.org/euclid.aoas/1532743478). **Module 3. Algorithms:** The function `bdgraph()` and `bdgraph.mpl()` provide several sampling algorithms: * Birth-death MCMC (BDMCMC) sampling algorithms described in [Mohammadi et al. (2021)](https://doi.org/10.1080/01621459.2021.1996377) and [Mohammadi and Wit (2015)](https://projecteuclid.org/euclid.ba/1422468425). * Reversible jump MCMC (RJMCMC) sampling algorithms described in [Dobra et al. (2011)](https://doi.org/10.1198/jasa.2011.tm10465). * Hill-climbing (HC) search algorithm described in [Pensar et al. (2017)](https://doi.org/10.1214/16-ba1032). **Module 4. Results:** Includes four types of functions: * *Graph selection*: The functions `select()`, `plinks()`, and `pgraph()` provide the selected graph, the posterior link inclusion probabilities and the posterior probability of each graph, respectively. * *Convergence check*: The functions `plotcoda()` and `traceplot()` provide several visualization plots to monitor the convergence of the sampling algorithms. * *Comparison and goodness-of-fit*: The functions `compare()` and `plotroc()` provide several comparison measures and an ROC plot for model comparison. * *Visualization*: The plotting functions `plot.bdgraph()` and `plot.sim()` provide visualizations of the simulated data and estimated graphs. # The BDgraph environment The **BDgraph** package provides a set of comprehensive tools related to Bayesian graphical models; we describe below the essential functions available in the package. ## Posterior sampling We design the function `bdgraph()`, as the main function of the package, to take samples from the posterior distributions based on both of our Bayesian frameworks (GGMs and GCGMs). By default, the `bdgraph()` function is based on underlying sampling algorithm defined in [Mohammadi et al. (2021)](https://doi.org/10.1080/01621459.2021.1996377). Moreover, as an alternative to those BDMCMC sampling algorithms, we implement RJMCMC sampling algorithms for both the Gaussian and non-Gaussian frameworks. By using the following function ```{r eval = FALSE} bdgraph( data, n = NULL, method = "ggm", algorithm = "bdmcmc", iter = 5000, burnin = iter / 2, not.cont = NULL, g.prior = 0.5, df.prior = 3, g.start = "empty", jump = NULL, save = FALSE, cores = NULL, threshold = 1e-8, verbose = TRUE ) ``` we obtain a sample from our target joint posterior distribution. `bdgraph()` returns an object of `S3` class type *bdgraph*. The functions `plot()`, `print()`, and `summary()` are working with the object *bdgraph*. The input `data` can be an ($n \times p$) *matrix* or a *data.frame* or a covariance ($p \times p$) matrix ($n$ is the sample size and $p$ is the dimension); it can also be an object of class *sim*, which is the output of function `bdgraph.sim()`. The argument `method` determines the type of methods, GGMs, GCGMs. Option *"ggm"* is based on Gaussian graphical models that is designed for multivariate Gaussian data. Option *"gcgm"* is based on the GCGMs that is designed for non-Gaussian data such as, non-Gaussian continuous, discrete or mixed data. The argument `algorithm` refers the type of sampling algorithms which could be based on BDMCMC or RJMCMC. Option *"bdmcmc"* (as default) is for the BDMCMC sampling algorithms. Option *"rjmcmc"* is for the RJMCMC sampling algorithms, which are alternative algorithms. See [Mohammadi and Wit (2015)](https://projecteuclid.org/euclid.ba/1422468425). The argument `g.start` specifies the initial graph for our sampling algorithm. It could be *"empty"* (default) or *"full"*. Option *"empty"* means the initial graph is an empty graph and *"full"* means a full graph. It also could be an object with `S3` class \code{"bdgraph"}, which allows users to run the sampling algorithm from the last objects of the previous run. The argument `jump` determines the number of links that are simultaneously updated in the BDMCMC algorithm. For parallel computation in `C++` which is based on **OpenMP**, user can use argument `cores` which specifies the number of cores to use for parallel execution. Note, the package **BDgraph** has two other sampling functions, `bdgraph.mpl()` and `bdgraph.dwl()` which are designed in the similar framework as the function `bdgraph()`. The function `bdgraph.mpl()` is for Bayesian model determination in undirected graphical models based on marginal pseudo-likelihood, for both continuous and discrete variables; For more details see \cite{dobra2018}. The function `bdgraph.dwl()` is for Bayesian model determination for count data; See [Vinciotti et al. (2022)](https://doi.org/10.48550/arXiv.2203.10118). ## Posterior graph selection We design the **BDgraph** package in such a way that posterior graph selection can be done based on both Bayesian model averaging (BMA), as default, and maximum a posterior probability (MAP). The functions `select()` and `plinks()` are designed for the objects of class *bdgraph* to provide BMA and MAP estimations for posterior graph selection. The function ```{r eval = FALSE} plinks( bdgraph.obj, round = 2, burnin = NULL ) ``` provides estimated posterior link inclusion probabilities for all possible links, which is based on BMA estimation. In cases where the sampling algorithm is based on BDMCMC, these probabilities for all possible links $e=(i,j)$ in the graph can be estimated using a Rao-Blackwellized estimate based on \begin{eqnarray} \label{posterior-link} Pr( e \in E | data )= \frac{\sum_{t=1}^{N}{1(e \in E^{(t)}) W(K^{(t)}) }}{\sum_{t=1}^{N}{W(K^{(t)})}}, \end{eqnarray} where $N$ is the number of iteration and $W(K^{(t)})$ are the weights of the graph $G^{(t)}$ with the precision matrix $K^{(t)}$. The function ```{r eval = FALSE} select( bdgraph.obj, cut = NULL, vis = FALSE ) ``` provides the inferred graph based on both BMA (as default) and MAP estimators. The inferred graph based on BMA estimation is a graph with links for which the estimated posterior probabilities are greater than a certain cut-point (as default `cut=0.5`). The inferred graph based on MAP estimation is a graph with the highest posterior probability. Note, for posterior graph selection based on MAP estimation we should save all adjacency matrices by using the option `save = TRUE` in the function `bdgraph()`. Saving all the adjacency matrices could, however, cause memory problems. ## Convergence check In general, convergence in MCMC approaches can be difficult to evaluate. From a theoretical point of view, the sampling distribution will converge to the target joint posterior distribution as the number of iteration increases to infinity. Because we normally have little theoretical insight about how quickly MCMC algorithms converge to the target stationary distribution we therefore rely on post hoc testing of the sampled output. In general, the sample is divided into two parts: a ``burn-in'' part of the sample and the remainder, in which the chain is considered to have converged sufficiently close to the target posterior distribution. Two questions then arise: How many samples are sufficient? How long should the burn-in period be? The `plotcoda()` and `traceplot()` are two visualization functions for the objects of class *bdgraph* that make it possible to check the convergence of the search algorithms in **BDgraph**. The function ```{r eval = FALSE} plotcoda( bdgraph.obj, thin = NULL, control = TRUE, main = NULL, verbose = TRUE, ... ) ``` provides the trace of estimated posterior probability of all possible links to check convergence of the search algorithms. Option \code{control} is designed for the case where if `control=TRUE` (as default) and the dimension ($p$) is greater than $15$, then $100$ links are randomly selected for visualization. The function ```{r eval = FALSE} traceplot( bdgraph.obj, acf = FALSE, pacf = FALSE, main = NULL, ... ) ``` provides the trace of graph size to check convergence of the search algorithms. Option `acf` is for visualization of the autocorrelation functions for graph size; option `pacf` visualizes the partial autocorrelations. ## Comparison and goodness-of-fit The functions `compare()` and `plotroc()` are designed to evaluate and compare the performance of the selected graph. These functions are particularly useful for simulation studies. With the function ```{r eval = FALSE} compare( pred, actual, main = NULL, vis = FALSE ) ``` we can evaluate the performance of the Bayesian methods available in our **BDgraph** package and compare them with alternative approaches. This function provides several measures such as the balanced $F$-score measure, which is defined as follows: \begin{eqnarray} \label{f1} F_1\mbox{-score} = \frac{2 \mbox{TP}}{2 \mbox{TP + FP + FN}}, \end{eqnarray} where TP, FP and FN are the number of true positives, false positives and false negatives, respectively. The $F_1$-score lies between $0$ and $1$, where $1$ stands for perfect identification and $0$ for no true positives. The function ```{r eval = FALSE} plotroc = function( pred, actual, cut = 20, smooth = FALSE, ... ) ``` provides a ROC plot for visualization comparison based on the estimated posterior link inclusion probabilities. See also function `roc()` for a ROC curve specifically for graph structure learning. ## Data simulation The function `bdgraph.sim()` is designed to simulate different types of datasets with various graph structures. The function ```{r eval = FALSE} bdgraph.sim( p = 10, graph = "random", n = 0, type = "Gaussian", prob = 0.2, size = NULL, mean = 0, class = NULL, cut = 4, b = 3, D = diag( p ), K = NULL, sigma = NULL, q = exp(-1), beta = 1, vis = FALSE, rewire = 0.05, range.mu = c( 3, 5 ), range.dispersion = c( 0.01, 0.1 ) ) ``` can simulate multivariate Gaussian, non-Gaussian, discrete, binary and mixed data with different undirected graph structures, including *"random"*, *"cluster"*, *"scale-free"*, *"lattice"*, *"hub"*, *"star"*, *"circle"*, *"AR(1)"*, *"AR(2)"*, and *"fixed"* graphs. Users can specify the type of multivariate data by option `type` and the graph structure by option `graph`. They can determine the sparsity level of the obtained graph by using option `prob`. With this function users can generate mixed data from *"count"*, *"ordinal"*, *"binary"*, *"Gaussian"* and *"non-Gaussian"* distributions. `bdgraph.sim()` returns an object of the `S3` class type "sim". Functions `plot()` and `print()` work with this object type. There is another function in the **BDgraph** package with the name `graph.sim()` which is designed to simulate different types of graph structures. The function ```{r eval = FALSE} graph.sim( p = 10, graph = "random", prob = 0.2, size = NULL, class = NULL, vis = FALSE, rewire = 0.05 ) ``` can simulate different undirected graph structures, including *"random"*, *"cluster"*, *"scale-free"*, *"lattice"*, *"hub"*, *"star"*, and *"circle"* graphs. Users can specify the type of graph structure by option `graph`. They can determine the sparsity level of the obtained graph by using option `prob`. `bdgraph.sim()` returns an object of the `S3` class type "graph". Functions `plot()` and `print()` work with this object type. # An example on simulated data We illustrate the user interface of the **BDgraph** package by use of a simple simulation. By using the function `bdgraph.sim()` we simulate $60$ observations ($n=60$) from a multivariate Gaussian distribution with $8$ variables ($p=8$) and ``scale-free'' graph structure, as below. ```{r} library( BDgraph ) set.seed( 5 ) data.sim <- bdgraph.sim( n = 60, p = 8, graph = "scale-free", type = "Gaussian" ) round( head( data.sim $ data, 4 ), 2 ) ``` Since the generated data are Gaussian, we run the BDMCMC algorithm which is based on Gaussian graphical models. For this we choose `method = "ggm"`, as follows: ```{r eval = TRUE} sample.bdmcmc <- bdgraph( data = data.sim, method = "ggm", algorithm = "bdmcmc", iter = 5000, save = TRUE, verbose = FALSE ) ``` We choose option `save = TRUE` to save the samples in order to check convergence of the algorithm. Running this function takes less than one second, as the computational intensive tasks are performed in `C++` and interfaced with `R`. Since the function `bdgraph()` returns an object of class `S3`, users can see the summary result as follows ```{r} summary( sample.bdmcmc ) ``` The summary results are the adjacency matrix of the selected graph (`selected_g`) based on BMA estimation, the estimated posterior probabilities of all possible links (`p_links`) and the estimated precision matrix (`K_hat`). In addition, the function `summary()` reports a visualization summary of the results as we can see above. At the top-left is the graph with the highest posterior probability. The plot at the top-right gives the estimated posterior probabilities of all the graphs which are visited by the BDMCMC algorithm; it indicates that our algorithm visits more than $2000$ different graphs. The plot at the bottom-left gives the estimated posterior probabilities of the size of the graphs; it indicates that our algorithm visited mainly graphs with sizes between $4$ and $18$ links. At the bottom-right is the trace of our algorithm based on the size of the graphs. The function `compare()` provides several measures to evaluate the performance of our algorithms and compare them with alternative approaches with respect to the true graph structure. To evaluate the performance of the BDMCMC algorithm and compare it with that of an alternative algorithm, we also run the RJMCMC algorithm under the same conditions as below. ```{r} sample.rjmcmc <- bdgraph( data = data.sim, method = "ggm", algorithm = "rjmcmc", iter = 5000, save = TRUE, verbose = FALSE ) ``` where the sampling algorithm from the joint posterior distribution is based on the RJMCMC algorithm. Users can compare the performance of these two algorithms by using the code ```{r eval = FALSE} plotroc( list( sample.bdmcmc, sample.rjmcmc ), data.sim, smooth = TRUE, labels = c( "BDMCMC", "RJMCMC" ), color = c( "blue", "red" ) ) ``` which visualizes an ROC plot for both algorithms, BDMCMC and RJMCMC. We can also compare the performance of those algorithms by using the `compare()` function as follows: ```{r} compare( list( sample.bdmcmc, sample.rjmcmc ), data.sim, main = c( "True graph", "BDMCMC", "RJMCMC" ), vis = TRUE ) ``` The results show that for this specific simulated example both algorithms have more or less the same performance; See [Mohammadi et al. (2021)](https://doi.org/10.1080/01621459.2021.1996377) for a comprehensive simulation study. In this simulation example, we run both BDMCMC and RJMCMC algorithms for $5,000$ iterations, $2,500$ of them as burn-in. To check whether the number of iterations is enough and to monitoring the convergence of our both algorithm, we run ```{r} plotcoda( sample.bdmcmc, verbose = FALSE ) plotcoda( sample.rjmcmc, verbose = FALSE ) ``` The results indicate that the BDMCMC algorithm converges faster with compare with RJMCMC algorithm. # References Mohammadi, R. and Wit, E. C. (2019). **BDgraph**: An *R* Package for Bayesian Structure Learning in Graphical Models, *Journal of Statistical Software*, 89(3):1-30, [doi:10.18637/jss.v089.i03](https://www.jstatsoft.org/article/view/v089i03). Mohammadi, A. and Wit, E. C. (2015). Bayesian Structure Learning in Sparse Gaussian Graphical Models, *Bayesian Analysis*, 10(1):109-138, [doi:10.1214/14-BA889](https://projecteuclid.org/euclid.ba/1422468425). Mohammadi, R., Massam, H. and Letac, G. (2021). Accelerating Bayesian Structure Learning in Sparse Gaussian Graphical Models, *Journal of the American Statistical Association*, [doi:10.1080/01621459.2021.1996377](https://doi.org/10.1080/01621459.2021.1996377) Mohammadi, A., et al (2017). Bayesian modelling of Dupuytren disease by using Gaussian copula graphical models, *Journal of the Royal Statistical Society: Series C*, 66(3):629-645, [doi:10.1111/rssc.12171](https://rss.onlinelibrary.wiley.com/doi/full/10.1111/rssc.12171) Dobra, A. and Mohammadi, R. (2018). Loglinear Model Selection and Human Mobility, *Annals of Applied Statistics*, 12(2):815-845, [doi:10.1214/18-AOAS1164](https://projecteuclid.org/euclid.aoas/1532743478) Vinciotti, V., Behrouzi, P., and Mohammadi, R. (2022) Bayesian structural learning of microbiota systems from count metagenomic data, *arXiv preprint*, [doi:10.48550/arXiv.2203.10118](https://doi.org/10.48550/arXiv.2203.10118) Dobra, A. and Lenkoski, A. (2011). Copula Gaussian graphical models and their application to modeling functional disability data, *The Annals of Applied Statistics*, 5(2A):969-93 Dobra, A., et al. (2011). Bayesian inference for general Gaussian graphical models with application to multivariate lattice data. *Journal of the American Statistical Association*, 106(496):1418-33, [doi:10.1198/jasa.2011.tm10465](https://doi.org/10.1198/jasa.2011.tm10465) Mohammadi, A. and Dobra, A. (2017). The `R` Package **BDgraph** for Bayesian Structure Learning in Graphical Models, *ISBA Bulletin*, 24(4):11-16 Lenkoski, A. (2013). A direct sampler for G-Wishart variates, *Stat*, 2(1):119-28, [doi:10.1002/sta4.23](https://doi.org/10.1002/sta4.23) Pensar, J. et al (2017) Marginal pseudo-likelihood learning of discrete Markov network structures, *Bayesian Analysis*, 12(4):1195-215, [doi:10.1214/16-BA1032](https://doi.org/10.1214/16-ba1032).
/scratch/gouwar.j/cran-all/cranData/BDgraph/vignettes/Introduction-BDgraph.Rmd
assert = function(bedata) { Si11 = bedata[bedata$GRP=="RT" & bedata$PRD==1, "SUBJ"] Si21 = bedata[bedata$GRP=="RT" & bedata$PRD==2, "SUBJ"] Si12 = bedata[bedata$GRP=="TR" & bedata$PRD==1, "SUBJ"] Si22 = bedata[bedata$GRP=="TR" & bedata$PRD==2, "SUBJ"] nameCheck = setdiff(c("GRP", "SUBJ", "PRD", "TRT"), colnames(bedata)) if (length(nameCheck) > 0) stop("GRP, SUBJ, PRD, TRT columns should exist!") return(identical(Si11, Si21) & identical(Si12, Si22)) } TrimData = function(bedata) { bedata$GRP = trimws(bedata$GRP) bedata$SUBJ = trimws(bedata$SUBJ) bedata$PRD = trimws(bedata$PRD) bedata$TRT = trimws(bedata$TRT) return(bedata) } drawind = function(g1l, g1r, g2l, g2r, g1s, g2s) { for (i in 1:length(g1l)) { x = jitter(c(1, 2), factor=0.3) y = c(g1l[i], g1r[i]) lines(x, y, type="l", lty=1, col="red") text(x[1]-0.05, y[1], paste(g1s[i]), cex=0.6, col="red") } for (i in 1:length(g2l)) { x = jitter(c(1, 2), factor=0.3) y = c(g2l[i], g2r[i]) lines(x, y, type="l", lty=2, col="blue") text(x[2]+0.05, y[2], paste(g2s[i]), cex=0.6, col="blue") } } drawmeansd = function(ma, sa, mb, sb, mc, sc, md, sd, y.max) { sft = 0.03 delta = mean(ma, mc) - mean(mb, md) y.RT = mean(ma, mc) + sign(delta) * y.max * 0.05 y.TR = mean(mb, md) - sign(delta) * y.max * 0.05 lines(c(1-sft, 2-sft), c(ma, mc), type="l", lty=1, col="red") text(1.5-sft, y.RT, "RT", col="red") if (sa > 0) arrows(1-sft, ma-sa, 1-sft, ma+sa, length=0.1, code=3, angle=90, col="red") if (sc > 0) arrows(2-sft, mc-sc, 2-sft, mc+sc, length=0.1, code=3, angle=90, col="red") lines(c(1+sft, 2+sft), c(mb, md), type="l", lty=2, col="blue") text(1.5+sft, y.TR, "TR", col="blue") if (sb > 0) arrows(1+sft, mb-sb, 1+sft, mb+sd, length=0.1, code=3, angle=90, col="blue") if (sd > 0) arrows(2+sft, md-sd, 2+sft, md+sd, length=0.1, code=3, angle=90, col="blue") }
/scratch/gouwar.j/cran-all/cranData/BE/R/BasicUtil.R
be2x2 = function(Data, Columns = c("AUClast", "Cmax", "Tmax"), rtfName="") { # oLocale = Sys.setlocale(category="LC_ALL","English.utf8") # on.exit(Sys.setlocale(category="LC_ALL", oLocale)) if ("data.frame" %in% class(Data)) { bedata = Data } else if ("character" %in% class(Data)) { bedata = read.csv(Data) } else { stop("Data should be data.frame or file name!") } bedata = bedata[order(bedata$GRP, bedata$PRD, bedata$SUBJ),]; if(!assert(bedata)) { cat("\n Subject count should be balanced!\n"); return(NULL); } bedata = TrimData(bedata) nCol = length(Columns) if (nCol == 0) stop("Input Error. Please, check the arguments!") if (rtfName != "") { rtf = RTF(rtfName) addHeader(rtf, title="Bioequivalence Test Result") addNewLine(rtf) addHeader(rtf, "Table of Contents") addTOC(rtf) } Result = vector() for (i in 1:nCol) { plot2x2(bedata, Columns[i]) if (toupper(Columns[i]) != "TMAX"){ cResult = test2x2(bedata, Columns[i]) } else { cResult = hodges(bedata, Columns[i]) } if (rtfName != "") { addPageBreak(rtf) addHeader(rtf, title=Columns[i], TOC.level=1) LineResult = capture.output(print(cResult)) for (j in 1:length(LineResult)) addParagraph(rtf, LineResult[j]) addPageBreak(rtf) addPlot(rtf, plot.fun=plot2x2a, width=6.5, height=6.5, res=300, bedata=bedata, Var=Columns[i]) addPageBreak(rtf) addPlot(rtf, plot.fun=plot2x2b, width=6.5, height=6.5, res=300, bedata=bedata, Var=Columns[i]) } Result = c(Result, list(cResult)) } if (rtfName != "") { addPageBreak(rtf) addSessionInfo(rtf) done(rtf) fRTF = readLines(rtfName) iL = grep("Signif. codes: 0", fRTF) fRTF[iL] = "Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1\\par}" writeLines(fRTF, rtfName) } names(Result) = Columns return(Result) }
/scratch/gouwar.j/cran-all/cranData/BE/R/be2x2.R
ci2cv = function(n1, n2, LL, UL, Alpha=0.1) { mse = ci2mse(n1, n2, LL, UL, Alpha) return(mse2cv(mse)) }
/scratch/gouwar.j/cran-all/cranData/BE/R/ci2cv.R
ci2mse = function(n1, n2, LL, UL, Alpha=0.1) { pe = exp((log(UL) + log(LL))/2) t0 = qt(1 - Alpha/2, n1 + n2 - 2) SD = (log(UL) - log(LL))/(2*t0) mse = 2*SD^2/(1/n1 + 1/n2) return(mse) }
/scratch/gouwar.j/cran-all/cranData/BE/R/ci2mse.R
cv2mse = function(cv) { cv = cv/100 return(log(cv*cv + 1)) }
/scratch/gouwar.j/cran-all/cranData/BE/R/cv2mse.R
hodges = function(bedata, Var) { if(!assert(bedata)) { cat("\n Subject count should be balanced!\n"); return(NULL); } Yi11 = bedata[bedata$GRP=="RT" & bedata$PRD==1, Var] Yi21 = bedata[bedata$GRP=="RT" & bedata$PRD==2, Var] Yi12 = bedata[bedata$GRP=="TR" & bedata$PRD==1, Var] Yi22 = bedata[bedata$GRP=="TR" & bedata$PRD==2, Var] n1 = length(Yi11) n2 = length(Yi12) if(n1 * n2 < 12) { cat("\n Too Small Sample Size for 90% Confidence Interval !\n"); return(NULL); } mu.r = (mean(Yi11) + mean(Yi22)) / 2; G1D = (Yi21 - Yi11) / 2 G2D = (Yi22 - Yi12) / 2 D = sort(outer(G1D, G2D, "-")); pval = pwilcox(min(length(D[D>0]), length(D[D<0])), n1, n2) w05 = qwilcox(0.05, n1, n2) w95 = qwilcox(0.95, n1, n2) names(pval) = list(c("p-value")); est1 = cbind(D[w05 - 1], median(D), D[w95]) est2 = (1 + est1 / mu.r ) * 100 est.a = rbind(est1, est2) dimnames(est.a) = list(c("90% Confidence Interval", "90% Confidence Interval(%)"), c("Lower Limit", "Point Estimate", "Upper Limit")); result = list(pval, est.a); names(result) = c("Wilcoxon Signed-Rank Test", "Hodges-Lehmann Estimate") return(result); }
/scratch/gouwar.j/cran-all/cranData/BE/R/hodges.R
mse2cv = function(mse) { cv = sqrt(exp(mse) - 1) return(100*cv) }
/scratch/gouwar.j/cran-all/cranData/BE/R/mse2cv.R
plot2x2 = function(bedata, Var) { dev.new() plot2x2a(bedata, Var) dev.new() plot2x2b(bedata, Var) }
/scratch/gouwar.j/cran-all/cranData/BE/R/plot2x2.R
plot2x2a = function(bedata, Var) { if(!assert(bedata)) { cat("\n Subject count should be balanced!\n"); return(NULL); } Si11 = bedata[bedata$GRP=="RT" & bedata$PRD==1, "SUBJ"] Si21 = bedata[bedata$GRP=="RT" & bedata$PRD==2, "SUBJ"] Si12 = bedata[bedata$GRP=="TR" & bedata$PRD==1, "SUBJ"] Si22 = bedata[bedata$GRP=="TR" & bedata$PRD==2, "SUBJ"] Yi11 = bedata[bedata$GRP=="RT" & bedata$PRD==1, Var] Yi21 = bedata[bedata$GRP=="RT" & bedata$PRD==2, Var] Yi12 = bedata[bedata$GRP=="TR" & bedata$PRD==1, Var] Yi22 = bedata[bedata$GRP=="TR" & bedata$PRD==2, Var] n1 = length(Yi11) n2 = length(Yi12) Y.11 = mean(Yi11) Y.21 = mean(Yi21) Y.12 = mean(Yi12) Y.22 = mean(Yi22) sY.11 = sd(Yi11) sY.21 = sd(Yi21) sY.12 = sd(Yi12) sY.22 = sd(Yi22) y.max = max(Y.11 + sY.11, Y.21 + sY.21, Y.12 + sY.12, Y.22 + sY.22, max(bedata[,Var])) * 1.2 par(oma=c(1,1,3,1), mfrow=c(2,2)) plot(0, 0, type="n", ylim=c(0, y.max), xlim=c(0.5, 2.5), axes=FALSE, xlab="Period", ylab=Var, main="(a) Individual Plot for Period") axis(2) axis(1, at=c(1,2)) drawind(Yi11, Yi21, Yi12, Yi22, Si11, Si12) plot(0, 0, type="n", ylim=c(0, y.max), xlim=c(0.5, 2.5), axes=FALSE, xlab="Treatment", ylab=Var, main="(b) Individual Plot for Treatment") axis(2) axis(1, at=c(1,2), labels=c("Test", "Reference")) drawind(Yi21, Yi11, Yi12, Yi22, Si11, Si12) plot(0, 0, type="n", ylim=c(0, y.max), xlim=c(0.5, 2.5), axes=FALSE, xlab="Period", ylab=Var, main="(c) Mean and SD by Period") axis(2) axis(1, at=c(1,2)) drawmeansd(Y.11, sY.11, Y.12, sY.12, Y.21, sY.21, Y.22, sY.22, y.max) plot(0, 0, type="n", ylim=c(0, y.max), xlim=c(0.5, 2.5), axes=FALSE, xlab="Treatment", ylab=Var, main="(d) Mean and SD by Treatment") axis(2) axis(1, at=c(1,2), labels=c("Test", "Reference")) drawmeansd(Y.21, sY.21, Y.12, sY.12, Y.11, sY.11, Y.22, sY.22, y.max) mtext(outer=T, side=3, paste("Equivalence Plots for", Var), cex=1.5) }
/scratch/gouwar.j/cran-all/cranData/BE/R/plot2x2a.R
plot2x2b = function(bedata, Var) { if(!assert(bedata)) { cat("\n Subject count should be balanced!\n"); return(NULL); } Yi11 = bedata[bedata$GRP=="RT" & bedata$PRD==1, Var] Yi21 = bedata[bedata$GRP=="RT" & bedata$PRD==2, Var] Yi12 = bedata[bedata$GRP=="TR" & bedata$PRD==1, Var] Yi22 = bedata[bedata$GRP=="TR" & bedata$PRD==2, Var] par(oma=c(1,1,3,1), mfrow=c(2,2)) boxplot(Yi11, Yi21, Yi12, Yi22, names=c("SEQ=RT\nPRD=1", "SEQ=RT\nPRD=2", "SEQ=TR\nPRD=1", "SEQ=TR\nPRD=2"), cex.axis=0.85, main="(a) By Sequence and Period") boxplot(c(Yi11, Yi21), c(Yi12, Yi22), names=c("Sequence=RT", "Sequence=TR"), main="(b) By Sequence") boxplot(c(Yi11, Yi12), c(Yi21, Yi22), names=c("Period=1", "Period=2"), main="(c) By Period") boxplot(c(Yi12, Yi21), c(Yi11, Yi22), names=c("Treatment=T", "Treatment=R"), main="(d) By Treatment") mtext(outer=TRUE, side=3, paste("Box Plots for", Var), cex=1.5) }
/scratch/gouwar.j/cran-all/cranData/BE/R/plot2x2b.R
pow2x2ci = function(n1, n2, LL, UL, Alpha=0.1) { mse = ci2mse(n1, n2, LL, UL, Alpha) Power = pow2x2mse(n1, n2, mse) return(Power) }
/scratch/gouwar.j/cran-all/cranData/BE/R/pow2x2ci.R
pow2x2mse = function(n1, n2, mse, True.R=1, Alpha=0.1, ThetaL=0.8, ThetaU=1.25) { # n1, n2: sample size for each group # if (True.R <= ThetaL | True.R >= ThetaU) return(0) t0 = qt(1 - Alpha/2, n1 + n2 - 2) p1 = pt(-1*t0, n1 + n2 - 2, ncp = log(ThetaL/True.R) / sqrt(mse/2*(1/n1 + 1/n2)) ) # 1st beta error: LL > 0.8 = 1 - p1 p2 = pt(t0, n1 + n2 - 2, ncp = log(ThetaU/True.R) / sqrt(mse/2*(1/n1 + 1/n2)) ) # 2nd beta error: UL < 1.25 = p2 Power = p1 - p2 # 1 - (1 - p1 + p2) = 1 - both beta errors if (Power < 0) Power = 0 return(Power) }
/scratch/gouwar.j/cran-all/cranData/BE/R/pow2x2mse.R
powcv = function(n, CV, DesignNo=1, True.R=1, Alpha=0.1, ThetaL=0.8, ThetaU=1.25) { mse = log(1 + (CV/100)^2) return(powmse(n, mse, DesignNo, True.R, Alpha, ThetaL, ThetaU)) }
/scratch/gouwar.j/cran-all/cranData/BE/R/powcv.R
powmse = function(n, mse, DesignNo=1, True.R=1, Alpha=0.1, ThetaL=0.8, ThetaU=1.25) { # if (True.R <= ThetaL | True.R >= ThetaU) return(0) aNu0 = c(2, 4, 4, 6, 12, 12, 12, 12, 12) aNu1 = c(2, 3, 4, 5, 5, 6, 4, 9, 6) aBx = c(1, 2, 3/4, 11/20, 1/4, 5/12, 1/3, 11/20, 1/2) nu = aNu0[DesignNo]*n - aNu1[DesignNo] bx = sqrt(mse*aBx[DesignNo]/n) t0 = qt(1 - Alpha/2, nu) p1 = pt(-t0, nu, ncp = log(ThetaL/True.R)/bx) # 1st beta error: LL > 0.8 = 1 - p1 p2 = pt(t0, nu, ncp = log(ThetaU/True.R)/bx) # 2nd beta error: UL < 1.25 = p2 Power = p1 - p1*p2 # = 1 - (1 - p1 + p2 - (1 - p1)*p2) = 1 - both beta errors if (Power < 0) Power = 0 return(Power) }
/scratch/gouwar.j/cran-all/cranData/BE/R/powmse.R
scaledBound = function(CV = 40, k = 0.76, digits = 4) { if (CV < 30) return(c(0.8, 1.25)) if (CV > 50) CV = 50 # SD0 = sqrt(log(1 + (30/100)^2)) # SD0 = 0.2935604 # k = log(1.25)/SD0 # format(k, digits=22) = 0.76012829768047396 # When CV=30%, bound becomes 0.8 - 1.25 SD0 = sqrt(log(1 + (CV/100)^2)) return(round(exp(c(-k, k)*SD0), digits)) }
/scratch/gouwar.j/cran-all/cranData/BE/R/scaledBound.R
ss2x2ci = function(n1, n2, LL, UL, Alpha=0.1) { pe = exp((log(UL) + log(LL))/2) mse = ci2mse(n1, n2, LL, UL, Alpha) s1 = ssmse(mse) s2 = ssmse(mse, True.R=pe) sampsize = cbind(s1, s2) p1 = round(100 * pow2x2mse(n1, n2, mse)) p2 = round(100 * pow2x2mse(n1, n2, mse, True.R=pe)) Power = cbind(p1, p2) result = rbind(sampsize, Power) dimnames(result) = list(c("80% Power Sample Size", paste("Power at n1 =", n1, ", n2 =", n2)), c("True Ratio=1", sprintf("True Ratio=%.4f", pe))) return(result) }
/scratch/gouwar.j/cran-all/cranData/BE/R/ss2x2ci.R
sscv = function(CV, DesignNo=1, True.R=1, Alpha=0.1, Beta=0.2, ThetaL=0.8, ThetaU=1.25, nMax=999999) { mse = log(1 + (CV/100)^2) return(ssmse(mse, DesignNo, True.R, Alpha, Beta, ThetaL, ThetaU, nMax)) }
/scratch/gouwar.j/cran-all/cranData/BE/R/sscv.R
ssmse = function(mse, DesignNo=1, True.R=1, Alpha=0.1, Beta=0.2, ThetaL=0.8, ThetaU=1.25, nMax=999999) { # if (True.R <= ThetaL | True.R >= ThetaU) return(Inf) for (i in 2:nMax) { Power = powmse(i, mse, DesignNo, True.R, Alpha, ThetaL, ThetaU) if (Power > 1 - Beta) { attr(i, "Power") = Power return(i) } } return(paste(">", nMax)) }
/scratch/gouwar.j/cran-all/cranData/BE/R/ssmse.R
ssscv = function(CV, DesignNo = 1, True.R = 1, Alpha = 0.1, Beta = 0.2, Region="EU", nMax = 999999) { Region = toupper(trimws(Region)) if (Region %in% c("US", "FDA")) { Bound = scaledBound(CV=CV, k=0.893, digits=22) } else if (Region %in% c("KR", "MFDS")) { Bound = scaledBound(CV=CV, k=0.76, digits=4) } else { Bound = scaledBound(CV=CV, k=0.76, digits=22) } mse = log(1 + (CV/100)^2) Res = ssmse(mse, DesignNo, True.R, Alpha, Beta, Bound[1], Bound[2], nMax) attr(Res, "Bound") = Bound return(Res) }
/scratch/gouwar.j/cran-all/cranData/BE/R/ssscv.R
test2x2 = function(bedata, Var) { if(!assert(bedata)) { cat("\n Subject count should be balanced!\n"); return(NULL); } bedata = TrimData(bedata) Yijk = log(bedata[, Var]) Yi11 = log(bedata[bedata$GRP=="RT" & bedata$PRD==1, Var]) Yi21 = log(bedata[bedata$GRP=="RT" & bedata$PRD==2, Var]) Yi12 = log(bedata[bedata$GRP=="TR" & bedata$PRD==1, Var]) Yi22 = log(bedata[bedata$GRP=="TR" & bedata$PRD==2, Var]) n1 = length(Yi11) n2 = length(Yi12) Y... = mean(Yijk) SStotal = sum((Yijk - Y...)^2) Y.11 = mean(Yi11) Y.21 = mean(Yi21) Y.12 = mean(Yi12) Y.22 = mean(Yi22) Yi.1 = (Yi11 + Yi21) / 2 Yi.2 = (Yi12 + Yi22) / 2 Y..1 = mean(Yi.1) Y..2 = mean(Yi.2) mu.r = (Y.11 + Y.22) / 2 mu.t = (Y.21 + Y.12) / 2 di1 = (Yi21 - Yi11) / 2 di2 = (Yi22 - Yi12) / 2 d.1 = mean(di1) d.2 = mean(di2) # Chat = Y.12 + Y.22 - Y.11 - Y.21 # Fhat = mu.t - mu.r # Phat = (Y.21 - Y.11 - Y.12 + Y.22)/2 SScarry = 2*n1*n2/(n1 + n2)*(Y.12 + Y.22 - Y.11 - Y.21)^2 / 4 SSinter = (sum((Yi.1 - Y..1)^2) + sum((Yi.2 - Y..2)^2)) * 2 SSbetween = SScarry + SSinter SSperiod = 2*n1*n2/(n1+n2)*(Y.21 + Y.22 - Y.11 - Y.12)^2 / 4 SSdrug = 2*n1*n2/(n1+n2)*(Y.21 + Y.12 - Y.11 - Y.22)^2 / 4 SSintra = 2*(sum((di1 - d.1)^2) + sum((di2 - d.2)^2)) # SSmodel = SStotal - SSintra Source = c("SUBJECT", "GROUP", "SUBJECT(GROUP)", "PERIOD", "DRUG", "ERROR", "TOTAL"); SS = c(SSbetween, SScarry, SSinter, SSperiod, SSdrug, SSintra, SStotal); DF = c(n1 + n2 - 1, 1, n1 + n2 - 2, 1, 1, n1 + n2 - 2, 2*n1 + 2*n2 - 1); MS = SS / DF mse = SSintra/(n1 + n2 - 2) Fv = MS / c(mse, MS[3], mse, mse, mse, mse, mse); p1 = 1 - pf(Fv[1], n1 + n2 - 1, n1 + n2 - 2) p2 = 1 - pf(Fv[2], 1, n1 + n2 - 2); p3 = 1 - pf(Fv[3], n1 + n2 - 2, n1 + n2 - 2); p4 = 1 - pf(Fv[4], 1, n1 + n2 - 2); p5 = 1 - pf(Fv[5], 1, n1 + n2 - 2); p = c(p1, p2, p3, p4, p5, NA, NA) Fv[6] = Fv[7] = MS[7] = NA ANOVA = cbind(SS, DF, MS, Fv, p) dimnames(ANOVA) = list(Source,c("Sum Sq", "Df", "Mean Sq", "F value", "Pr(>F)")) class(ANOVA) = "anova" pe = mu.t - mu.r se = sqrt(mse/2 * (1/n1 + 1/n2)) # See pp 62-63 of Chow & Liu t0 = qt(0.95, n1 + n2 - 2); ci0 = cbind(pe - t0 * se, pe, pe + t0 * se) sig2b = max(0, (MS[3] - MS[6])/2) sig2w = MS[6] cvs = cbind(sqrt(exp(sig2b) - 1), sqrt(exp(sig2w) - 1)) * 100 lsm = cbind(exp(mu.r), exp(mu.t)) dimnames(lsm) = list("Geometric Means", cbind("Reference Drug", "Test Drug")) ci = exp(ci0); dimnames(ci) = list("90% CI for Ratio", c("Lower Limit", "Point Estimate", "Upper Limit")); sampsize1 = ssmse(mse); sampsize2 = ssmse(mse, True.R=exp(pe)); ss = cbind(sampsize1, sampsize2) dimnames(ss) = list("80% Power Sample Size", c("True Ratio=1", "True Ratio=Point Estimate")); cvs = rbind(cbind(sig2b, sig2w), cvs) dimnames(cvs) = list(cbind("Variance Estimate", "Coefficient of Variation, CV(%)"), cbind("Between Subject", "Within Subject")) result = list(ANOVA, cvs, lsm, ci, ss); names(result) = c("Analysis of Variance (log scale)", "Between and Within Subject Variability", "Least Square Means (geometric mean)", "90% Confidence Interval of Geometric Mean Ratio (T/R)", "Sample Size") return(result); }
/scratch/gouwar.j/cran-all/cranData/BE/R/test2x2.R
runBEACH <- function(){ shiny::runApp(system.file('app', package='BEACH')) }
/scratch/gouwar.j/cran-all/cranData/BEACH/R/runBEACH.R
#***************************************************************************************************** #-- Function to produce table or plot to RTF file # #-- Author: Michael Man, Duytrac Nguyen, Danni Yu # #***************************************************************************************************** #----------------------------------------------------------------------------------------------- # ###--- These functions are used for produce a nice RTF file # #----------------------------------------------------------------------------------------------- if(!exists('muliHead.split')){ muliHead.split <<- ";" } if (TRUE) { #--- produce to rtf file that as SAS output. It can be used for single table or table with multiple pages rtf.table.out <- function( rtf, # RTF object that is just needed to be declared once before calling the function tb, # table out cell1=2, cell2=1, nheader=1, nline.body=40, #number of lines per page height=8.5, width=11, omi=c(1,1,1,1), cw=NULL, #column width colFormat=c(rep("L", 1), rep("C",3)), #alignment (left, center, or right) for each column varName=NULL, #variable name that want to be repeated when go to the next page var.ul="", #key string in table defining the bottom line on each page. # titles="", # footns="", # prd.status='QA', header=FALSE, footer=FALSE, addSpaceHeader=0, #expand the width of header or footnotes addSpaceFoot=0, #expand the width of header or footnotes page.disp=FALSE, #whether diplay page number # Done=TRUE, ... ){ # rtf: RTF object that is just needed to be declared once before calling the function # tb: table out # cw: column width # colFormat: alignment (left, center, or right) for each column # varName: variable name that want to be repeated when go to the next page # nline.body: number of lines per page # addSpaceFoot, addSpaceHeader: expand the width of header or footnotes # page.disp: whether diplay page number #--- generate blank pape (break page) if the data is more than a page if(nrow(tb) > nline.body) { idx <- seq(1, nrow(tb), by = nline.body) idx.n <- c(seq(nline.body, nrow(tb), by = nline.body), nrow(tb)) }else { idx <- 1 idx.n <- nrow(tb) } npage <- length(idx) for(k in 1:length(idx)) { if(idx[k]==idx.n[k]) subTable <- tb else subTable <- tb[idx[k]:idx.n[k], ] #--- if nrow < nline.body, need adding some spaces to move footnotes to bottom of the page if(nrow(subTable) < nline.body) { addData <- data.frame(matrix("",ncol=ncol(subTable), nrow=nline.body-nrow(subTable)-1)) colnames(addData) <- colnames(subTable) subTable <- rbind(subTable, addData) } #-- get values that will be in the 1st row of next page rownames(subTable) <- 1:nrow(subTable) #-- check if the last row of previous page with varName not matched the 1st row of next page if(k==1) string.val <- NULL if(k!=1 & !all(unique(subTable[1,varName]) %in% "") & !all(unique(subTable[1,varName]) %in% string.val)) string.val <- unique(subTable[1,varName]) if(k==1 & all(tb[min(nrow(tb), nrow(subTable)+1), varName] %in% "")) { for(m in 1:nrow(subTable)) if(all(!subTable[m,varName] %in% "")) string.val <- subTable[m, varName] } else if(!all(tb[min(nrow(tb),nrow(subTable)+1), varName] %in% "")) { string.val <- NULL } else { #-- add last row of previous page to 1st row of next page if(!is.null(string.val)) subTable[1, varName] <- string.val for(m in 1:nrow(subTable)) if(all(!subTable[m,varName] %in% "")) string.val <- subTable[m, varName] } hd <- sapply(colnames(subTable), function(x) strsplit(x, muliHead.split)[[1]]) ret <- rbind(hd, as.matrix(subTable)) colnames(ret) <- 1:ncol(ret) rownames(ret) <- 1:nrow(ret) ret2 <- ret colnames(ret2) <- 1:ncol(ret2) rownames(ret2) <- 1:nrow(ret2) attributes(ret2) <- list(dim = dim(ret2), dimnames = dimnames(ret2), `start cell` = c(cell1, cell2)) col.just <- matrix(c(rep(colFormat, nrow(ret2) + nheader)), ncol=ncol(ret2), byrow=TRUE) dat <- ret2 st <- attributes(dat)$'start cell'[1] hd <- 1:(st-1) if(is.null(cw)) cw <- c(1.5,rep(.7,ncol(dat)-1)) x <- dat cw2 <- matrix(rep(cw, nrow(x)), ncol=ncol(x), byrow=TRUE) if (st > 2) { y <- adj.width(x=dat[hd,],cw=cw, space=1) x[hd,] <- y$x cw2[hd,] <- y$cw } rtf.add.row <- function(rows=1:nrow(x)){ ret <- "{\\pard\n" for (i in rows) if (i <= nrow(x)){ sel <- which(cw2[i,]>0) ret <- paste(ret, .add.table.row( col.data = x[i,sel], col.widths = cw2[i,sel], col.justify = col.just[i,sel], font.size = fs, border.top = i %in% c(1), border.bottom = if (i > st-2) i %in% c(st-1,nrow(x),max(rows)) else x[i,sel] %in% var.ul ), sep='') if (i < st) if (!all(cw2[i,] == cw2[i+1,])) ret <- paste(ret,'{\\pard\\par}','', sep='') } ret <- paste(ret, "}\n\n", sep = "") rtf$.rtf <- paste(rtf$.rtf, ret, sep='') } rtf <- rtf fs <- rtf$.font.size rtf$.rtf <- gsub('Times New Roman', 'Courier New', rtf$.rtf) # make "Courier New" as default rtf$.rtf <- gsub('field{\\fldinst{page}}', '', rtf$.rtf, fixed=TRUE) # delete page number for (i in 1:1){ rtf.add.row(rows=c(1:(st-1), 1:nline.body-1+st+nline.body*(i-1))) } } }#end rtf.table.out #--- this funciton to be used for single plot output or # when there are different plots that would be saved in the same RTF file rtf.plot.out <- function(rtf, plotOut, page.disp=FALSE, height=8.5, width=11, omi.marg=c(1, 1, 1, 1), width.plot=8, height.plot=5, fs=10, titles,footns, prd.status="", widthHeader=7, widthFoot=9, breakPage=TRUE,...) { # rtf: RTF object that is just needed to be declared once before calling the function # plotOut: plot function # page.disp: whether diplay page number # width.plot, height.plot: width and height of plot # fs: font size for header and footnotes # titles,footns: title and footnotes # withHeader, widthFoot: width of header and footnotes # omi.marg: margin of the page # breakPage: if there are more than 1 page of the RTF file, need breakPage=TRUE, # otherwise (just a single page), set breakPage=FALSE rtf <- rtf rtf$.font.size <- fs rtf$.rtf <- gsub('Times New Roman', 'Courier New', rtf$.rtf) # make "Courier New" as default npage <- 1 # systems <- c(ifelse(page.disp==TRUE, paste('Page \\chpgn of ', npage, sep=''), ""), # format(Sys.time(), "%H:%M %d%b%Y"), # prd.status) # hd.m <- c(paste(titles, collapse='\\line '), # paste(systems, collapse='\\line ')) # main header # tmp <- .add.table.row( # col.data = hd.m, # col.widths = c(widthHeader,2), # col.justify = c('L', 'R'), # font.size = fs) # tmp2 <- .add.table.row( # col.data = paste(footns, collapse='\\line '), # col.widths = widthFoot, # col.justify = 'L', # font.size = fs) #-- add headers #rtf$.rtf <- paste(rtf$.rtf, '{\\pard\\par}', tmp, '{\\pard\\par}', sep='') #-- add plot addPlot(rtf, plot.fun=plotOut, width=width.plot, height=height.plot, res=300) #add plot #-- add footnotes #addParagraph(rtf, paste(footns, collapse='\\line ')) #rtf$.rtf <- paste(rtf$.rtf, '{\\pard\\par}', tmp2, '{\\pard\\par}', sep='') if(breakPage) addPageBreak(rtf, width=width, height=height, omi=omi.marg) }#end rtf.plot.out }#end RTF output functions #----------------------------------------------------------------------------------------------- # ###--- These functions are original developed/modified from Michael Man # in which he used RTF syntax (from tables and etable packages) rather than the RTF package. # #----------------------------------------------------------------------------------------------- if (TRUE) { .convert <- function (x) { x <- gsub("\\n", " \\\\line ", x) x <- gsub("<=", "\\\\u8804\\\\3", x) x <- gsub(">=", "\\\\u8805\\\\3", x) x <- gsub("&gt;", ">", x) x <- gsub("&lt;", "<", x) x <- gsub("&Alpha;", "\\\\u0913\\\\3", x) x <- gsub("&Beta;", "\\\\u0914\\\\3", x) x <- gsub("&Gamma;", "\\\\u0915\\\\3", x) x <- gsub("&Delta;", "\\\\u0916\\\\3", x) x <- gsub("&Epsilon;", "\\\\u0917\\\\3", x) x <- gsub("&Zeta;", "\\\\u0918\\\\3", x) x <- gsub("&Eta;", "\\\\u0919\\\\3", x) x <- gsub("&Theta;", "\\\\u0920\\\\3", x) x <- gsub("&Iota;", "\\\\u0921\\\\3", x) x <- gsub("&Kappa;", "\\\\u0922\\\\3", x) x <- gsub("&Lambda;", "\\\\u0923\\\\3", x) x <- gsub("&Mu;", "\\\\u0924\\\\3", x) x <- gsub("&Nu;", "\\\\u0925\\\\3", x) x <- gsub("&Xi;", "\\\\u0926\\\\3", x) x <- gsub("&Omicron;", "\\\\u0927\\\\3", x) x <- gsub("&Pi;", "\\\\u0928\\\\3", x) x <- gsub("&Rho;", "\\\\u0929\\\\3", x) x <- gsub("&Sigma;", "\\\\u0931\\\\3", x) x <- gsub("&Tau;", "\\\\u0932\\\\3", x) x <- gsub("&Upsilon;", "\\\\u0933\\\\3", x) x <- gsub("&Phi;", "\\\\u0934\\\\3", x) x <- gsub("&Chi;", "\\\\u0935\\\\3", x) x <- gsub("&Psi;", "\\\\u0936\\\\3", x) x <- gsub("&Omega;", "\\\\u0937\\\\3", x) x <- gsub("&alpha;", "\\\\u0945\\\\3", x) x <- gsub("&beta;", "\\\\u0946\\\\3", x) x <- gsub("&gamma;", "\\\\u0947\\\\3", x) x <- gsub("&delta;", "\\\\u0948\\\\3", x) x <- gsub("&epsilon;", "\\\\u0949\\\\3", x) x <- gsub("&zeta;", "\\\\u0950\\\\3", x) x <- gsub("&eta;", "\\\\u0951\\\\3", x) x <- gsub("&theta;", "\\\\u0952\\\\3", x) x <- gsub("&iota;", "\\\\u0953\\\\3", x) x <- gsub("&kappa;", "\\\\u0954\\\\3", x) x <- gsub("&lambda;", "\\\\u0955\\\\3", x) x <- gsub("&mu;", "\\\\u0956\\\\3", x) x <- gsub("&nu;", "\\\\u0957\\\\3", x) x <- gsub("&xi;", "\\\\u0958\\\\3", x) x <- gsub("&omicron;", "\\\\u0959\\\\3", x) x <- gsub("&pi;", "\\\\u0960\\\\3", x) x <- gsub("&rho;", "\\\\u0961\\\\3", x) x <- gsub("&sigmaf;", "\\\\u0962\\\\3", x) x <- gsub("&sigma;", "\\\\u0963\\\\3", x) x <- gsub("&tau;", "\\\\u0964\\\\3", x) x <- gsub("&upsilon;", "\\\\u0965\\\\3", x) x <- gsub("&phi;", "\\\\u0966\\\\3", x) x <- gsub("&chi;", "\\\\u0967\\\\3", x) x <- gsub("&psi;", "\\\\u0968\\\\3", x) x <- gsub("&omega;", "\\\\u0969\\\\3", x) x <- gsub("TRUE", "Yes", x) x <- gsub("FALSE", "No", x) x } .get.space.before.after <- function (space.before = NULL, space.after = NULL) { ret <- "" if (!is.null(space.before)) { ret <- paste(ret, "\\sb", (space.before * 1440), sep = "") } if (!is.null(space.after)) { ret <- paste(ret, "\\sa", (space.after * 1440), sep = "") } ret } .add.table <- function (dat, col.widths = NULL, col.justify = NULL, header.col.justify = NULL, font.size = 10, row.names = FALSE, indent = 0, NA.string = "-", bd.top=NULL, bd.bottom=NULL, # MZM: border option, need row numbers max.table.width = NULL, space.before = NULL, space.after = NULL) { ret <- "{\\pard\n" if (!is.null(bd.top) | !is.null(bd.bottom)) { #MZM: for complex table dat <- as.data.frame(dat, stringsAsFactors = FALSE) nc <- ncol(dat) if (is.null(col.widths)) col.widths <- rep(6.5/nc, nc) for (i in 1:nrow(dat)) { ret <- paste(ret, .add.table.row(as.character(dat[i, ]), col.widths, col.justify, font.size = font.size, last.row = FALSE, indent = indent, space.before = space.before, # MZM: change last.row border.top = i %in% bd.top, border.bottom = i %in% bd.bottom, # MZM: add top/bottom option space.after = space.after), sep = "") } } else if ("table" %in% class(dat)) { if (length(dim(dat)) == 1) { varnames <- names(dimnames(dat))[1] nc <- 2 nr <- length(dimnames(dat)[[1]]) if (is.null(col.widths)) { col.widths <- rep(6.5/nc, nc) } ret <- paste(ret, .add.table.header.row(c(names(dimnames(dat))[1], " "), col.widths, header.col.justify, font.size = font.size, repeat.header = TRUE, indent = indent), sep = "") if (nrow(dat) > 1) { for (i in 1:(nrow(dat) - 1)) { rn <- rownames(dat)[i] ret <- paste(ret, .add.table.row(c(rn, as.character(dat[i])), col.widths, col.justify, font.size = font.size, indent = indent, space.before = space.before, space.after = space.after), sep = "") } } rn <- rownames(dat)[nrow(dat)] ret <- paste(ret, .add.table.row(c(rn, as.character(dat[nrow(dat)])), col.widths, col.justify, font.size = font.size, indent = indent, border.bottom = TRUE, space.before = space.before, space.after = space.after), sep = "") } else if (length(dim(dat)) == 2) { varnames <- names(dimnames(dat)) nc <- ncol(dat) + 1 nr <- nrow(dat) if (is.null(col.widths)) { col.widths <- rep(6.5/nc, nc) } ret <- paste(ret, .add.merged.table.row(c(" ", paste("\\b ", varnames[2], " \\b0", sep = ""), rep(" ", nc - 2)), col.widths, font.size = font.size, indent = indent, border.top = TRUE), sep = "") ret <- paste(ret, .add.table.row(c(paste("\\b ", varnames[1], " \\b0", sep = ""), colnames(dat)), col.widths, col.justify, font.size = font.size, indent = indent, border.bottom = TRUE), sep = "") if (nrow(dat) > 1) { for (i in 1:(nrow(dat) - 1)) { rn <- rownames(dat)[i] ret <- paste(ret, .add.table.row(c(rn, as.character(dat[i, ])), col.widths, col.justify, font.size = font.size, indent = indent, space.before = space.before, space.after = space.after), sep = "") } } rn <- rownames(dat)[nrow(dat)] ret <- paste(ret, .add.table.row(c(rn, as.character(dat[nrow(dat), ])), col.widths, col.justify, font.size = font.size, indent = indent, border.bottom = TRUE, space.before = space.before, space.after = space.after), sep = "") } else { stop("Table dimensions can't be written") } } else if ("xtab" %in% class(dat)) { nc <- ncol(dat$counts) + 2 nr <- nrow(dat$counts) if (is.null(col.widths)) { col.widths <- rep(6.5/nc, nc) } ret <- paste(ret, .add.merged.table.row(c(" ", paste("\\b ", dat$varnames[2], " \\b0", sep = ""), rep(" ", nc - 2)), col.widths, font.size = font.size, indent = indent, border.top = TRUE), sep = "") ret <- paste(ret, .add.table.row(c(paste("\\b ", dat$varnames[1], " \\b0", sep = ""), colnames(dat$counts), "Total"), col.widths, col.justify, font.size = font.size, indent = indent, border.bottom = TRUE), sep = "") grand.total <- sum(dat$col.margin) if (nrow(dat$counts) > 1) { for (i in 1:(nrow(dat$counts))) { rn <- rownames(dat$counts)[i] ret <- paste(ret, .add.table.row(c(rn, as.character(dat$counts[i, ]), paste(dat$row.margin[i], " (", sprintf("%0.1f", dat$row.margin[i]/grand.total * 100), "%)", sep = "")), col.widths, col.justify, font.size = font.size, indent = indent, space.before = space.before, space.after = space.after), sep = "") ret <- paste(ret, .add.table.row(c(" ", paste("(", sprintf("%0.1f", dat$counts[i, ]/dat$row.margin[i] * 100), "% R)", sep = ""), " "), col.widths, col.justify, font.size = font.size, indent = indent, space.before = space.before, space.after = space.after), sep = "") ret <- paste(ret, .add.table.row(c(" ", paste("(", sprintf("%0.1f", dat$counts[i, ]/dat$col.margin * 100), "% C)", sep = ""), " "), col.widths, col.justify, font.size = font.size, indent = indent, space.before = space.before, space.after = space.after), sep = "") ret <- paste(ret, .add.table.row(rep(" ", nc), col.widths, col.justify, font.size = font.size, indent = indent, space.before = space.before, space.after = space.after), sep = "") } } ret <- paste(ret, .add.table.row(c("Total", paste(as.character(dat$col.margin), paste(" (", sprintf("%0.1f", dat$col.margin/grand.total * 100), "%)", sep = "")), as.character(grand.total)), col.widths, font.size = font.size, last.row = TRUE, indent = indent, space.before = space.before, space.after = space.after), sep = "") } else if ("matrix" %in% class(dat) & !is.null(attributes(dat)$"start cell")) { start.row <- attributes(dat)$"start cell"[1] dat <- as.data.frame(dat, stringsAsFactors = FALSE) if (is.null(col.widths) & !is.null(max.table.width)) { col.widths <- .optimize.col.widths(dat, include.row.names = row.names, max.table.width = max.table.width, font.size = font.size) } nc <- ncol(dat) if (is.null(col.widths)) { col.widths <- rep(6.5/nc, nc) } if (nrow(dat) > 1) { for (i in 1:(nrow(dat) - 1)) { if (i < start.row) { border.top = FALSE border.bottom = FALSE if (i == 1) { border.top = TRUE } if (i == (start.row - 1)) { border.bottom = TRUE } ret <- paste(ret, .add.table.row(paste("\\b ", as.character(dat[i, ]), " \\b0", sep = ""), col.widths, col.justify, font.size = font.size, indent = indent, border.top = border.top, border.bottom = border.bottom, space.before = space.before, space.after = space.after), sep = "") } else { ret <- paste(ret, .add.table.row(as.character(dat[i, ]), col.widths, col.justify, font.size = font.size, indent = indent, space.before = space.before, space.after = space.after), sep = "") } } ret <- paste(ret, .add.table.row(as.character(dat[nrow(dat), ]), col.widths, col.justify, font.size = font.size, last.row = TRUE, indent = indent, space.before = space.before, space.after = space.after), sep = "") } } else if ("data.frame" %in% class(dat) || "matrix" %in% class(dat)) { if ("matrix" %in% class(dat)) { dat <- as.data.frame(dat) } rnames <- rownames(dat) is.na(dat) <- is.na(dat) dat <- data.frame(lapply(dat, as.character), stringsAsFactors = FALSE, check.names = FALSE) dat[is.na(dat)] <- NA.string dat[dat == "NA"] <- NA.string rownames(dat) <- rnames if (is.null(col.widths) & !is.null(max.table.width)) { col.widths <- .optimize.col.widths(dat, include.row.names = row.names, max.table.width = max.table.width, font.size = font.size) } nc <- ncol(dat) if (row.names == TRUE) { nc <- nc + 1 } if (is.null(col.widths)) { col.widths <- rep(6.5/nc, nc) } if (row.names == TRUE) { ret <- paste(ret, .add.table.header.row(c(" ", colnames(dat)), col.widths, header.col.justify, font.size = font.size, repeat.header = TRUE, indent = indent), sep = "") } else { ret <- paste(ret, .add.table.header.row(colnames(dat), col.widths, header.col.justify, font.size = font.size, repeat.header = TRUE, indent = indent), sep = "") } if (nrow(dat) > 1) { for (i in 1:(nrow(dat) - 1)) { if (row.names == TRUE) { rn <- rownames(dat)[i] ret <- paste(ret, .add.table.row(c(rn, as.character(dat[i, ])), col.widths, col.justify, font.size = font.size, indent = indent, space.before = space.before, space.after = space.after), sep = "") } else { ret <- paste(ret, .add.table.row(as.character(dat[i, ]), col.widths, col.justify, font.size = font.size, indent = indent, space.before = space.before, space.after = space.after), sep = "") } } } if (row.names == TRUE) { rn <- rownames(dat)[nrow(dat)] ret <- paste(ret, .add.table.row(c(rn, as.character(dat[nrow(dat), ])), col.widths, col.justify, font.size = font.size, last.row = TRUE, indent = indent, space.before = space.before, space.after = space.after), sep = "") } else { ret <- paste(ret, .add.table.row(as.character(dat[nrow(dat), ]), col.widths, col.justify, font.size = font.size, last.row = TRUE, indent = indent, space.before = space.before, space.after = space.after), sep = "") } } else { warning("No suitable RTF converter for object class!") } ret <- paste(ret, "}\n\n", sep = "") ret } .add.table.row <- function (col.data = c("c1", "c2", "c3"), col.widths = c(1, 4.5, 1), col.justify = NULL, font.size = 10, last.row = FALSE, indent = 0, border.top = FALSE, border.bottom = FALSE, space.before = NULL, space.after = NULL) { header <- paste("\\trowd\\trgaph100\\trleft", indent, sep = "") if (length(col.data) != length(col.widths)) { stop(paste("The number of data columns (", length(col.data), ") doesn't match the column widths (", length(col.widths), ")! Input data: ", col.data, sep = "")) } justify <- vector() justify["L"] <- "\\ql" justify["R"] <- "\\qr" justify["C"] <- "\\qc" justify["J"] <- "\\qj" justify.v <- rep(justify["L"], length(col.data)) numeric.cols <- which(!is.na(suppressWarnings(as.numeric(col.data)))) if (length(numeric.cols) > 0) { justify.v[numeric.cols] <- justify["R"] } if (!is.null(col.justify)) { if (length(col.justify) == 1) { if (col.justify %in% names(justify)) { justify.v <- rep(justify[col.justify], length(col.data)) } else { stop(paste("col.justify parameter not recognized: ", col.justify, " (should be L, R, C, or J)", sep = "")) } } else if (length(col.justify) == length(col.data)) { justify.v <- justify[col.justify] } else { stop(paste("The number of data columns (", length(col.data), ") doesn't match the col.justify (", length(col.justify), ") parameter! Input data: ", paste(col.data, sep = "", collapse = ", "), sep = "")) } } btop <- "" bbottom <- "" if (any(border.top)) # MZM btop <- sapply(border.top, ifelse, "\\clbrdrt\\brdrs\\brdrw15",'') #MZM: make border.top as a vector option if (last.row == TRUE | any(border.bottom)) #MZM bbottom <- sapply(border.bottom, ifelse, "\\clbrdrb\\brdrs\\brdrw15",'') #MZM: make border.bottom as a vector option cols.prefix <- paste("\\clvertalt\\clshdrawnil\\clwWidth", round(col.widths * 1440, 0), "\\clftsWidth3\\clheight260\\clpadl100\\clpadr100\\gaph", btop, bbottom, "\\cellx", c(1:length(col.widths)), "\n", sep = "", collapse = "") cols <- paste("\\pard", justify.v, .get.space.before.after(space.before, space.after), "\\widctlpar\\intbl\\fi0\\f2\\fs", font.size * 2, " ", .convert(col.data), "\\cell\n", sep = "", collapse = "") end.row <- "\\widctlpar\\intbl\\row\n" paste(header, cols.prefix, cols, end.row, sep = "") } # add width basing on duplication adj.width <- function(x, cw, space=1){ ret <- array(0, dim=dim(x)) x2 <- x dup <- t(apply(x,1, function(x) c(FALSE, unlist(x[-1])==unlist(x[-length(x)])))) for (i in 1:nrow(x)) { for (j in ncol(x):1) { if (i > 1 & j <= ncol(x)) if (!dup[i-1,j]) dup[i,j] <- FALSE if (dup[i,j]) { ret[i,j-1] <- ret[i,j]+space*cw[j] ret[i,j ] <- -space*cw[j] x2[i,j] <- '' } } ret[i,] <- ret[i,]+cw } list(x=x2, cw=ret) }#end }#end mist functions if (TRUE) { #----------------------------------------------------------------------------------------------- # ###--- These functions are used for formatting dataframe, before produce it to RTF file # #----------------------------------------------------------------------------------------------- # cat the expression and its result. cat.exp <- function(x, start='\n----', sep2=ifelse(Print, '\n', ': '), end='\n', Print=is.na(match(class(eval(x)), c('integer', 'numeric', 'character')))) { cat(start, deparse(substitute(x)), sep2) if (!Print) cat(eval(x),end) else print(eval(x)) }#end # Function to add blank line between item (record) from table output. add.blank.line.between <- function(dat, index_blank) { #--- adding blank lines between subjects dat2 <- NULL for(k in 1:length(index_blank)) { if(k==1) { if(index_blank[k]==index_blank[k+1]-1) { tmp <- rbind(dat[1:index_blank[k], ], "") } else { tmp <- rbind(dat[(index_blank[k]:(index_blank[k+1]-1)), ], "") } } else if(k==length(index_blank)) { tmp <- rbind(dat[(index_blank[k]:nrow(dat)), ], "") } else { tmp <- rbind(dat[(index_blank[k]:(index_blank[k+1]-1)), ], "") } if(is.null(dat2)) dat2 <- tmp else dat2 <- rbind(dat2, tmp) } dat_with_blank <- dat2 return(dat_with_blank) }#end add_blank_line <- function(dat, index_blank) { #--- adding blank lines into data dat2 <- NULL for(k in 1:length(index_blank)) { if(k==1) { tmp <- rbind(dat[1:index_blank[k], ], "") } else { tmp <- rbind(dat[(index_blank[k-1]+1):index_blank[k], ], "") } if(is.null(dat2)) dat2 <- tmp else dat2 <- rbind(dat2, tmp) } dat_with_blank <- rbind(dat2, dat[(index_blank[k]+1):nrow(dat), ]) # add the last part return(dat_with_blank) }#end # format numbers before outputing format.num <- function(x, num.sigf=2, width=1, num.space=1, trun=FALSE) { num <- formatC(format(round(x, num.sigf), nsmall=num.sigf), width=width, flag=paste(rep("", num.space), collapse=" ")) if(trun==TRUE) { num <- gsub(" ", "", num) } return(num) }#end format_num sep.space <- function(n) { paste(rep(" ", times=n), collapse="") }#end #--- exclude col with all NA value ex.col <- function(dat, excluded=c(NA, "")) { for(i in colnames(dat)) if(all(dat[,i] %in% excluded)) { print(i) dat <- dat[,-which(names(dat) %in% i)] } dat } #--- excluded row with all NA value ex.row <- function(dat, na.str=c(NA, "NA", "", " ", ".")) { ex.r <- NULL for(i in 1:nrow(dat)) { x <- dat[i,] if(all(x %in% na.str)) ex.r <- c(ex.r, i) } if(!is.null(ex.r)) ret <- dat[-ex.r,] else ret <- dat return(ret) }#end #--- function to make the 1st letter of a word to uppercase simpleCap <- function(x) { x2 <- tolower(x) gsub("(^|[[:space:]])([[:alpha:]])", "\\1\\U\\2", x2, perl=TRUE) }#end # reorder levels level.order <- function(x, index=c(1,2,3)) { y <- factor(x) levels(y) <- index y <- as.numeric(as.character(y)) return(y) }#end # remove duplcate. For example, a ID has multiple rows, just displaying # the ID in the 1st row, the rest is empty removed.dup <- function(dat, dupBy=NULL, varName=NULL) { id.dup <- which(duplicated(dat[,dupBy])) dat[id.dup, varName] <- "" return(dat) }#end #--- function to replace value replace.val <- function(x, replaceVal=NA, byVal=NULL) { id <- which(x %in% replaceVal) x[id] <- byVal x }#end replace_val # some cases needed to convert NA to zero convert.NA.to.zero <- function(dat) { check.NA <- function(x, width=2) { if(any(is.na(x))) x[x%in%NA] <- format(0, justify='right', width=width) x } tmp <- apply(dat, 2, check_NA) ret <- data.frame(tmp) return(ret) }#end # Function to Generate rtf table column widths col.width <- function(tb){ cws <- NULL for(i in 1:length(names(tb))) { ncName <- nchar(names(tb)[i]) ncString <- max(nchar(tb[,i])) nc <- max(ncName, ncString) cw <- nc*0.89/10 # assume 10 characters per an inch cws <- c(cws, cw) } return(cws) }#end # Fill missing/blank as NA fill.missing <- function(x) { x2 <- x if(any(x2 %in% c(NA, "", ".", " "))) { x2[which(x2 %in% c(NA, "", ".", " "))] <- NA } # make sure class of x would be the same as its original class class(x2) <- class(x) return(x2) }#end # make two data have the same class() # apply for original and derived data class.data <- function(dat1, dat2) { # dat1: original # dat2: derived if(ncol(dat1) != ncol(dat2)) stop for(i in 1:ncol(dat1)) { class(dat2[,i]) <- class(dat1[,i]) } return(dat2) }#end # function to map Lilly color with chart R color color.code <- function(str.color) { colz <- NULL for(i in 1:length(str.color)) { colz[i] <- str.color[i] if(str.color[i] %in% "red") {colz[i] <- '#D52B1E'} if(str.color[i] %in% "blue") {colz[i] <- '#00A1DE'} if(str.color[i] %in% "darkblue") {colz[i] <- '#263F6A'} if(str.color[i] %in% "green") {colz[i] <- '#00AF3F'} if(str.color[i] %in% "lightgreen") {colz[i] <- '#C2EDCE'} if(str.color[i] %in% "darkgreen") {colz[i] <- '#275E37'} if(str.color[i] %in% "yellow") {colz[i] <- '#FED100'} if(str.color[i] %in% "orange") {colz[i] <- '#FF6D22'} if(str.color[i] %in% c('grey', 'gray')) {colz[i] <- '#A59D95'} if(str.color[i] %in% c('lightgrey', 'lightgray')) {colz[i] <- '#D5D2CA'} if(str.color[i] %in% c('darkgrey', 'darkgray')) {colz[i] <- '#82786F'} if(str.color[i] %in% "brown") {colz[i] <- '#4E2E2D'} }#end return(colz) }#end stat_summary <- function(xval, quantile=FALSE) { # xval: a numeric vector summ <- summary(xval) SD <- sd(xval, na.rm=T) if(quantile) { result <- c(summ[names(summ)%in%'Mean'], SD, summ[names(summ)%in%'1st Qu.'], summ[names(summ)%in%'Median'], summ[names(summ)%in%'3rd Qu.'], summ[names(summ)%in%'Min.'], summ[names(summ)%in%'Max.']) } else { result <- c(summ[names(summ)%in%'Mean'], SD, summ[names(summ)%in%'Median'], summ[names(summ)%in%'Min.'], summ[names(summ)%in%'Max.']) } return(result) }#end stat_summary }#end #------------------------------------------------------------------------------------------------
/scratch/gouwar.j/cran-all/cranData/BEACH/inst/app/functions/RTF_functions_DY.r
read<-TRUE; indataset.names <<- names(indataset)
/scratch/gouwar.j/cran-all/cranData/BEACH/inst/app/functions/empty.r
conditionalPanel( condition="true", div(class='row'), div(class='span4', textInput('datPath','Path for read in dataset.', value="")), #paste0("//lrlhps/data/ttx_projects/onc/reusable/mock_data", #"/mock_merged_clin_FMI_Breast.csv"))), div(class='span4', textInput('outPath','Path for output RTF file.', value= tempfile(pattern='shiny', tmpdir="", #//lrlhps/data/ttx_projects/onc/reusable/r_function/dev/output fileext='.rtf'))), br(), div(class='row'), div(class='span11', tabsetPanel( tabPanel('Run Code', downloadButton("save_rcode","Save Code"), div(class="alert alert-info", strong("Note: "), r.lib.alert), verbatimTextOutput("rcode")), tabPanel('Source Functions', downloadButton("save_scode","Save Source"), verbatimTextOutput("scode")))) )
/scratch/gouwar.j/cran-all/cranData/BEACH/inst/app/functions/rcode.r
conditionalPanel(condition='true', h5(a('COSMIC Database',href='http://cancer.sanger.ac.uk/cancergenome/projects/cosmic/',target='_blank')), h5(a('Memorial Sloan Kettering cBioPortal Cancer Genomics Database',href='http://www.cbioportal.org/public-portal/',target='_blank')), h5(a('Roche Genome Cancer Database',href='http://rcgdb.bioinf.uni-sb.de/MutomeWeb/',target='_blank')) )
/scratch/gouwar.j/cran-all/cranData/BEACH/inst/app/functions/resource.r
#----------UI Functions------------------# #select color function selectInput_color <- function(id='wpColor', label='Background color', choices=colors(), selected='azure3', HEX=HEXColors){ code <- paste0("<div class=\"form-group shiny-input-container\">\n", "<label class=\"control-label\" for=\"", id, "\">", label, ":</label>\n<div>\n", "<select id=\"", id, "\"><option value=\"", selected, "\" selected>", selected, "</option>\n") for(i in 1:length(choices)){ code <- paste0(code, "<option value=\"", choices[i], "\" style=\"background-color: ", HEX[choices[i]], "\">", choices[i], "</option>\n") } code <- paste0(code, "</select>", "<script type=\"application/json\" data-for=\"", id, "\" data-nonempty=\"\">{}</script> \n</div>\n</div> ") return(code) } #Function to create Table with checkboxes checkboxTableInput <- function(df,table.id="checktable",id.name, checked, check.name,labels=NULL, showSelectedOnly=FALSE ){ table_head0<-capture.output(print(xtable(df[0,]), type="html", include.rownames=F,include.colnames=T)) table_head0[3]<-"<table border=1 class=\"table table-bordered\">" table_head <- paste(table_head0, collapse=" ") table_head <- gsub("</TABLE>", "", table_head) table_head <- gsub("</table>", "", table_head) table_head <- gsub("<table", paste0("<table id=\"",table.id,"\""), table_head) table_head<- gsub('<TR>','<tr>',table_head) table_head<- gsub('</TR>','</tr>',table_head) table_head <- gsub("<tr>", paste("<tr> <th> ", check.name, " </th>", sep=""), table_head) table_body <- paste(capture.output(print(xtable(df), type="html", content.only=T, include.rownames=F, include.colnames=F)), collapse=" ") table_body<- gsub('<TR>','<tr>',table_body) table_body<- gsub('</TR>','</tr>',table_body) table_body<- gsub('<TD>','<td>',table_body) table_body<- gsub('</TD>','</td>',table_body) table_body<- gsub('</tr>','',table_body) table_body<- gsub('</table>','',table_body) which.tag <- regexpr("<tr>", table_body)[1] table_body <- substr(table_body, which.tag, nchar(table_body)) table_body2 <- unlist(strsplit(table_body, "<tr>", fixed=T)) # print(table_body2) table_body3 <- '' #table_body2[1] if(showSelectedOnly){ for (i in 1:nrow(df)){ if(checked[i]){ check_tag <- paste("<tr> <td align=left>", as.character(checkboxInput(paste0(id.name,'_',i), "", checked[i])), " </td>", sep="") table_body3<-paste(table_body3, check_tag, table_body2[i+1], "</tr>", sep="") } } }else{ for (i in 1:nrow(df)){ check_tag <- paste("<tr> <TD align=left>", as.character(checkboxInput(paste0(id.name,'_',i), "", checked[i])), " </td>", sep="") table_body3<-paste(table_body3, check_tag, table_body2[i+1], "</tr>", sep="") } } table_out <- paste(table_head, table_body3, "</table>", collapse=" ") if (!is.null(labels)){ for (k in 1:length(labels)){ table_out<-gsub(paste0('<th> ',colnames(df)[k],' </th>'), paste0('<th> ',labels[k],' </th>'), table_out) } } # print(table_out) return(table_out) } #-------------Create Tabs-------------# tabs<-function(tab.id,tab.label,tab.value){ tabset<-unique(cbind(tab.label,tab.value)) tabcode1<-paste0('<div class=\"tabbable tabs-above\">\n', '<ul class=\"nav nav-tabs shiny-tab-input\" id=\"', tab.id,'\">\n<li class=\"active\">\n') tabcode2<-paste0('<a href=\"#tab-',tab.id,'-',1:nrow(tabset), '\" data-toggle=\"tab\" data-value=\"', tabset[,1],"\">",tabset[,2],"</a>\n</li>\n<li>\n") tabcode2[length(tabcode2)]<-gsub('<li>','</ul>',tabcode2[length(tabcode2)]) tabcode3<-"<div class=\"tab-content\">" tabcode4<-paste0('<div class=\"tab-pane active\" data-value=\"', tabset[,1],'\" id=\"tab-',tab.id,'-',1:nrow(tabset), '\"></div>\n',collapse=" ") tabcode5<-'</div>\n</div>' tabcode<-paste0(tabcode1,paste0(tabcode2,collapse=" "), tabcode3,tabcode4,tabcode5,collapse=" ") return(tabcode) } #-------------side panel data input-------------# inlinetext<-function(text.id,text.label,text.value, note=NULL){ if(is.null(note)){ nt <- "" }else { nt <- paste0('<h6 style=\"width:50%\">', note, ' </h6>') } if(FALSE){ #using textInput widget code <- paste0( "<div class = \"form-group shiny-input-container\", style = \"width:100%\">", paste0("<label for=\"", text.id, "\">", text.label, "</label>"), paste0("<input id=\"", text.id, "\" type=\"text\" class=\"form-control\" value=\"", text.value, "\"/>"), "</div>", collapse='\n' ) } else { #using traditional widget code<-paste0( '<div class=\"input-prepend\" style=\"width:100%\">', paste0('<span class=\"add-on\" >',text.label,'</span>'), paste0('<input style=\"width:50%\" id=\"',text.id, '\" class=\"form-control\" value=\"',text.value,'\" type=\"text\" />\n'), nt, '</div>', collapse='\n') } return(code) } #-------------For output R code-------------# runcode<-function(codelist, # merged dataset of loa and configuration file datPath, # dataset path from input outPath, # output path from input libs, params1, #a vector of widgets name (require ordered) paramLabs1, #a vector of widgets label(1:1 matched to params) sourceCode, # source files from configuration file subCode, title0, # Main title with study id and tumor type devpath, outBcode=NULL ){ #codelist<-codelist[!(!is.na(codelist[,paramLabs1[1]]) & is.na(codelist[,params1[1]])),] sourceCode<-unique(sourceCode[!is.na(sourceCode)]) sourceCode<-sourceCode[!grepl("rcode.r",sourceCode)] head1<-sop_head #paste0('#/*soh',paste0(rep('*',73),collapse='')) nParam<-length(params1) params1.od <- order(params1) params1 <- params1[params1.od] paramLabs1 <- paramLabs1[params1.od] if(FALSE){ head2<-'if(FALSE){ # DESCRIPTION: Parameters for generating following results:' tmploa<-unique(codelist[,c('Request.Name',params1,paramLabs1)]) tmploa2<-sapply(1:nrow(tmploa),function(y){ paste0(tmploa$Request.Name[y],' ', ifelse(is.na(tmploa[y,paramLabs1[1]]), '', paste0('(',paste0(sapply(which(!is.na(tmploa[y,paramLabs1])),function(x){ paste0(tmploa[y,paramLabs1[x]],'=', ifelse(is.na(tmploa[y,params1[x]]), 'Parameters Needed', tmploa[y,params1[x]])) }),collapse=';'),') \n') ) )}) tmploa2<-gsub(";", ";\n #", tmploa2) head3<-paste0(' #',1:length(tmploa2),'. ',tmploa2) head4<-paste0('\n}\n#', paste0(rep("-",90),collapse='')) #end of DESCRIPTION } else { head2<-'' head3<-'' head4<-'' } head5<-''# paste0(' #', gsub('\n', '\n # ', libs)) head6<-'\nif(TRUE){ #------Read in CSV Dataset------' head7<-paste0( ' indataset<-list() \n', ' for(i in 1:length(inf)){ \n', ' indataset[[i]]<-read.csv_sas(inf[i],stringsAsFactors=FALSE,header=TRUE, encoding=inf.enc[i], comment.char=\"\") \n', ' } \n ', ' names(indataset)<-inf \n', ' indataset.i<-indataset[[1]] ') head8<-paste0(' ', subCode) head6.1<-'\n}\nif(TRUE){ #------Read in one RData------' head7.1<-paste0( 'load(inf.R, indataR<-new.env())\n', 'indataR<<-as.list(indataR)\n' ) head9<-'\n}\n\nif (TRUE){ #------Source Packages and Function Files------' #connect default folder for reusable functions head10<-paste0( ' if(FALSE){ #Please firstly check whether all the required pacakges are installed.\n ', '#install.packages(c(...))\n ', gsub('\n', '\n ', libs), '\n }', '\n require(rtf) \n require(haven) \n', '\n read.csv_sas<<-function(file, header=TRUE, nrow=-1, comment.char="", ...){', '\n is.sas<-grepl(\'.sas7bdat\', file, fixed=TRUE)', '\n is.csv<-grepl(\'.csv\', file, fixed=TRUE)', '\n if(is.sas){', '\n ot<-haven::read_sas(file)', '\n if(header & nrow==1){ot<-names(ot)}', '\n }else if (is.csv){', '\n tm<-try(ot<-read.csv(file=file, h=header, nrow=nrow, na=c(\'NA\', \'\', \'.\'), stringsAsFactors=FALSE, comment.char=comment.char, ...))', '\n if(class(tm)==\'try-error\')', '\n tm<-try(ot<-read.csv(file=file, h=header, nrow=nrow, na=c(\'NA\', \'\', \'.\'), stringsAsFactors=FALSE,fileEncoding=\"latin1\", comment.char=comment.char))', '\n if(class(tm)==\'try-error\')', '\n tm<-try(ot<-read.csv(file=file, h=header, nrow=nrow, na=c(\'NA\', \'\', \'.\'), stringsAsFactors=FALSE,fileEncoding=\"UTF-8\", comment.char=comment.char))', '\n if(class(tm)==\'try-error\')', '\n tm<-try(ot<-readLines(con=file)) ', '\n }else{', '\n ot<-NULL\n}', '\n return(ot) \n }', "\n try(source(SourceFile)) \n ", "\n ", ifelse(is.null(eval(parse(text=outBcode))), " ", outBcode), "\n}") head11<-'\n\nif(OutputRTF){ #----- Generate RTF file ------' head12<-paste0('\n pageW<-11 \n pageH<-8.5 \n figW<-9 \n figH<-6 \n', '\n rtf<-RTF(rtfFileName,width=pageW,height=pageH, font.size=8,omi=c(.5,.5,.5,.5))') r_out<-c(head1,head2,head3,head4,head5, head9,head10,head6,head7,head8,head6.1, head7.1, head11,head12) for (i in 1:nrow(codelist)){ for(x in nParam:1){ if(!is.na(codelist[i,params1[x]])){ tmp0<-unlist(strsplit(as.character(codelist[i,params1[x]]), ',',fixed=TRUE)) tmp00 <- try( as.numeric(tmp0) ) if( class(tmp00)[1]=='try-error' || any(is.na(as.numeric(tmp0))) ) say1 <- TRUE else say1 <-FALSE tmp<-ifelse(say1, paste0('c(\"',paste0(tmp0,collapse='\",\"'),'\")'), paste0('c(',paste0(codelist[i,params1[x]],collapse=','),')')) codelist$Title[i]<- gsub(paste0('input$',params1[x]), tmp,codelist$Title[i],fixed=TRUE) codelist$PlotCode[i]<- gsub(paste0('input$',params1[x]), tmp,codelist$PlotCode[i],fixed=TRUE) codelist$FootCode[i]<- gsub(paste0('input$',params1[x]), tmp,codelist$FootCode[i],fixed=TRUE) } } #Add Header title<-codelist$Title[i] if(is.na(title) || length(title)<1) title <- " " if(grepl(title, 'paste', fixed=TRUE)) title<-eval(parse(text=title)) addhead<-vector() addhead[1]<-paste0('\n\n #------Add Header ',codelist$order[i],' ------') addhead[2]<-paste0(' addHeader(rtf,title=\"',title0,'\",font.size=10)') addhead[3]<-paste0(' addHeader(rtf,title=\"',title,'\",font.size=10)') r_out<-c(r_out,addhead) #Add Plot if( (!is.na(codelist$Type.y[i]) & codelist$Type.y[i]=='Figure') || (!is.na(codelist$Type.x[i]) & codelist$Type.x[i]=='Figure') ){ addplot<-vector() addplot[1]<-paste0(' #------Add Plot: ',codelist$Request.Name[i],' ------') addplot[2]<-paste0(' tmp<-',codelist$tmp[i]) addplot[3]<-paste0(' pngtmp<-function(){',codelist$PlotCode[i],'}') addplot[4]<-paste0(' addPlot(rtf,pngtmp,width=',codelist$width[i]/160,',height=',codelist$height[i]/160,')') r_out<-c(r_out,addplot)} #Add Table if( (!is.na(codelist$Type.y[i]) & codelist$Type.y[i]=='Table') || (!is.na(codelist$Type.x[i]) & codelist$Type.x[i]=='Table') ){ addtab<-vector() addtab[1]<-paste0(' #------Add Table: ',codelist$Request.Name[i],' ------') addtab[2]<-paste0(' tmp<-',codelist$tmp[i]) addtab[3]<-paste0(' outTable<-{',codelist$PlotCode[i],'}') addtab[4]<-paste0(' tWidth<-9\nnc<-nchar(as.character(outTable[,1]))\nc1W<-pmax(max(nc)*0.079/2, 20*0.079)\n', ' caW<-nc*0.079\nlcW<-.711\nothW<-(tWidth-c1W-lcW)/(ncol(outTable)-2)\n', ' centW<-rep(othW,ncol(outTable)-2)\ncWs<-c(c1W,centW,lcW)' ) addtab[5]<-paste0( ' addTable(rtf,outTable,col.widths=cWs,col.justify=rep(\'L\',length(outTable)))' ) r_out<-c(r_out,addtab) } #Add Footnote footnote<-codelist$FootCode[i] footnote<-gsub("\\\\n","\n",footnote) if(!is.na(footnote)&&gsub("", " ", footnote)!=''&&substr(footnote,1,5)=='paste') footnote<-eval(parse(text=footnote)) addfoot<-vector() addfoot[1]<-' addNewLine(rtf, n=2)' addfoot[2]<-paste0(' #------Add Footnote ',codelist$order[i],' ------') addfoot[3]<-paste0(' addParagraph(rtf,\"',footnote,'\")') r_out<-c(r_out,addfoot) if(i!=nrow(codelist)){ r_out<-c(r_out,' addPageBreak(rtf,width=11,height=8.5,font.size=8,omi=c(.5,.5,.5,.5))') }else{ r_out<-c(r_out,'\ndone(rtf)\n} #------End of RTF------\n') } } return(paste0(r_out,collapse='\n')) } checkSource<-function(fnm, keyS1='source('){#fnm must be a file under inpath2 rF1<-NULL r1<-readLines(con=fnm) r2<-toupper(gsub(" ", '', r1)) falseKey<-FALSE for(j in 1:length(r1)){ if(grepl('IF(FALSE)', r2[j], fixed=TRUE)|grepl('IF(F)', r2[j], fixed=TRUE)){ falseKey<-TRUE b1<-0 } if(falseKey){ if(gsub("IF(FALSE)","", r2[j],fixed=TRUE)=="[{]"|substr(r2[j],1,1)=="[{]") b1<-b1+1 if(b1==0 & grepl("[{]", r2[j])) falseKey<-FALSE if(grepl("}", r2[j])) { b1<-b1-1 if(b1==0) falseKey<-FALSE } }else{ if(grepl(toupper(keyS1), r2[j], fixed=TRUE)){ f3<-strsplit(r1[j],split='local.path1,', fixed=TRUE)[[1]][2] f3<-gsub("users/","",f3, fixed=TRUE) f3<-gsub("'","",f3, fixed=TRUE) f3<-gsub('"','',f3, fixed=TRUE) f3<-gsub('\"','',f3, fixed=TRUE) f3<-gsub(')','',f3, fixed=TRUE) f3<-gsub('(','',f3, fixed=TRUE) f3<-gsub(' ','',f3, fixed=TRUE) if(grepl(".r", tolower(f3), fixed=TRUE)){ rF1<-c(rF1, f3) } } } } return(rF1) } #-------------Creat Parameters-------------# #use radiobutton, slidebar, checkbox, selectInput if(newWay){ widgets.code<-function(UInames, max.n){ ind<-max.n!=0 check.code<-lapply(max.n['check']:1,function(x){ ret<-'\n output$checkbox_xx<-renderUI({ tmpN<-reactive(which(check.param()$Request.Name==input$analysis)) if(length(tmpN())<1) return(NULL) try(tmp<-eval(parse(text=Vdic()$tmp[AnalyC()]))) if(is.na(check.param()[tmpN(),\'check.label_xx\']) ||class(try(default<-eval(parse(text=check.param()[tmpN(),\'check.default_xx\']))))==\"try-error\" ||class(try(choice<-eval(parse(text=check.param()[tmpN(),\'check.choice_xx\']))))==\"try-error\")return(NULL) if (length(choice)==0)return(div(class=\"alert alert-error\",strong(\'checkbox Options Are Not Available\'))) if (is.na(default))default<-choice checkboxGroupInput(inputId=\'check_xx\',label=strong(check.param()[tmpN(),\'check.label_xx\']),choices=choice,selected=default)})\n\n ' if (x==1){ret<-gsub('_xx','',ret,fixed=TRUE)}else{ret<-gsub('_xx',x,ret,fixed=TRUE)} ret }) check.codes<-Reduce(function(x,y)paste0(x,y,collapse='\n'),check.code) radio.code<-lapply(max.n['radio']:1,function(x){ ret<-'output$radiobutton_xx<-renderUI({ tmpN<-reactive(which(radio.param()$Request.Name==input$analysis)) if(length(tmpN())<1) return(NULL) try(tmp<-eval(parse(text=Vdic()$tmp[AnalyC()]))) if(is.na(radio.param()[tmpN(),\'radio.label_xx\']) ||class(try(default<-eval(parse(text=radio.param()[tmpN(),\'radio.default_xx\']))))==\"try-error\" ||class(try(choice<-eval(parse(text=radio.param()[tmpN(),\'radio.choice_xx\']))))==\"try-error\")return(NULL) if (length(choice)==0)return(div(class=\"alert alert-error\",strong(\'radiobutton Options Are Not Available\'))) if (is.na(default))default<-choice[1] radioButtons(\'radio_xx\',label=strong(radio.param()[tmpN(),\'radio.label_xx\']),choices=choice,selected=default)})\n\n ' if (x==1){ret<-gsub('_xx','',ret,fixed=TRUE)}else{ret<-gsub('_xx',x,ret,fixed=TRUE)} ret }) radio.codes<-Reduce(function(x,y)paste0(x,y,collapse='\n'),radio.code) dropdown.code<-lapply(max.n['dropdown']:1,function(x){ ret<-'output$dropdown_xx<-renderUI({ isolate({ tmpN<-reactive(which(dropdown.param()$Request.Name==input$analysis)) if(length(tmpN())<1) return(NULL) try(tmp<-eval(parse(text=Vdic()$tmp[AnalyC()]))) }) if(is.null(dropdown.param()[tmpN(),\'dropdown.label_xx\'])) return(NULL) if (is.na(dropdown.param()[tmpN(),\'dropdown.label_xx\']) ||class(try(default<-eval(parse(text=dropdown.param()[tmpN(),\'dropdown.default_xx\']))))==\"try-error\" ||class(try(default2<-eval(parse(text=dropdown.param()[tmpN(),\'dropdown.multiple_xx\']))))==\"try-error\" ||class(try(choice<-eval(parse(text=dropdown.param()[tmpN(),\'dropdown.choice_xx\']))))==\"try-error\")return(NULL) if (length(choice)==0)return(div(class=\"alert alert-error\",strong(\'dropdown Options Are Not Available\'))) if (all(is.na(default)))default<-choice[1] if (all(is.na(default2)))default2<-TRUE selectInput(\'dropdown_xx\',label=strong(dropdown.param()[tmpN(),\'dropdown.label_xx\']), choices=choice,selected=default,multiple=default2,selectize=TRUE, width=\"100%\") }) \n\n ' if (x==1){ret<-gsub('_xx','',ret,fixed=TRUE)}else{ret<-gsub('_xx',x,ret,fixed=TRUE)} ret }) dropdown.codes<-Reduce(function(x,y)paste0(x,y,collapse='\n'),dropdown.code) slide.code<<-lapply(max.n['slide']:1,function(x){ ret<-'output$slider_xx<-renderUI({ tmpN<-reactive(which(slide.param()$Request.Name==input$analysis)) if(length(tmpN())<1) return(NULL) try(tmp<-eval(parse(text=Vdic()$tmp[AnalyC()]))) if(is.null(slide.param()[tmpN(),\'slide.label_xx\'])) return(NULL) if (is.na(slide.param()[tmpN(),\'slide.label_xx\']) ||class(try(min<-eval(parse(text=slide.param()[tmpN(),\'slide.min_xx\']))))[1]==\"try-error\" ||class(try(max<-eval(parse(text=slide.param()[tmpN(),\'slide.max_xx\']))))[1]==\"try-error\" ||class(try(default<-eval(parse(text=slide.param()[tmpN(),\'slide.value_xx\']))))[1]==\"try-error\" ||class(try(by<-eval(parse(text=slide.param()[tmpN(),\'slide.by_xx\']))))[1]==\"try-error\")return(NULL) if (length(c(min,max,default,by))<4)return(div(class=\"alert alert-error\",strong(\'slider Options Are Not Available\'))) if (is.na(default))default<-mean(min,max) dw.max<<-max dw.min<<-min dw.by<<-by conditionalPanel(condition=\'true\', sliderInput(\'slide_xx\',label=strong(slide.param()[tmpN(),\'slide.label_xx\']), min=min,max=max,value=default,step=by,animate = TRUE), downloadButton(\"getAnim_slide_xx\",label=\'gif\'), downloadButton(\"getPDF_slide_xx\",label=\'pdf\') ) }) \n\n output$getAnim_slide_xx<-downloadHandler( filename=function(){ tt <- \'currentSliderAnimation.gif\' return(tt) }, content=function(file){ slideAnimFunc <- function(code1){ seq1 <- seq(from=dw.min, to=dw.max, by=dw.by) for(sld1 in seq1){ code2<- gsub(\'input$slide_xx\', sld1, code1) eval(parse(text=code2)) } } codelist<<-Vdic()$PlotCode[AnalyN()[1]] #codelist$width <- codelist$width.x #codelist$height <- codelist$height.x #codelist$res <- codelist$res.x #animation::saveVideo(slideAnimFunc(codelist), video.name=file) owd<-setwd(local.path2) seq1 <- seq(from=dw.min, to=dw.max, by=dw.by) fn.ani1<-dir(local.path2) fn.ani1<-fn.ani1[grepl(\".png\", fn.ani1)] file.remove(fn.ani1) fn.ani<-NULL for(sld1 in seq1){ print(sld1) print( code2<<- gsub(\'input$slide_xx\', sld1, codelist, fixed=T) ) fn.ani <- c(fn.ani, paste0(\'slideAnim\',sld1, \'.png\')) png(paste0(\'slideAnim\',sld1, \'.png\')) try0<-try(eval(parse(text=code2))) if(class(try0)[1]==\'try-error\'){ plot(0~0, col=\'white\', axes=F, ylab=\'\', xlab=\'\') } dev.off() } im.convert(\'slideAnim*.png\', output=file) try(file.remove(fn.ani)) setwd(owd) }) \n\n output$getPDF_slide_xx<-downloadHandler( filename=function(){ tt <- \'currentSlider.pdf\' return(tt) }, content=function(file){ slideAnimFunc <- function(code1){ seq1 <- seq(from=dw.min, to=dw.max, by=dw.by) for(sld1 in seq1){ code2<- gsub(\'input$slide_xx\', sld1, code1) eval(parse(text=code2)) } } codelist<<-Vdic()$PlotCode[AnalyN()[1]] seq1 <- seq(from=dw.min, to=dw.max, by=dw.by) pdf(file, title = paste(\"BEACH Output\", pdf.label), height=tfl.h/tfl.r, width=tfl.w/tfl.r, pointsize = 1/tfl.r ) for(sld1 in seq1){ print(sld1) print( code2<<- gsub(\'input$slide_xx\', sld1, codelist, fixed=T) ) try0<-try(eval(parse(text=code2))) if(class(try0)[1]==\'try-error\'){ plot(0~0, col=\'white\', axes=F, ylab=\'\', xlab=\'\') } } dev.off() }) \n\n' if (x==1){ret<-gsub('_xx','',ret,fixed=TRUE)}else{ret<-gsub('_xx',x,ret,fixed=TRUE)} ret }) slide.codes<-Reduce(function(x,y)paste0(x,y,collapse='\n'),slide.code) date.code<-lapply(max.n['date']:1,function(x){ ret<-'output$date_xx<-renderUI({ tmpN<-reactive(which(date.param()$Request.Name==input$analysis)) if(length(tmpN())<1) return(NULL) try(tmp<-eval(parse(text=Vdic()$tmp[AnalyC()]))) if (is.na(date.param()[tmpN(),\'date.label_xx\']) ||class(try(default<-eval(parse(text="(date.param()[tmpN(),\'date.value_xx\'])"))))==\"try-error\")return(NULL) if (!is.null(default)&is.na(default)) return(div(class=\"alert alert-error\",strong(\'date Options Are Not Available\'))) dateInput(\'date_xx\',label=strong(date.param()[tmpN(),\'date.label_xx\']), value=default, format = \"yyyy-mm-dd\")})\n\n' if (x==1){ret<-gsub('_xx','',ret,fixed=TRUE)}else{ret<-gsub('_xx',x,ret,fixed=TRUE)} ret }) date.codes<-Reduce(function(x,y)paste0(x,y,collapse='\n'),date.code) dateR.code<-lapply(max.n['dateR']:1,function(x){ ret<-'output$dateR_xx<-renderUI({ tmpN<-reactive(which(dateR.param()$Request.Name==input$analysis)) if(length(tmpN())<1) return(NULL) try(tmp<-eval(parse(text=Vdic()$tmp[AnalyC()]))) if (is.na(dateR.param()[tmpN(),\'dateR.label_xx\']) ||class(try(min<-eval(parse(text="(dateR.param()[tmpN(),\'dateR.start_xx\'])"))))==\"try-error\" ||class(try(max<-eval(parse(text="(dateR.param()[tmpN(),\'dateR.end_xx\'])"))))==\"try-error\") return(NULL) if ((!is.null(min)&is.null(max))&(is.na(min)&is.na(max))) return(div(class=\"alert alert-error\",strong(\'data range Options Are Not Available\'))) dateRangeInput(\'dateR_xx\',label=strong(dateR.param()[tmpN(),\'dateR.label_xx\']), start=min, end=max, format = \"yyyy-mm-dd\")})\n\n' if (x==1){ret<-gsub('_xx','',ret,fixed=TRUE)}else{ret<-gsub('_xx',x,ret,fixed=TRUE)} ret }) dateR.codes<-Reduce(function(x,y)paste0(x,y,collapse='\n'),dateR.code) num.code<-lapply(max.n['num']:1,function(x){ ret<-'output$num_xx<-renderUI({ tmpN<-reactive(which(num.param()$Request.Name==input$analysis)) if(length(tmpN())<1) return(NULL) try(tmp<-eval(parse(text=Vdic()$tmp[AnalyC()]))) if (is.na(num.param()[tmpN(),\'num.label_xx\']) ||class(try(default<-eval(parse(text="num.param()[tmpN(),\'num.value_xx\']"))))==\"try-error\")return(NULL) if (is.na(default)) return(div(class=\"alert alert-error\",strong(\'numericInput Options Are Not Available\'))) numericInput(\'num_xx\',label=strong(num.param()[tmpN(),\'num.label_xx\']), value=default)})\n\n' if (x==1){ret<-gsub('_xx','',ret,fixed=TRUE)}else{ret<-gsub('_xx',x,ret,fixed=TRUE)} ret }) num.codes<-Reduce(function(x,y)paste0(x,y,collapse='\n'),num.code) text.code<-lapply(max.n['text']:1,function(x){ ret<-'output$text_xx<-renderUI({ tmpN<-reactive(which(text.param()$Request.Name==input$analysis)) if(length(tmpN())<1) return(NULL) try(tmp<-eval(parse(text=Vdic()$tmp[AnalyC()]))) if (is.na(text.param()[tmpN(),\'text.label_xx\']) ||class(try(default<-eval(parse(text=text.param()[tmpN(),\'text.value_xx\']))))==\"try-error\")return(NULL) if (is.na(default)) return(div(class=\"alert alert-error\",strong(\'textInput Options Are Not Available\'))) textInput(\'text_xx\',label=strong(text.param()[tmpN(),\'text.label_xx\']), value=default)})\n\n' if (x==1){ret<-gsub('_xx','',ret,fixed=TRUE)}else{ret<-gsub('_xx',x,ret,fixed=TRUE)} ret }) text.codes<-Reduce(function(x,y)paste0(x,y,collapse='\n'),text.code) textbox.code<-lapply(max.n['textbox']:1,function(x){ ret<-paste0('output$textbox_xx<-renderUI({ tmpN<-reactive(which(textbox.param()$Request.Name==input$analysis)) try(tmp<-eval(parse(text=Vdic()$tmp[AnalyC()]))) if(is.na(textbox.param()[tmpN(),\'textbox.label_xx\']))return(NULL) cols<-eval(parse(text=textbox.param()[tmpN(),\'textbox.cols_xx\'])) rows<-eval(parse(text=textbox.param()[tmpN(),\'textbox.rows_xx\'])) default<-textbox.param()[tmpN(),\'textbox.default_xx\'] label<-textbox.param()[tmpN(),\'textbox.label_xx\'] if(is.na(cols)||is.null(cols))cols<-40 if(is.na(rows)||is.null(rows))rows<-2 texttmp<-paste0(\'<h6>\',label,\'</h6>\n<textarea name=\"\',textbox_xx,\'\" rows=\"\',rows,\'\" cols=\"\',cols,\'\">\',default,\'</textarea>\') return(shiny::HTML(texttmp)) })\n\n') if (x==1){ret<-gsub('_xx','',ret,fixed=TRUE)}else{ret<-gsub('_xx',x,ret,fixed=TRUE)} ret }) textbox.codes<-Reduce(function(x,y)paste0(x,y,collapse='\n'),textbox.code) widgets.code<-paste0(c(check.codes,radio.codes,dropdown.codes,slide.codes, date.codes, dateR.codes, num.codes, text.codes, textbox.codes)[ind], collapse='\n\n') return(widgets.code) } } widgets.order<<-function(analysis, UIdic1, UInames, ncol.widg=NULL){ # print(UIdic1) # print(UInames) # print(analysis) if(is.null(ncol.widg)){ncol.widg<-1} input.names<-as.vector(t(UIdic1[UIdic1$Request.Name==analysis, UInames])) if(length(input.names)==0){ widg.list=NULL }else{ input.labs<-as.vector(t(UIdic1[UIdic1$Request.Name==analysis, gsub("uiInput", "uilab", UInames, fixed=TRUE)])) #names(input.names)<-1:length(input.names) s_1<-!is.na(input.names) input.names<-input.names[s_1]#unique(setdiff(as.vector(input.names),NA)) input.labs<-input.labs[s_1] input.labs[is.na(input.labs)]<-"" widg.list<-unlist(strsplit(input.names,'input$',fixed=TRUE)) sel0<-widg.list!='' & !is.na(widg.list) input.names<-widg.list<-widg.list[sel0] #input.labs<-input.labs[sel0] widg.list<-gsub('check','checkbox',widg.list) widg.list<-gsub('radio','radiobutton',widg.list) widg.list<-gsub('dropdown','dropdown',widg.list) widg.list<-gsub('slide','slider',widg.list) # widg.list<-gsub('date','date',widg.list) # widg.list<-gsub('dateR','dateR',widg.list) # widg.list<-gsub('num','num',widg.list) # widg.list<-gsub('text','text',widg.list) # widg.list<-gsub('textbox','textbox',widg.list) } if(length(widg.list)==0){ widg.code<-'return(NULL)'; input.names<-input.labs<-NA }else{ if(F){ widg.code<-paste0('uiOutput(\'',widg.list,'\')',collapse=',') widg.code<-paste0('return(conditionalPanel(condition=\'true\', div(', widg.code,')))',collapse='') }else{ widg.code<-paste0('uiOutput(\'',widg.list,'\')') #,collapse=',' w.widg<-floor(12/ncol.widg) #upto 4, column width nrow.widg<-ceiling(length(widg.code)/ncol.widg)#number of rows widg.code2<-NULL for(i in 1:nrow.widg){ widg.code3<-NULL for(j in 1:ncol.widg){ ij<-(i-1)*ncol.widg+j if(ij <= length(widg.code)){ wij<-paste0("column(", w.widg,", ", widg.code[ij], ", offset=", 0, ")") #max(w.widg*(j-1)-2,0) widg.code3<-paste0(c(widg.code3, wij), collapse=",") } } widg.code2<-c(widg.code2, paste0("fluidRow(", widg.code3, ")")) } widg.code<-paste0(widg.code2, collapse=',') widg.code<-paste0('return(conditionalPanel(condition=\'true\', div(', widg.code,')))',collapse='') } } out1<-data.frame(code=widg.code,names=input.names,labs=input.labs) return(out1) } widgets.param<-function(uidic, wid, max.n){ if(!wid %in% names(max.n)){ return(NA) }else{ temp<-lapply(setdiff(unique(uidic$Request.Name),NA),function(x){ row_sel<-uidic$Request.Name==x ret<-unique(uidic[which(row_sel), grepl(wid,colnames(uidic))]) ret$Request.Name<-x #dfnames is the widget name which default values not specified in CD wid2<-wid[!wid%in%c("num","text")] if(length(wid2)>0){ dfnames<-c(paste0(wid2,'.default',c(max.n[wid2]:2, ''))) dfnames<-dfnames[!dfnames%in%colnames(uidic)] if (length(dfnames)>0){ dfs<-matrix(NA,nrow=nrow(ret),ncol=length(dfnames)) colnames(dfs)<-dfnames ret2<-data.frame(ret,dfs,row.names=NULL) }else{ ret2<-data.frame(ret,row.names=NULL)} }else{ ret2<-data.frame(ret,row.names=NULL)} #dfnames3 is the dropdown widget name which multiple not specified in CD wid3<-wid2[grepl("dropdown",wid2)] if(length(wid3)>0){ dfnames3<-c(paste0(wid3,'.multiple',c(max.n[wid3]:2, ''))) dfnames3<-dfnames3[!dfnames3%in%colnames(uidic)] if (length(dfnames3)>0){ dfs<-matrix(NA,nrow=nrow(ret2),ncol=length(dfnames3)) colnames(dfs)<-dfnames3 ret3<-data.frame(ret2,dfs, row.names=NULL) }else{ ret3<-data.frame(ret2,row.names=NULL) } }else{ ret3<-data.frame(ret2,row.names=NULL) } return(ret3) }) #convert the list object to data.frame ret0<-Reduce(function(x,y){unique(rbind(x,y))},temp) return(ret0) } } #-------------Functions for RTF output setup-------------# if(TRUE){ col_width <- function(tb){ #Function to Generate rtf table column widths cws <- NULL for(i in 1:length(names(tb))) { ncName <- nchar(names(tb)[i]) ncString <- max(nchar(tb[,i])) nc <- max(ncName, ncString) cw <- nc*0.89/10 # assume 10 characters per an inch cws <- c(cws, cw) } return(cws) } #--- convert factor to character colname convert_fac_to_char <- function(dat) { for(i in 1:ncol(dat)) { if(class(dat[, i]) == "factor") dat[, i] <- as.character(dat[, i]) } return(dat) } .convert <- function (x) { x <- gsub("\\n", " \\\\line ", x) x <- gsub("<=", "\\\\u8804\\\\3", x) x <- gsub(">=", "\\\\u8805\\\\3", x) x <- gsub("&gt;", ">", x) x <- gsub("&lt;", "<", x) x <- gsub("&Alpha;", "\\\\u0913\\\\3", x) x <- gsub("&Beta;", "\\\\u0914\\\\3", x) x <- gsub("&Gamma;", "\\\\u0915\\\\3", x) x <- gsub("&Delta;", "\\\\u0916\\\\3", x) x <- gsub("&Epsilon;", "\\\\u0917\\\\3", x) x <- gsub("&Zeta;", "\\\\u0918\\\\3", x) x <- gsub("&Eta;", "\\\\u0919\\\\3", x) x <- gsub("&Theta;", "\\\\u0920\\\\3", x) x <- gsub("&Iota;", "\\\\u0921\\\\3", x) x <- gsub("&Kappa;", "\\\\u0922\\\\3", x) x <- gsub("&Lambda;", "\\\\u0923\\\\3", x) x <- gsub("&Mu;", "\\\\u0924\\\\3", x) x <- gsub("&Nu;", "\\\\u0925\\\\3", x) x <- gsub("&Xi;", "\\\\u0926\\\\3", x) x <- gsub("&Omicron;", "\\\\u0927\\\\3", x) x <- gsub("&Pi;", "\\\\u0928\\\\3", x) x <- gsub("&Rho;", "\\\\u0929\\\\3", x) x <- gsub("&Sigma;", "\\\\u0931\\\\3", x) x <- gsub("&Tau;", "\\\\u0932\\\\3", x) x <- gsub("&Upsilon;", "\\\\u0933\\\\3", x) x <- gsub("&Phi;", "\\\\u0934\\\\3", x) x <- gsub("&Chi;", "\\\\u0935\\\\3", x) x <- gsub("&Psi;", "\\\\u0936\\\\3", x) x <- gsub("&Omega;", "\\\\u0937\\\\3", x) x <- gsub("&alpha;", "\\\\u0945\\\\3", x) x <- gsub("&beta;", "\\\\u0946\\\\3", x) x <- gsub("&gamma;", "\\\\u0947\\\\3", x) x <- gsub("&delta;", "\\\\u0948\\\\3", x) x <- gsub("&epsilon;", "\\\\u0949\\\\3", x) x <- gsub("&zeta;", "\\\\u0950\\\\3", x) x <- gsub("&eta;", "\\\\u0951\\\\3", x) x <- gsub("&theta;", "\\\\u0952\\\\3", x) x <- gsub("&iota;", "\\\\u0953\\\\3", x) x <- gsub("&kappa;", "\\\\u0954\\\\3", x) x <- gsub("&lambda;", "\\\\u0955\\\\3", x) x <- gsub("&mu;", "\\\\u0956\\\\3", x) x <- gsub("&nu;", "\\\\u0957\\\\3", x) x <- gsub("&xi;", "\\\\u0958\\\\3", x) x <- gsub("&omicron;", "\\\\u0959\\\\3", x) x <- gsub("&pi;", "\\\\u0960\\\\3", x) x <- gsub("&rho;", "\\\\u0961\\\\3", x) x <- gsub("&sigmaf;", "\\\\u0962\\\\3", x) x <- gsub("&sigma;", "\\\\u0963\\\\3", x) x <- gsub("&tau;", "\\\\u0964\\\\3", x) x <- gsub("&upsilon;", "\\\\u0965\\\\3", x) x <- gsub("&phi;", "\\\\u0966\\\\3", x) x <- gsub("&chi;", "\\\\u0967\\\\3", x) x <- gsub("&psi;", "\\\\u0968\\\\3", x) x <- gsub("&omega;", "\\\\u0969\\\\3", x) x <- gsub("TRUE", "Yes", x) x <- gsub("FALSE", "No", x) x } .get.space.before.after <- function (space.before = NULL, space.after = NULL) { ret <- "" if (!is.null(space.before)) { ret <- paste(ret, "\\sb", (space.before * 1440), sep = "") } if (!is.null(space.after)) { ret <- paste(ret, "\\sa", (space.after * 1440), sep = "") } ret } .add.table.row <- function (col.data = c("c1", "c2", "c3"), col.widths = c(1, 4.5, 1), col.justify = NULL, font.size = 10, last.row = FALSE, indent = 0, border.top = FALSE, border.bottom = FALSE, space.before = NULL, space.after = NULL) { header <- paste("\\trowd\\trgaph100\\trleft", indent, sep = "") if (length(col.data) != length(col.widths)) { stop(paste("The number of data columns (", length(col.data), ") doesn't match the column widths (", length(col.widths), ")! Input data: ", col.data, sep = "")) } justify <- vector() justify["L"] <- "\\ql" justify["R"] <- "\\qr" justify["C"] <- "\\qc" justify["J"] <- "\\qj" justify.v <- rep(justify["L"], length(col.data)) numeric.cols <- which(!is.na(suppressWarnings(as.numeric(col.data)))) if (length(numeric.cols) > 0) { justify.v[numeric.cols] <- justify["R"] } if (!is.null(col.justify)) { if (length(col.justify) == 1) { if (col.justify %in% names(justify)) { justify.v <- rep(justify[col.justify], length(col.data)) } else { stop(paste("col.justify parameter not recognized: ", col.justify, " (should be L, R, C, or J)", sep = "")) } } else if (length(col.justify) == length(col.data)) { justify.v <- justify[col.justify] } else { stop(paste("The number of data columns (", length(col.data), ") doesn't match the col.justify (", length(col.justify), ") parameter! Input data: ", paste(col.data, sep = "", collapse = ", "), sep = "")) } } btop <- "" bbottom <- "" if (any(border.top)) # btop <- sapply(border.top, ifelse, "\\clbrdrt\\brdrs\\brdrw15",'') # make border.top as a vector option if (last.row == TRUE | any(border.bottom)) # bbottom <- sapply(border.bottom, ifelse, "\\clbrdrb\\brdrs\\brdrw15",'') #make border.bottom as a vector option cols.prefix <- paste("\\clvertalt\\clshdrawnil\\clwWidth", round(col.widths * 1440, 0), "\\clftsWidth3\\clheight260\\clpadl100\\clpadr100\\gaph", btop, bbottom, "\\cellx", c(1:length(col.widths)), "\n", sep = "", collapse = "") cols <- paste("\\pard", justify.v, .get.space.before.after(space.before, space.after), "\\widctlpar\\intbl\\fi0\\f2\\fs", font.size * 2, " ", .convert(col.data), "\\cell\n", sep = "", collapse = "") end.row <- "\\widctlpar\\intbl\\row\n" paste(header, cols.prefix, cols, end.row, sep = "") } # add width basing on duplication adj.width <- function(x, cw, space=1){ ret <- array(0, dim=dim(x)) x2 <- x #dup <- t(apply(x,1, function(x) duplicated(x)& x!='')) dup <- t(apply(x,1, function(x) c(FALSE, x[-1]==x[-length(x)]))) for (i in 1:nrow(x)) { for (j in ncol(x):1) { if (i > 1 & j <= ncol(x)) if (!dup[i-1,j]) dup[i,j] <- FALSE if (dup[i,j]) { ret[i,j-1] <- ret[i,j]+space*cw[j] ret[i,j ] <- -space*cw[j] x2[i,j] <- '' } } ret[i,] <- ret[i,]+cw } list(x=x2, cw=ret) } ###--- This one is added/modified a little bit from the original rtf.tab that Michael Man developed # It expanded the width for header or footnote rtf.tab <- function(dat,cw=NULL,titles,col.just=NULL,var.ul,prd.status='QA',footns='',header=FALSE,footer=FALSE, nline.body=40, addSpaceHeader=0, addSpaceFoot=0, page.disp=TRUE,...) { # almost automated w/ modified .add.table.row st <- attributes(dat)$'start cell'[1] hd <- 1:(st-1) if(is.null(cw)) cw <- c(1.5,rep(.7,ncol(dat)-1)) if(is.null(col.just)) col.just <- rep('R', nrow(dat)) if(is.null(dim(col.just))) col.just <- matrix(rep(col.just,ncol(dat)), nrow=nrow(dat), byrow=FALSE) x <- dat cw2 <- matrix(rep(cw, nrow(x)), ncol=ncol(x), byrow=TRUE) if (st > 2) { #undebug(adj.width) y <- adj.width(x=dat[hd,],cw=cw, space=1) x[hd,] <- y$x cw2[hd,] <- y$cw } #expr=expression({ rtf.add.row <- function(rows=1:nrow(x)){ ret <- "{\\pard\n" for (i in rows) if (i <= nrow(x)){ sel <- which(cw2[i,]>0) ret <- paste(ret, .add.table.row( col.data = x[i,sel], col.widths = cw2[i,sel], col.justify = col.just[i,sel], font.size = fs, border.top = i %in% c(1), border.bottom = if (i > st-2) i %in% c(st-1,nrow(x),max(rows)) else x[i,sel] %in% var.ul ), sep='') if (i < st) if (!all(cw2[i,] == cw2[i+1,])) ret <- paste(ret,'{\\pard\\par}','', sep='') } ret <- paste(ret, "}\n\n", sep = "") rtf$.rtf <- paste(rtf$.rtf, ret, sep='') } #}) rtf <- RTF(...) fs <- rtf$.font.size rtf$.rtf <- gsub('Times New Roman', 'Courier New', rtf$.rtf) # make "Courier New" as default rtf$.rtf <- gsub('field{\\fldinst{page}}', '', rtf$.rtf, fixed=TRUE) # delete page number #nline.body <- 2 npage <- ceiling((nrow(x)-st+1)/nline.body) #addHeader(rtf,title=titles[[1]],subtitle=titles[[2]]) #systems <- c('Page \\chpgn of {\\field{\\*\\fldinst NUMPAGES }}', systems <- c(ifelse(page.disp==TRUE, paste('Page \\chpgn of ', npage, sep=''), ""), format(Sys.time(), "%H:%M %d%b%Y"), prd.status) #systems <- c(paste('Page \\chpgn of ', npage, sep=''), # format(Sys.time(), "%H:%M %d%b%Y"), # prd.status) hd.m <- c(paste(titles, collapse='\\line '), paste(systems, collapse='\\line ')) # main header tmp <- .add.table.row( col.data = hd.m, col.widths = c(sum(cw)-2+addSpaceHeader,2), col.justify = c('L', 'R'), font.size = fs) tmp2 <- .add.table.row( col.data = paste(footns, collapse='\\line '), col.widths = sum(cw)+addSpaceFoot, col.justify = 'L', font.size = fs) if (FALSE) rtf$.rtf <- paste(rtf$.rtf, "{\\header\\pard", "\\fi0\\f2\\fs", fs*2, "\\qr Page \\chpgn of {\\field{\\*\\fldinst NUMPAGES }}\\par}", sep='') for (i in 1:npage){ rtf$.rtf <- paste(rtf$.rtf, ifelse(i==1,'','\\page'), '{\\pard\\par}', ifelse(header,'{\\header',''), tmp, ifelse(header,'}',''), '{\\pard\\par}', sep='') #startParagraph(rtf) #eval(expr) rtf.add.row(rows=c(1:(st-1), 1:nline.body-1+st+nline.body*(i-1))) #endParagraph(rtf) rtf$.rtf <- paste(rtf$.rtf, '{\\pard\\par}', ifelse(footer,'\\footer',''), tmp2, sep='') } done(rtf) }#end rtf.tab #--- produce to rtf file that as SAS output. It can be used for single table or table with multiple pages rtf_table_out_as_sas <- function(rtf, tb, cw=NULL, colFormat=c(rep("L", 1), rep("C",1), rep("R",1)), cell1=2, cell2=1, nheader=1, varName=NULL, var.ul='', prd.status=' ', #'QA', titles="", footns="", header=FALSE, footer=FALSE, nline.body=30, height=8.5, width=11, omi=c(1,1,1,1), addSpaceHeader=0, addSpaceFoot=0, page.disp=TRUE, ...) { # rtf: RTF object that is just needed to be declared once before calling the function # tb: table out # cw: column width # colFormat: alignment (left, center, or right) for each column # varName: variable name that want to be repeated when go to the next page # var.ul: pre-specified cell values that indicate the bottom line in a table # nline.body: number of lines per page # addSpaceFoot, addSpaceHeader: expand the width of header or footnotes # page.disp: whether diplay page number #--- generate blank pape (break page) if the data is more than a page if(nrow(tb) > nline.body) { idx <- seq(1, nrow(tb), by = nline.body) idx.n <- c(seq(nline.body, nrow(tb), by = nline.body), nrow(tb)) }else { idx <- 1 idx.n <- nrow(tb) } npage <- length(idx) for(k in 1:length(idx)) { subTable <- tb[idx[k]:idx.n[k], ] if(is.null(nrow(subTable))){ subTable <- data.frame(` `=subTable) } #--- if nrow < nline.body, need adding some spaces to move footnotes to bottom of the page if(nrow(subTable) < nline.body) { addData <- data.frame(matrix("",ncol=ncol(subTable), nrow=nline.body-nrow(subTable)-1)) names(addData) <- names(subTable) subTable <- rbind(subTable, addData) } #-- get values that will be in the 1st row of next page rownames(subTable) <- 1:nrow(subTable) #-- check if the last row of previous page with varName not matched the 1st row of next page if(k==1) string.val <- NULL if(k!=1 & !all(unique(subTable[1,varName]) %in% "") & !all(unique(subTable[1,varName]) %in% string.val)) string.val <- unique(subTable[1,varName]) if(k==1 & all(tb[nrow(subTable)+1, varName] %in% "")) { for(m in 1:nrow(subTable)) if(all(!subTable[m,varName] %in% "")) string.val <- subTable[m, varName] } else if(!all(tb[nrow(subTable)+1, varName] %in% "")) { string.val <- NULL } else { #-- add last row of previous page to 1st row of next page if(!is.null(string.val)) subTable[1, varName] <- string.val for(m in 1:nrow(subTable)) if(all(!subTable[m,varName] %in% "")) string.val <- subTable[m, varName] } hd <- sapply(colnames(subTable), function(x) strsplit(x, '; ')[[1]]) ret <- rbind(hd, as.matrix(subTable)) colnames(ret) <- 1:ncol(ret) rownames(ret) <- 1:nrow(ret) ret2 <- ret colnames(ret2) <- 1:ncol(ret2) rownames(ret2) <- 1:nrow(ret2) attributes(ret2) <- list(dim = dim(ret2), dimnames = dimnames(ret2), `start cell` = c(cell1, cell2)) col.just <- matrix(c(rep(colFormat, nrow(ret2) + nheader)), ncol=ncol(ret2), byrow=TRUE) dat <- ret2 st <- attributes(dat)$'start cell'[1] hd <- 1:(st-1) if(is.null(cw)) cw <- c(2.5, rep(1.5,ncol(dat)-1)) x <- dat cw2 <- matrix(rep(cw, nrow(x)), ncol=ncol(x), byrow=TRUE) if (st > 2) { y <- adj.width(x=dat[hd,],cw=cw, space=1) x[hd,] <- y$x cw2[hd,] <- y$cw } rtf.add.row <- function(rows=1:nrow(x)){ ret <- "{\\pard\n" for (i in rows) if (i <= nrow(x)){ sel <- which(cw2[i,]>0) ret <- paste(ret, .add.table.row( col.data = x[i,sel], col.widths = cw2[i,sel], col.justify = col.just[i,sel], font.size = fs, border.top = i %in% c(1), border.bottom = if (i > st-2) i %in% c(st-1,nrow(x),max(rows)) else x[i,sel] %in% var.ul #x is the subtable with header ), sep='') if (i < st) if (!all(cw2[i,] == cw2[i+1,])) ret <- paste(ret,'{\\pard\\par}','', sep='') } ret <- paste(ret, "}\n\n", sep = "") rtf$.rtf <- paste(rtf$.rtf, ret, sep='') } rtf <- rtf fs <- rtf$.font.size rtf$.rtf <- gsub('Times New Roman', 'Courier New', rtf$.rtf) # make "Courier New" as default rtf$.rtf <- gsub('field{\\fldinst{page}}', '', rtf$.rtf, fixed=TRUE) # delete page number tmp2 <- .add.table.row( col.data = paste(footns, collapse='\\line '), col.widths = sum(cw)+addSpaceFoot, col.justify = 'L', font.size = fs) rtf.add.row(rows=c(1:(st-1), 1:nline.body-1+st)) rtf$.rtf <- paste(rtf$.rtf, '{\\pard\\par}', ifelse(footer,'\\footer',''), tmp2, sep='') } #end of the for loop return(rtf) }#end rtf_table_out_as_sas } #-------------Manually Convert R object into HTML code-------------# df2html<-function( #convert a table into part of HTML code datF, #a data.frame for table output tabTit="", #table title fnote=NULL, #footnote ind=1 ){ datF<-as.data.frame(datF) dim1<-dim(datF) nr<-dim1[1] nc<-dim1[2] cnm<-colnames(datF) rnm<-rownames(datF) #currently the rownames would not be printed out. out<-paste0('<a name=\"IDX',ind,'\"></a>') out<-c(out, '<div align=\"left\">') tabSum2<-paste0('<table class=\"Table\" cellspacing=\"1\" cellpadding=\"', nc+2, '\" rules=\"groups\" frame=\"box\" border=\"1\" bordercolor=\"#000000\" ', 'summary=\"', tabTit, '\" >') #style="table-layout: fixed; width: 100%" out<-c(out, tabSum2, '<colgroup>', rep('<col>',nc), '</colgroup>', '<thead>') #For table header tabHead<-c('<tr>', paste0('<td class="l NoteContent" colspan=\"', nc, '\">', tabTit, '<br>', paste(rep("-",138),collapse=''), '</td>'), '</tr>', '<tr>') for(i in 1:nc){ tabHead<-c(tabHead, paste0('<th class=\"c b Header\" scope=\"col\">', cnm[i], '</th>')) } out<-c(out, tabHead, '</tr>', '</thead>', '<tbody>') #for table body tabBody<-NULL for(j in 1:nr){ tabBody<-c(tabBody, '<tr>') for(i in 1:nc){ tabBody<-c(tabBody, paste0('<td class=\"l Data\">', datF[j,i], '</td>')) } tabBody<-c(tabBody, '</tr>') } out<-c(out, tabBody, '</tbody>', '<tfoot>', '<tr>') out<-c(out, paste0('<td class=\"l NoteContent\" colspan=\"',nc,'\">', paste(rep("-",138),collapse=''), '<br>', fnote, '</td>'), '</tr>', '</tfoot>') out<-c(out, '</table>', '</div>', '<p style="page-break-after: always;"><br></p><hr size="3">') return(out) } fig2html<-function( #convert a png figure into part of HTML code figNm='plot.png', # the png file name figTit="", #figure title figH="480", figW="640", fnote=NULL, #footnote ind=1 ){ out<-paste0('<a name=\"IDX',ind,'\"></a>') figTit1<-c('<div align=\"left\">', paste0('<table class=\"Table\" cellspacing=\"1\" cellpadding=\"1', '\" rules=\"groups\" frame=\"box\" border=\"1\" bordercolor=\"#000000\" ', 'summary=\"', figTit, '\" >'), '<colgroup>','<col>', '</colgroup>', '<thead>', '<tr>' ) out<-c(out, figTit1, paste0('<td class=\"l NoteContent\" colspan=\"1\">', figTit, '</td>'), '</tr>', '</thead>', '<tbody>', '<tr>' ) out<-c(out, '<td>', paste0('<img alt=\" \" src=\"', figNm, '\" style=\" height: ', figH, 'px; width: ', figW, 'px;\" border=\"0\">'), '</td>', '</tr>', '</tbody>','<tfoot>','<tr>') out<-c(out, paste0('<td class=\"l NoteContent\" colspan=\"1\">',fnote, '</td>'), '</tr>', '</tfoot>') out<-c(out, '</table>', '</div>', '<p style="page-break-after: always;"><br></p><hr size="3">') return(out) } cLink<-function( #generate a link in content table tit="tmplink", ind=1 ){ out<-'<li class=\"ContentItem\">' out<-c(out, '<span><b>&#183;</b><a href=\"', paste0('body.htm#IDX', ind,'\" target=\"body\">',tit,'</a>'), '</span><br></li>') return(out) } #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~# #revise a html table code #make it into multi-level header toMultH <- function( tbc, # a vector of html table code split1=";" ){ wh.h <- grep('<th>', tbc) if(length(wh.h)>1){return(tbc)} tbc.h <- tbc[1:(wh.h-1)] if(wh.h==length(tbc)){return(tbc)} tbc.b <- tbc[(wh.h+1):length(tbc)] hh <- tbc[wh.h] hh <- gsub("<th>", "", hh, fixed=TRUE) hh <- gsub("<tr>", "", hh, fixed=TRUE) hh <- gsub("</tr>", "", hh, fixed=TRUE) hh <- strsplit(hh, split="</th>")[[1]] hh <- hh[-length(hh)] #remove the last empty element hh <- strsplit(hh, split=split1, fixed=TRUE) hh.l <- sapply(hh, length) short <- hh.l<max(hh.l) hh[short] <- lapply(hh[short], function(x){ c(x, rep(" ", max(hh.l)-length(x)))}) hh3 <-matrix(unlist(hh), nrow=max(hh.l)) hh3 <- apply(hh3, 1, function(x){ r1 <- "<tr> <th colspan=\'" colspan <- 1 if(length(x)>1){ for(i in 1:(length(x)-1)){#requre ncol for the table is 2+ if( gsub(" ", "", x[i])==gsub(" ", "", x[i+1])){ colspan <- colspan + 1 }else { r1 <- paste(r1, colspan, "\'>", x[i], "</th> <th colspan=\'") colspan <- 1 } } } r1 <- paste(r1, colspan, "\'>", x[length(x)], "</th> </tr>'") return(r1) #<th colspan='2'> }) return(c(tbc.h, hh3, tbc.b)) } #----------UI Functions------------------# #select color function selectInput_color <- function(id='wpColor', label='Background color', choices=colors(), selected='azure3', HEX=HEXColors){ code <- paste0("<div class=\"form-group shiny-input-container\">\n", "<label class=\"control-label\" for=\"", id, "\">", label, ":</label>\n<div>\n", "<select id=\"", id, "\"><option value=\"", selected, "\" selected>", selected, "</option>\n") for(i in 1:length(choices)){ code <- paste0(code, "<option value=\"", choices[i], "\" style=\"background-color: ", HEX[choices[i]], "\">", choices[i], "</option>\n") } code <- paste0(code, "</select>", "<script type=\"application/json\" data-for=\"", id, "\" data-nonempty=\"\">{}</script> \n</div>\n</div> ") return(code) } #Function to create Table with checkboxes checkboxTableInput <- function(df,table.id="checktable",id.name, checked, check.name,labels=NULL, showSelectedOnly=FALSE ){ table_head0<-capture.output(print(xtable(df[0,]), type="html", include.rownames=F,include.colnames=T)) table_head0[3]<-"<table border=1 class=\"table table-bordered\">" table_head <- paste(table_head0, collapse=" ") table_head <- gsub("</TABLE>", "", table_head) table_head <- gsub("</table>", "", table_head) table_head <- gsub("<table", paste0("<table id=\"",table.id,"\""), table_head) table_head<- gsub('<TR>','<tr>',table_head) table_head<- gsub('</TR>','</tr>',table_head) table_head <- gsub("<tr>", paste("<tr> <th> ", check.name, " </th>", sep=""), table_head) table_body <- paste(capture.output(print(xtable(df), type="html", content.only=T, include.rownames=F, include.colnames=F)), collapse=" ") table_body<- gsub('<TR>','<tr>',table_body) table_body<- gsub('</TR>','</tr>',table_body) table_body<- gsub('<TD>','<td>',table_body) table_body<- gsub('</TD>','</td>',table_body) table_body<- gsub('</tr>','',table_body) table_body<- gsub('</table>','',table_body) which.tag <- regexpr("<tr>", table_body)[1] table_body <- substr(table_body, which.tag, nchar(table_body)) table_body2 <- unlist(strsplit(table_body, "<tr>", fixed=T)) # print(table_body2) table_body3 <- '' #table_body2[1] if(showSelectedOnly){ for (i in 1:nrow(df)){ if(checked[i]){ check_tag <- paste("<tr> <td align=left>", as.character(checkboxInput(paste0(id.name,'_',i), "", checked[i])), " </td>", sep="") table_body3<-paste(table_body3, check_tag, table_body2[i+1], "</tr>", sep="") } } }else{ for (i in 1:nrow(df)){ check_tag <- paste("<tr> <TD align=left>", as.character(checkboxInput(paste0(id.name,'_',i), "", checked[i])), " </td>", sep="") table_body3<-paste(table_body3, check_tag, table_body2[i+1], "</tr>", sep="") } } table_out <- paste(table_head, table_body3, "</table>", collapse=" ") if (!is.null(labels)){ for (k in 1:length(labels)){ table_out<-gsub(paste0('<th> ',colnames(df)[k],' </th>'), paste0('<th> ',labels[k],' </th>'), table_out) } } # print(table_out) return(table_out) } #-------------Create Tabs-------------# tabs<-function(tab.id,tab.label,tab.value){ tabset<-unique(cbind(tab.label,tab.value)) tabcode1<-paste0('<div class=\"tabbable tabs-above\">\n', '<ul class=\"nav nav-tabs shiny-tab-input\" id=\"', tab.id,'\">\n<li class=\"active\">\n') tabcode2<-paste0('<a href=\"#tab-',tab.id,'-',1:nrow(tabset), '\" data-toggle=\"tab\" data-value=\"', tabset[,1],"\">",tabset[,2],"</a>\n</li>\n<li>\n") tabcode2[length(tabcode2)]<-gsub('<li>','</ul>',tabcode2[length(tabcode2)]) tabcode3<-"<div class=\"tab-content\">" tabcode4<-paste0('<div class=\"tab-pane active\" data-value=\"', tabset[,1],'\" id=\"tab-',tab.id,'-',1:nrow(tabset), '\"></div>\n',collapse=" ") tabcode5<-'</div>\n</div>' tabcode<-paste0(tabcode1,paste0(tabcode2,collapse=" "), tabcode3,tabcode4,tabcode5,collapse=" ") return(tabcode) } #-------------side panel data input-------------# inlinetext<-function(text.id,text.label,text.value, note=NULL){ if(is.null(note)){ nt <- "" }else { nt <- paste0('<h6 style=\"width:50%\">', note, ' </h6>') } if(FALSE){ #using textInput widget code <- paste0( "<div class = \"form-group shiny-input-container\", style = \"width:100%\">", paste0("<label for=\"", text.id, "\">", text.label, "</label>"), paste0("<input id=\"", text.id, "\" type=\"text\" class=\"form-control\" value=\"", text.value, "\"/>"), "</div>", collapse='\n' ) } else { #using traditional widget code<-paste0( '<div class=\"input-prepend\" style=\"width:100%\">', paste0('<span class=\"add-on\" >',text.label,'</span>'), paste0('<input style=\"width:50%\" id=\"',text.id, '\" class=\"form-control\" value=\"',text.value,'\" type=\"text\" />\n'), nt, '</div>', collapse='\n') } return(code) } #-------------For output R code-------------# runcode<-function(codelist, # merged dataset of loa and configuration file datPath, # dataset path from input outPath, # output path from input libs, params1, #a vector of widgets name (require ordered) paramLabs1, #a vector of widgets label(1:1 matched to params) sourceCode, # source files from configuration file subCode, title0, # Main title with study id and tumor type devpath, outBcode=NULL ){ codelist<-codelist[!(!is.na(codelist[,paramLabs1[1]]) & is.na(codelist[,params1[1]])),] sourceCode<-unique(sourceCode[!is.na(sourceCode)]) sourceCode<-sourceCode[!grepl("rcode.r",sourceCode)] head1<-sop_head #paste0('#/*soh',paste0(rep('*',73),collapse='')) nParam<-length(params1) if(FALSE){ head2<-'if(FALSE){ # DESCRIPTION: Parameters for generating following results:' tmploa<-unique(codelist[,c('Request.Name',params1,paramLabs1)]) tmploa2<-sapply(1:nrow(tmploa),function(y){ paste0(tmploa$Request.Name[y],' ', ifelse(is.na(tmploa[y,paramLabs1[1]]), '', paste0('(',paste0(sapply(which(!is.na(tmploa[y,paramLabs1])),function(x){ paste0(tmploa[y,paramLabs1[x]],'=', ifelse(is.na(tmploa[y,params1[x]]), 'Parameters Needed', tmploa[y,params1[x]])) }),collapse=';'),') \n') ) )}) tmploa2<-gsub(";", ";\n #", tmploa2) head3<-paste0(' #',1:length(tmploa2),'. ',tmploa2) head4<-paste0('\n}\n#', paste0(rep("-",90),collapse='')) #end of DESCRIPTION } else { head2<-'' head3<-'' head4<-'' } head5<-''# paste0(' #', gsub('\n', '\n # ', libs)) head6<-'\nif(TRUE){ #------Read in CSV Dataset------' head7<-paste0( ' indataset<-list() \n', ' for(i in 1:length(inf)){ \n', ' indataset[[i]]<-read.csv_sas(inf[i],stringsAsFactors=FALSE,header=TRUE, encoding=inf.enc[i], comment.char=\"\") \n', ' } \n ', ' names(indataset)<-inf \n', ' indataset.i<-indataset[[1]] ') head8<-paste0(' ', subCode) head6.1<-'\n}\nif(TRUE){ #------Read in one RData------' head7.1<-paste0( 'load(inf.R, indataR<-new.env())\n', 'indataR<<-as.list(indataR)\n' ) head9<-'\n}\n\nif (TRUE){ #------Source Packages and Function Files------' #connect default folder for reusable functions head10<-paste0( ' if(FALSE){ #Please firstly check whether all the required pacakges are installed.\n ', '#install.packages(c(...))\n ', gsub('\n', '\n ', libs), '\n }', '\n require(rtf) \n require(haven) \n', '\n read.csv_sas<<-function(file, header=TRUE, nrow=-1, comment.char="", ...){', '\n is.sas<-grepl(\'.sas7bdat\', file, fixed=TRUE)', '\n is.csv<-grepl(\'.csv\', file, fixed=TRUE)', '\n if(is.sas){', '\n ot<-haven::read_sas(file)', '\n if(header & nrow==1){ot<-names(ot)}', '\n }else if (is.csv){', '\n tm<-try(ot<-read.csv(file=file, h=header, nrow=nrow, na=c(\'NA\', \'\', \'.\'), stringsAsFactors=FALSE, comment.char=comment.char, ...))', '\n if(class(tm)==\'try-error\')', '\n tm<-try(ot<-read.csv(file=file, h=header, nrow=nrow, na=c(\'NA\', \'\', \'.\'), stringsAsFactors=FALSE,fileEncoding=\"latin1\", comment.char=comment.char))', '\n if(class(tm)==\'try-error\')', '\n tm<-try(ot<-read.csv(file=file, h=header, nrow=nrow, na=c(\'NA\', \'\', \'.\'), stringsAsFactors=FALSE,fileEncoding=\"UTF-8\", comment.char=comment.char))', '\n if(class(tm)==\'try-error\')', '\n tm<-try(ot<-readLines(con=file)) ', '\n }else{', '\n ot<-NULL\n}', '\n return(ot) \n }', "\n try(source(SourceFile)) \n ", "\n ", ifelse(is.null(eval(parse(text=outBcode))), " ", outBcode), "\n}") head11<-'\n\nif(OutputRTF){ #----- Generate RTF file ------' head12<-paste0('\n pageW<-11 \n pageH<-8.5 \n figW<-9 \n figH<-6 \n', '\n rtf<-RTF(rtfFileName,width=pageW,height=pageH, font.size=8,omi=c(.5,.5,.5,.5))') r_out<-c(head1,head2,head3,head4,head5, head9,head10,head6,head7,head8,head6.1, head7.1, head11,head12) for (i in 1:nrow(codelist)){ for(x in nParam:1){ if(!is.na(codelist[i,params1[x]])){ tmp0<-unlist(strsplit(as.character(codelist[i,params1[x]]), ',',fixed=TRUE)) tmp00 <- try( as.numeric(tmp0) ) if( class(tmp00)[1]=='try-error' || any(is.na(as.numeric(tmp0))) ) say1 <- TRUE else say1 <-FALSE tmp<-ifelse(say1, paste0('c(\"',paste0(tmp0,collapse='\",\"'),'\")'), paste0('c(',paste0(codelist[i,params1[x]],collapse=','),')')) codelist$Title[i]<- gsub(paste0('input$',params1[x]), tmp,codelist$Title[i],fixed=TRUE) codelist$PlotCode[i]<- gsub(paste0('input$',params1[x]), tmp,codelist$PlotCode[i],fixed=TRUE) codelist$FootCode[i]<- gsub(paste0('input$',params1[x]), tmp,codelist$FootCode[i],fixed=TRUE) } } #Add Header title<-codelist$Title[i] if(is.na(title) || length(title)<1) title <- " " if(grepl(title, 'paste', fixed=TRUE)) title<-eval(parse(text=title)) addhead<-vector() addhead[1]<-paste0('\n\n #------Add Header ',codelist$order[i],' ------') addhead[2]<-paste0(' addHeader(rtf,title=\"',title0,'\",font.size=10)') addhead[3]<-paste0(' addHeader(rtf,title=\"',title,'\",font.size=10)') r_out<-c(r_out,addhead) #Add Plot if( (!is.na(codelist$Type.y[i]) & codelist$Type.y[i]=='Figure') || (!is.na(codelist$Type.x[i]) & codelist$Type.x[i]=='Figure') ){ addplot<-vector() addplot[1]<-paste0(' #------Add Plot: ',codelist$Request.Name[i],' ------') addplot[2]<-paste0(' tmp<-',codelist$tmp[i]) addplot[3]<-paste0(' pngtmp<-function(){',codelist$PlotCode[i],'}') addplot[4]<-paste0(' addPlot(rtf,pngtmp,width=',codelist$width[i]/160,',height=',codelist$height[i]/160,')') r_out<-c(r_out,addplot)} #Add Table if( (!is.na(codelist$Type.y[i]) & codelist$Type.y[i]=='Table') || (!is.na(codelist$Type.x[i]) & codelist$Type.x[i]=='Table') ){ addtab<-vector() addtab[1]<-paste0(' #------Add Table: ',codelist$Request.Name[i],' ------') addtab[2]<-paste0(' tmp<-',codelist$tmp[i]) addtab[3]<-paste0(' outTable<-{',codelist$PlotCode[i],'}') addtab[4]<-paste0(' tWidth<-9\nnc<-nchar(as.character(outTable[,1]))\nc1W<-pmax(max(nc)*0.079/2, 20*0.079)\n', ' caW<-nc*0.079\nlcW<-.711\nothW<-(tWidth-c1W-lcW)/(ncol(outTable)-2)\n', ' centW<-rep(othW,ncol(outTable)-2)\ncWs<-c(c1W,centW,lcW)' ) addtab[5]<-paste0( ' addTable(rtf,outTable,col.widths=cWs,col.justify=rep(\'L\',length(outTable)))' ) r_out<-c(r_out,addtab) } #Add Footnote footnote<-codelist$FootCode[i] footnote<-gsub("\\\\n","\n",footnote) if(!is.na(footnote)&&gsub("", " ", footnote)!=''&&substr(footnote,1,5)=='paste') footnote<-eval(parse(text=footnote)) addfoot<-vector() addfoot[1]<-' addNewLine(rtf, n=2)' addfoot[2]<-paste0(' #------Add Footnote ',codelist$order[i],' ------') addfoot[3]<-paste0(' addParagraph(rtf,\"',footnote,'\")') r_out<-c(r_out,addfoot) if(i!=nrow(codelist)){ r_out<-c(r_out,' addPageBreak(rtf,width=11,height=8.5,font.size=8,omi=c(.5,.5,.5,.5))') }else{ r_out<-c(r_out,'\ndone(rtf)\n} #------End of RTF------\n') } } return(paste0(r_out,collapse='\n')) } checkSource<-function(fnm, keyS1='source('){#fnm must be a file under inpath2 rF1<-NULL r1<-readLines(con=fnm) r2<-toupper(gsub(" ", '', r1)) falseKey<-FALSE for(j in 1:length(r1)){ if(grepl('IF(FALSE)', r2[j], fixed=TRUE)|grepl('IF(F)', r2[j], fixed=TRUE)){ falseKey<-TRUE b1<-0 } if(falseKey){ if(gsub("IF(FALSE)","", r2[j],fixed=TRUE)=="[{]"|substr(r2[j],1,1)=="[{]") b1<-b1+1 if(b1==0 & grepl("[{]", r2[j])) falseKey<-FALSE if(grepl("}", r2[j])) { b1<-b1-1 if(b1==0) falseKey<-FALSE } }else{ if(grepl(toupper(keyS1), r2[j], fixed=TRUE)){ f3<-strsplit(r1[j],split='local.path1,', fixed=TRUE)[[1]][2] f3<-gsub("users/","",f3, fixed=TRUE) f3<-gsub("'","",f3, fixed=TRUE) f3<-gsub('"','',f3, fixed=TRUE) f3<-gsub('\"','',f3, fixed=TRUE) f3<-gsub(')','',f3, fixed=TRUE) f3<-gsub('(','',f3, fixed=TRUE) f3<-gsub(' ','',f3, fixed=TRUE) if(grepl(".r", tolower(f3), fixed=TRUE)){ rF1<-c(rF1, f3) } } } } return(rF1) } #-------------Creat Parameters-------------# #use radiobutton, slidebar, checkbox, selectInput if(!newWay){ widgets.code<-function(UInames, max.n){ ind<-max.n!=0 check.code<-lapply(max.n['check']:1,function(x){ ret<-'\n output$checkbox_xx<-renderUI({ tmpN<-reactive(which(check.param()$Request.Name==input$analysis)) if(length(tmpN())<1) return(NULL) try(tmp<-eval(parse(text=Vdic()$tmp[AnalyC()]))) if(is.na(check.param()[tmpN(),\'check.label_xx\']) ||class(try(default<-eval(parse(text=check.param()[tmpN(),\'check.default_xx\']))))==\"try-error\" ||class(try(choice<-eval(parse(text=check.param()[tmpN(),\'check.choice_xx\']))))==\"try-error\")return(NULL) if (length(choice)==0)return(div(class=\"alert alert-error\",strong(\'checkbox Options Are Not Available\'))) if (is.na(default))default<-choice checkboxGroupInput(inputId=\'check_xx\',label=strong(check.param()[tmpN(),\'check.label_xx\']),choices=choice,selected=default)})\n\n ' if (x==1){ret<-gsub('_xx','',ret,fixed=TRUE)}else{ret<-gsub('_xx',x,ret,fixed=TRUE)} ret }) check.codes<-Reduce(function(x,y)paste0(x,y,collapse='\n'),check.code) radio.code<-lapply(max.n['radio']:1,function(x){ ret<-'output$radiobutton_xx<-renderUI({ tmpN<-reactive(which(radio.param()$Request.Name==input$analysis)) if(length(tmpN())<1) return(NULL) try(tmp<-eval(parse(text=Vdic()$tmp[AnalyC()]))) if(is.na(radio.param()[tmpN(),\'radio.label_xx\']) ||class(try(default<-eval(parse(text=radio.param()[tmpN(),\'radio.default_xx\']))))==\"try-error\" ||class(try(choice<-eval(parse(text=radio.param()[tmpN(),\'radio.choice_xx\']))))==\"try-error\")return(NULL) if (length(choice)==0)return(div(class=\"alert alert-error\",strong(\'radiobutton Options Are Not Available\'))) if (is.na(default))default<-choice[1] radioButtons(\'radio_xx\',label=strong(radio.param()[tmpN(),\'radio.label_xx\']),choices=choice,selected=default)})\n\n ' if (x==1){ret<-gsub('_xx','',ret,fixed=TRUE)}else{ret<-gsub('_xx',x,ret,fixed=TRUE)} ret }) radio.codes<-Reduce(function(x,y)paste0(x,y,collapse='\n'),radio.code) dropdown.code<-lapply(max.n['dropdown']:1,function(x){ ret<-'output$dropdown_xx<-renderUI({ isolate({ tmpN<-reactive(which(dropdown.param()$Request.Name==input$analysis)) if(length(tmpN())<1) return(NULL) try(tmp<-eval(parse(text=Vdic()$tmp[AnalyC()]))) }) if(is.null(dropdown.param()[tmpN(),\'dropdown.label_xx\'])) return(NULL) if (is.na(dropdown.param()[tmpN(),\'dropdown.label_xx\']) ||class(try(default<-eval(parse(text=dropdown.param()[tmpN(),\'dropdown.default_xx\']))))==\"try-error\" ||class(try(default2<-eval(parse(text=dropdown.param()[tmpN(),\'dropdown.multiple_xx\']))))==\"try-error\" ||class(try(choice<-eval(parse(text=dropdown.param()[tmpN(),\'dropdown.choice_xx\']))))==\"try-error\")return(NULL) if (length(choice)==0)return(div(class=\"alert alert-error\",strong(\'dropdown Options Are Not Available\'))) if (all(is.na(default)))default<-choice[1] if (all(is.na(default2)))default2<-TRUE selectInput(\'dropdown_xx\',label=strong(dropdown.param()[tmpN(),\'dropdown.label_xx\']), choices=choice,selected=default,multiple=default2,selectize=TRUE, width=\"100%\") }) \n\n ' if (x==1){ret<-gsub('_xx','',ret,fixed=TRUE)}else{ret<-gsub('_xx',x,ret,fixed=TRUE)} ret }) dropdown.codes<-Reduce(function(x,y)paste0(x,y,collapse='\n'),dropdown.code) slide.code<-lapply(max.n['slide']:1,function(x){ ret<-'output$slider_xx<-renderUI({ tmpN<-reactive(which(slide.param()$Request.Name==input$analysis)) if(length(tmpN())<1) return(NULL) try(tmp<-eval(parse(text=Vdic()$tmp[AnalyC()]))) if(is.null(slide.param()[tmpN(),\'slide.label_xx\'])) return(NULL) if (is.na(slide.param()[tmpN(),\'slide.label_xx\']) ||class(try(min<-eval(parse(text=slide.param()[tmpN(),\'slide.min_xx\']))))[1]==\"try-error\" ||class(try(max<-eval(parse(text=slide.param()[tmpN(),\'slide.max_xx\']))))[1]==\"try-error\" ||class(try(default<-eval(parse(text=slide.param()[tmpN(),\'slide.value_xx\']))))[1]==\"try-error\" ||class(try(by<-eval(parse(text=slide.param()[tmpN(),\'slide.by_xx\']))))[1]==\"try-error\")return(NULL) if (length(c(min,max,default,by))<4)return(div(class=\"alert alert-error\",strong(\'slider Options Are Not Available\'))) if (is.na(default))default<-mean(min,max) sliderInput(\'slide_xx\',label=strong(slide.param()[tmpN(),\'slide.label_xx\']),min=min,max=max,value=default,step=by,animate = TRUE)})\n\n' if (x==1){ret<-gsub('_xx','',ret,fixed=TRUE)}else{ret<-gsub('_xx',x,ret,fixed=TRUE)} ret }) slide.codes<-Reduce(function(x,y)paste0(x,y,collapse='\n'),slide.code) date.code<-lapply(max.n['date']:1,function(x){ ret<-'output$date_xx<-renderUI({ tmpN<-reactive(which(date.param()$Request.Name==input$analysis)) if(length(tmpN())<1) return(NULL) try(tmp<-eval(parse(text=Vdic()$tmp[AnalyC()]))) if (is.na(date.param()[tmpN(),\'date.label_xx\']) ||class(try(default<-eval(parse(text="(date.param()[tmpN(),\'date.value_xx\'])"))))==\"try-error\")return(NULL) if (!is.null(default)&is.na(default)) return(div(class=\"alert alert-error\",strong(\'date Options Are Not Available\'))) dateInput(\'date_xx\',label=strong(date.param()[tmpN(),\'date.label_xx\']), value=default, format = \"yyyy-mm-dd\")})\n\n' if (x==1){ret<-gsub('_xx','',ret,fixed=TRUE)}else{ret<-gsub('_xx',x,ret,fixed=TRUE)} ret }) date.codes<-Reduce(function(x,y)paste0(x,y,collapse='\n'),date.code) dateR.code<-lapply(max.n['dateR']:1,function(x){ ret<-'output$dateR_xx<-renderUI({ tmpN<-reactive(which(dateR.param()$Request.Name==input$analysis)) if(length(tmpN())<1) return(NULL) try(tmp<-eval(parse(text=Vdic()$tmp[AnalyC()]))) if (is.na(dateR.param()[tmpN(),\'dateR.label_xx\']) ||class(try(min<-eval(parse(text="(dateR.param()[tmpN(),\'dateR.start_xx\'])"))))==\"try-error\" ||class(try(max<-eval(parse(text="(dateR.param()[tmpN(),\'dateR.end_xx\'])"))))==\"try-error\") return(NULL) if ((!is.null(min)&is.null(max))&(is.na(min)&is.na(max))) return(div(class=\"alert alert-error\",strong(\'data range Options Are Not Available\'))) dateRangeInput(\'dateR_xx\',label=strong(dateR.param()[tmpN(),\'dateR.label_xx\']), start=min, end=max, format = \"yyyy-mm-dd\")})\n\n' if (x==1){ret<-gsub('_xx','',ret,fixed=TRUE)}else{ret<-gsub('_xx',x,ret,fixed=TRUE)} ret }) dateR.codes<-Reduce(function(x,y)paste0(x,y,collapse='\n'),dateR.code) num.code<-lapply(max.n['num']:1,function(x){ ret<-'output$num_xx<-renderUI({ tmpN<-reactive(which(num.param()$Request.Name==input$analysis)) if(length(tmpN())<1) return(NULL) try(tmp<-eval(parse(text=Vdic()$tmp[AnalyC()]))) if (is.na(num.param()[tmpN(),\'num.label_xx\']) ||class(try(default<-eval(parse(text="num.param()[tmpN(),\'num.value_xx\']"))))==\"try-error\")return(NULL) if (is.na(default)) return(div(class=\"alert alert-error\",strong(\'numericInput Options Are Not Available\'))) numericInput(\'num_xx\',label=strong(num.param()[tmpN(),\'num.label_xx\']), value=default)})\n\n' if (x==1){ret<-gsub('_xx','',ret,fixed=TRUE)}else{ret<-gsub('_xx',x,ret,fixed=TRUE)} ret }) num.codes<-Reduce(function(x,y)paste0(x,y,collapse='\n'),num.code) text.code<-lapply(max.n['text']:1,function(x){ ret<-'output$text_xx<-renderUI({ tmpN<-reactive(which(text.param()$Request.Name==input$analysis)) if(length(tmpN())<1) return(NULL) try(tmp<-eval(parse(text=Vdic()$tmp[AnalyC()]))) if (is.na(text.param()[tmpN(),\'text.label_xx\']) ||class(try(default<-eval(parse(text=text.param()[tmpN(),\'text.value_xx\']))))==\"try-error\")return(NULL) if (is.na(default)) return(div(class=\"alert alert-error\",strong(\'textInput Options Are Not Available\'))) textInput(\'text_xx\',label=strong(text.param()[tmpN(),\'text.label_xx\']), value=default)})\n\n' if (x==1){ret<-gsub('_xx','',ret,fixed=TRUE)}else{ret<-gsub('_xx',x,ret,fixed=TRUE)} ret }) text.codes<-Reduce(function(x,y)paste0(x,y,collapse='\n'),text.code) textbox.code<-lapply(max.n['textbox']:1,function(x){ ret<-paste0('output$textbox_xx<-renderUI({ tmpN<-reactive(which(textbox.param()$Request.Name==input$analysis)) try(tmp<-eval(parse(text=Vdic()$tmp[AnalyC()]))) if(is.na(textbox.param()[tmpN(),\'textbox.label_xx\']))return(NULL) cols<-eval(parse(text=textbox.param()[tmpN(),\'textbox.cols_xx\'])) rows<-eval(parse(text=textbox.param()[tmpN(),\'textbox.rows_xx\'])) default<-textbox.param()[tmpN(),\'textbox.default_xx\'] label<-textbox.param()[tmpN(),\'textbox.label_xx\'] if(is.na(cols)||is.null(cols))cols<-40 if(is.na(rows)||is.null(rows))rows<-2 texttmp<-paste0(\'<h6>\',label,\'</h6>\n<textarea name=\"\',textbox_xx,\'\" rows=\"\',rows,\'\" cols=\"\',cols,\'\">\',default,\'</textarea>\') return(shiny::HTML(texttmp)) })\n\n') if (x==1){ret<-gsub('_xx','',ret,fixed=TRUE)}else{ret<-gsub('_xx',x,ret,fixed=TRUE)} ret }) textbox.codes<-Reduce(function(x,y)paste0(x,y,collapse='\n'),textbox.code) widgets.code<-paste0(c(check.codes,radio.codes,dropdown.codes,slide.codes, date.codes, dateR.codes, num.codes, text.codes, textbox.codes)[ind], collapse='\n\n') return(widgets.code) } } widgets.order<<-function(analysis, UIdic1, UInames, ncol.widg=NULL){ # print(UIdic1) # print(UInames) # print(analysis) if(is.null(ncol.widg)){ncol.widg<-1} input.names<-as.vector(t(UIdic1[UIdic1$Request.Name==analysis, UInames])) if(length(input.names)==0){ widg.list=NULL }else{ input.labs<-as.vector(t(UIdic1[UIdic1$Request.Name==analysis, gsub("uiInput", "uilab", UInames, fixed=TRUE)])) #names(input.names)<-1:length(input.names) s_1<-!is.na(input.names) input.names<-input.names[s_1]#unique(setdiff(as.vector(input.names),NA)) input.labs<-input.labs[s_1] input.labs[is.na(input.labs)]<-"" widg.list<-unlist(strsplit(input.names,'input$',fixed=TRUE)) sel0<-widg.list!='' & !is.na(widg.list) input.names<-widg.list<-widg.list[sel0] #input.labs<-input.labs[sel0] widg.list<-gsub('check','checkbox',widg.list) widg.list<-gsub('radio','radiobutton',widg.list) widg.list<-gsub('dropdown','dropdown',widg.list) widg.list<-gsub('slide','slider',widg.list) # widg.list<-gsub('date','date',widg.list) # widg.list<-gsub('dateR','dateR',widg.list) # widg.list<-gsub('num','num',widg.list) # widg.list<-gsub('text','text',widg.list) # widg.list<-gsub('textbox','textbox',widg.list) } if(length(widg.list)==0){ widg.code<-'return(NULL)'; input.names<-input.labs<-NA }else{ if(F){ widg.code<-paste0('uiOutput(\'',widg.list,'\')',collapse=',') widg.code<-paste0('return(conditionalPanel(condition=\'true\', div(', widg.code,')))',collapse='') }else{ widg.code<-paste0('uiOutput(\'',widg.list,'\')') #,collapse=',' w.widg<-floor(12/ncol.widg) #upto 4, column width nrow.widg<-ceiling(length(widg.code)/ncol.widg)#number of rows widg.code2<-NULL for(i in 1:nrow.widg){ widg.code3<-NULL for(j in 1:ncol.widg){ ij<-(i-1)*ncol.widg+j if(ij <= length(widg.code)){ wij<-paste0("column(", w.widg,", ", widg.code[ij], ", offset=", 0, ")") #max(w.widg*(j-1)-2,0) widg.code3<-paste0(c(widg.code3, wij), collapse=",") } } widg.code2<-c(widg.code2, paste0("fluidRow(", widg.code3, ")")) } widg.code<-paste0(widg.code2, collapse=',') widg.code<-paste0('return(conditionalPanel(condition=\'true\', div(', widg.code,')))',collapse='') } } out1<-data.frame(code=widg.code,names=input.names,labs=input.labs) return(out1) } widgets.param<-function(uidic, wid, max.n){ if(!wid %in% names(max.n)){ return(NA) }else{ temp<-lapply(setdiff(unique(uidic$Request.Name),NA),function(x){ row_sel<-uidic$Request.Name==x ret<-unique(uidic[which(row_sel), grepl(wid,colnames(uidic))]) ret$Request.Name<-x #dfnames is the widget name which default values not specified in CD wid2<-wid[!wid%in%c("num","text")] if(length(wid2)>0){ dfnames<-c(paste0(wid2,'.default',c(max.n[wid2]:2, ''))) dfnames<-dfnames[!dfnames%in%colnames(uidic)] if (length(dfnames)>0){ dfs<-matrix(NA,nrow=nrow(ret),ncol=length(dfnames)) colnames(dfs)<-dfnames ret2<-data.frame(ret,dfs,row.names=NULL) }else{ ret2<-data.frame(ret,row.names=NULL)} }else{ ret2<-data.frame(ret,row.names=NULL)} #dfnames3 is the dropdown widget name which multiple not specified in CD wid3<-wid2[grepl("dropdown",wid2)] if(length(wid3)>0){ dfnames3<-c(paste0(wid3,'.multiple',c(max.n[wid3]:2, ''))) dfnames3<-dfnames3[!dfnames3%in%colnames(uidic)] if (length(dfnames3)>0){ dfs<-matrix(NA,nrow=nrow(ret2),ncol=length(dfnames3)) colnames(dfs)<-dfnames3 ret3<-data.frame(ret2,dfs, row.names=NULL) }else{ ret3<-data.frame(ret2,row.names=NULL) } }else{ ret3<-data.frame(ret2,row.names=NULL) } return(ret3) }) #convert the list object to data.frame ret0<-Reduce(function(x,y){unique(rbind(x,y))},temp) return(ret0) } } #-------------Functions for RTF output setup-------------# if(TRUE){ col_width <- function(tb){ #Function to Generate rtf table column widths cws <- NULL for(i in 1:length(names(tb))) { ncName <- nchar(names(tb)[i]) ncString <- max(nchar(tb[,i])) nc <- max(ncName, ncString) cw <- nc*0.89/10 # assume 10 characters per an inch cws <- c(cws, cw) } return(cws) } #--- convert factor to character colname convert_fac_to_char <- function(dat) { for(i in 1:ncol(dat)) { if(class(dat[, i]) == "factor") dat[, i] <- as.character(dat[, i]) } return(dat) } .convert <- function (x) { x <- gsub("\\n", " \\\\line ", x) x <- gsub("<=", "\\\\u8804\\\\3", x) x <- gsub(">=", "\\\\u8805\\\\3", x) x <- gsub("&gt;", ">", x) x <- gsub("&lt;", "<", x) x <- gsub("&Alpha;", "\\\\u0913\\\\3", x) x <- gsub("&Beta;", "\\\\u0914\\\\3", x) x <- gsub("&Gamma;", "\\\\u0915\\\\3", x) x <- gsub("&Delta;", "\\\\u0916\\\\3", x) x <- gsub("&Epsilon;", "\\\\u0917\\\\3", x) x <- gsub("&Zeta;", "\\\\u0918\\\\3", x) x <- gsub("&Eta;", "\\\\u0919\\\\3", x) x <- gsub("&Theta;", "\\\\u0920\\\\3", x) x <- gsub("&Iota;", "\\\\u0921\\\\3", x) x <- gsub("&Kappa;", "\\\\u0922\\\\3", x) x <- gsub("&Lambda;", "\\\\u0923\\\\3", x) x <- gsub("&Mu;", "\\\\u0924\\\\3", x) x <- gsub("&Nu;", "\\\\u0925\\\\3", x) x <- gsub("&Xi;", "\\\\u0926\\\\3", x) x <- gsub("&Omicron;", "\\\\u0927\\\\3", x) x <- gsub("&Pi;", "\\\\u0928\\\\3", x) x <- gsub("&Rho;", "\\\\u0929\\\\3", x) x <- gsub("&Sigma;", "\\\\u0931\\\\3", x) x <- gsub("&Tau;", "\\\\u0932\\\\3", x) x <- gsub("&Upsilon;", "\\\\u0933\\\\3", x) x <- gsub("&Phi;", "\\\\u0934\\\\3", x) x <- gsub("&Chi;", "\\\\u0935\\\\3", x) x <- gsub("&Psi;", "\\\\u0936\\\\3", x) x <- gsub("&Omega;", "\\\\u0937\\\\3", x) x <- gsub("&alpha;", "\\\\u0945\\\\3", x) x <- gsub("&beta;", "\\\\u0946\\\\3", x) x <- gsub("&gamma;", "\\\\u0947\\\\3", x) x <- gsub("&delta;", "\\\\u0948\\\\3", x) x <- gsub("&epsilon;", "\\\\u0949\\\\3", x) x <- gsub("&zeta;", "\\\\u0950\\\\3", x) x <- gsub("&eta;", "\\\\u0951\\\\3", x) x <- gsub("&theta;", "\\\\u0952\\\\3", x) x <- gsub("&iota;", "\\\\u0953\\\\3", x) x <- gsub("&kappa;", "\\\\u0954\\\\3", x) x <- gsub("&lambda;", "\\\\u0955\\\\3", x) x <- gsub("&mu;", "\\\\u0956\\\\3", x) x <- gsub("&nu;", "\\\\u0957\\\\3", x) x <- gsub("&xi;", "\\\\u0958\\\\3", x) x <- gsub("&omicron;", "\\\\u0959\\\\3", x) x <- gsub("&pi;", "\\\\u0960\\\\3", x) x <- gsub("&rho;", "\\\\u0961\\\\3", x) x <- gsub("&sigmaf;", "\\\\u0962\\\\3", x) x <- gsub("&sigma;", "\\\\u0963\\\\3", x) x <- gsub("&tau;", "\\\\u0964\\\\3", x) x <- gsub("&upsilon;", "\\\\u0965\\\\3", x) x <- gsub("&phi;", "\\\\u0966\\\\3", x) x <- gsub("&chi;", "\\\\u0967\\\\3", x) x <- gsub("&psi;", "\\\\u0968\\\\3", x) x <- gsub("&omega;", "\\\\u0969\\\\3", x) x <- gsub("TRUE", "Yes", x) x <- gsub("FALSE", "No", x) x } .get.space.before.after <- function (space.before = NULL, space.after = NULL) { ret <- "" if (!is.null(space.before)) { ret <- paste(ret, "\\sb", (space.before * 1440), sep = "") } if (!is.null(space.after)) { ret <- paste(ret, "\\sa", (space.after * 1440), sep = "") } ret } .add.table.row <- function (col.data = c("c1", "c2", "c3"), col.widths = c(1, 4.5, 1), col.justify = NULL, font.size = 10, last.row = FALSE, indent = 0, border.top = FALSE, border.bottom = FALSE, space.before = NULL, space.after = NULL) { header <- paste("\\trowd\\trgaph100\\trleft", indent, sep = "") if (length(col.data) != length(col.widths)) { stop(paste("The number of data columns (", length(col.data), ") doesn't match the column widths (", length(col.widths), ")! Input data: ", col.data, sep = "")) } justify <- vector() justify["L"] <- "\\ql" justify["R"] <- "\\qr" justify["C"] <- "\\qc" justify["J"] <- "\\qj" justify.v <- rep(justify["L"], length(col.data)) numeric.cols <- which(!is.na(suppressWarnings(as.numeric(col.data)))) if (length(numeric.cols) > 0) { justify.v[numeric.cols] <- justify["R"] } if (!is.null(col.justify)) { if (length(col.justify) == 1) { if (col.justify %in% names(justify)) { justify.v <- rep(justify[col.justify], length(col.data)) } else { stop(paste("col.justify parameter not recognized: ", col.justify, " (should be L, R, C, or J)", sep = "")) } } else if (length(col.justify) == length(col.data)) { justify.v <- justify[col.justify] } else { stop(paste("The number of data columns (", length(col.data), ") doesn't match the col.justify (", length(col.justify), ") parameter! Input data: ", paste(col.data, sep = "", collapse = ", "), sep = "")) } } btop <- "" bbottom <- "" if (any(border.top)) # btop <- sapply(border.top, ifelse, "\\clbrdrt\\brdrs\\brdrw15",'') # make border.top as a vector option if (last.row == TRUE | any(border.bottom)) # bbottom <- sapply(border.bottom, ifelse, "\\clbrdrb\\brdrs\\brdrw15",'') #make border.bottom as a vector option cols.prefix <- paste("\\clvertalt\\clshdrawnil\\clwWidth", round(col.widths * 1440, 0), "\\clftsWidth3\\clheight260\\clpadl100\\clpadr100\\gaph", btop, bbottom, "\\cellx", c(1:length(col.widths)), "\n", sep = "", collapse = "") cols <- paste("\\pard", justify.v, .get.space.before.after(space.before, space.after), "\\widctlpar\\intbl\\fi0\\f2\\fs", font.size * 2, " ", .convert(col.data), "\\cell\n", sep = "", collapse = "") end.row <- "\\widctlpar\\intbl\\row\n" paste(header, cols.prefix, cols, end.row, sep = "") } # add width basing on duplication adj.width <- function(x, cw, space=1){ ret <- array(0, dim=dim(x)) x2 <- x #dup <- t(apply(x,1, function(x) duplicated(x)& x!='')) dup <- t(apply(x,1, function(x) c(FALSE, x[-1]==x[-length(x)]))) for (i in 1:nrow(x)) { for (j in ncol(x):1) { if (i > 1 & j <= ncol(x)) if (!dup[i-1,j]) dup[i,j] <- FALSE if (dup[i,j]) { ret[i,j-1] <- ret[i,j]+space*cw[j] ret[i,j ] <- -space*cw[j] x2[i,j] <- '' } } ret[i,] <- ret[i,]+cw } list(x=x2, cw=ret) } ###--- This one is added/modified a little bit from the original rtf.tab that Michael Man developed # It expanded the width for header or footnote rtf.tab <- function(dat,cw=NULL,titles,col.just=NULL,var.ul,prd.status='QA',footns='',header=FALSE,footer=FALSE, nline.body=40, addSpaceHeader=0, addSpaceFoot=0, page.disp=TRUE,...) { # almost automated w/ modified .add.table.row st <- attributes(dat)$'start cell'[1] hd <- 1:(st-1) if(is.null(cw)) cw <- c(1.5,rep(.7,ncol(dat)-1)) if(is.null(col.just)) col.just <- rep('R', nrow(dat)) if(is.null(dim(col.just))) col.just <- matrix(rep(col.just,ncol(dat)), nrow=nrow(dat), byrow=FALSE) x <- dat cw2 <- matrix(rep(cw, nrow(x)), ncol=ncol(x), byrow=TRUE) if (st > 2) { #undebug(adj.width) y <- adj.width(x=dat[hd,],cw=cw, space=1) x[hd,] <- y$x cw2[hd,] <- y$cw } #expr=expression({ rtf.add.row <- function(rows=1:nrow(x)){ ret <- "{\\pard\n" for (i in rows) if (i <= nrow(x)){ sel <- which(cw2[i,]>0) ret <- paste(ret, .add.table.row( col.data = x[i,sel], col.widths = cw2[i,sel], col.justify = col.just[i,sel], font.size = fs, border.top = i %in% c(1), border.bottom = if (i > st-2) i %in% c(st-1,nrow(x),max(rows)) else x[i,sel] %in% var.ul ), sep='') if (i < st) if (!all(cw2[i,] == cw2[i+1,])) ret <- paste(ret,'{\\pard\\par}','', sep='') } ret <- paste(ret, "}\n\n", sep = "") rtf$.rtf <- paste(rtf$.rtf, ret, sep='') } #}) rtf <- RTF(...) fs <- rtf$.font.size rtf$.rtf <- gsub('Times New Roman', 'Courier New', rtf$.rtf) # make "Courier New" as default rtf$.rtf <- gsub('field{\\fldinst{page}}', '', rtf$.rtf, fixed=TRUE) # delete page number #nline.body <- 2 npage <- ceiling((nrow(x)-st+1)/nline.body) #addHeader(rtf,title=titles[[1]],subtitle=titles[[2]]) #systems <- c('Page \\chpgn of {\\field{\\*\\fldinst NUMPAGES }}', systems <- c(ifelse(page.disp==TRUE, paste('Page \\chpgn of ', npage, sep=''), ""), format(Sys.time(), "%H:%M %d%b%Y"), prd.status) #systems <- c(paste('Page \\chpgn of ', npage, sep=''), # format(Sys.time(), "%H:%M %d%b%Y"), # prd.status) hd.m <- c(paste(titles, collapse='\\line '), paste(systems, collapse='\\line ')) # main header tmp <- .add.table.row( col.data = hd.m, col.widths = c(sum(cw)-2+addSpaceHeader,2), col.justify = c('L', 'R'), font.size = fs) tmp2 <- .add.table.row( col.data = paste(footns, collapse='\\line '), col.widths = sum(cw)+addSpaceFoot, col.justify = 'L', font.size = fs) if (FALSE) rtf$.rtf <- paste(rtf$.rtf, "{\\header\\pard", "\\fi0\\f2\\fs", fs*2, "\\qr Page \\chpgn of {\\field{\\*\\fldinst NUMPAGES }}\\par}", sep='') for (i in 1:npage){ rtf$.rtf <- paste(rtf$.rtf, ifelse(i==1,'','\\page'), '{\\pard\\par}', ifelse(header,'{\\header',''), tmp, ifelse(header,'}',''), '{\\pard\\par}', sep='') #startParagraph(rtf) #eval(expr) rtf.add.row(rows=c(1:(st-1), 1:nline.body-1+st+nline.body*(i-1))) #endParagraph(rtf) rtf$.rtf <- paste(rtf$.rtf, '{\\pard\\par}', ifelse(footer,'\\footer',''), tmp2, sep='') } done(rtf) }#end rtf.tab #--- produce to rtf file that as SAS output. It can be used for single table or table with multiple pages rtf_table_out_as_sas <- function(rtf, tb, cw=NULL, colFormat=c(rep("L", 1), rep("C",1), rep("R",1)), cell1=2, cell2=1, nheader=1, varName=NULL, var.ul='', prd.status=' ', #'QA', titles="", footns="", header=FALSE, footer=FALSE, nline.body=30, height=8.5, width=11, omi=c(1,1,1,1), addSpaceHeader=0, addSpaceFoot=0, page.disp=TRUE, ...) { # rtf: RTF object that is just needed to be declared once before calling the function # tb: table out # cw: column width # colFormat: alignment (left, center, or right) for each column # varName: variable name that want to be repeated when go to the next page # var.ul: pre-specified cell values that indicate the bottom line in a table # nline.body: number of lines per page # addSpaceFoot, addSpaceHeader: expand the width of header or footnotes # page.disp: whether diplay page number #--- generate blank pape (break page) if the data is more than a page if(nrow(tb) > nline.body) { idx <- seq(1, nrow(tb), by = nline.body) idx.n <- c(seq(nline.body, nrow(tb), by = nline.body), nrow(tb)) }else { idx <- 1 idx.n <- nrow(tb) } npage <- length(idx) for(k in 1:length(idx)) { subTable <- tb[idx[k]:idx.n[k], ] if(is.null(nrow(subTable))){ subTable <- data.frame(` `=subTable) } #--- if nrow < nline.body, need adding some spaces to move footnotes to bottom of the page if(nrow(subTable) < nline.body) { addData <- data.frame(matrix("",ncol=ncol(subTable), nrow=nline.body-nrow(subTable)-1)) names(addData) <- names(subTable) subTable <- rbind(subTable, addData) } #-- get values that will be in the 1st row of next page rownames(subTable) <- 1:nrow(subTable) #-- check if the last row of previous page with varName not matched the 1st row of next page if(k==1) string.val <- NULL if(k!=1 & !all(unique(subTable[1,varName]) %in% "") & !all(unique(subTable[1,varName]) %in% string.val)) string.val <- unique(subTable[1,varName]) if(k==1 & all(tb[nrow(subTable)+1, varName] %in% "")) { for(m in 1:nrow(subTable)) if(all(!subTable[m,varName] %in% "")) string.val <- subTable[m, varName] } else if(!all(tb[nrow(subTable)+1, varName] %in% "")) { string.val <- NULL } else { #-- add last row of previous page to 1st row of next page if(!is.null(string.val)) subTable[1, varName] <- string.val for(m in 1:nrow(subTable)) if(all(!subTable[m,varName] %in% "")) string.val <- subTable[m, varName] } hd <- sapply(colnames(subTable), function(x) strsplit(x, '; ')[[1]]) ret <- rbind(hd, as.matrix(subTable)) colnames(ret) <- 1:ncol(ret) rownames(ret) <- 1:nrow(ret) ret2 <- ret colnames(ret2) <- 1:ncol(ret2) rownames(ret2) <- 1:nrow(ret2) attributes(ret2) <- list(dim = dim(ret2), dimnames = dimnames(ret2), `start cell` = c(cell1, cell2)) col.just <- matrix(c(rep(colFormat, nrow(ret2) + nheader)), ncol=ncol(ret2), byrow=TRUE) dat <- ret2 st <- attributes(dat)$'start cell'[1] hd <- 1:(st-1) if(is.null(cw)) cw <- c(2.5, rep(1.5,ncol(dat)-1)) x <- dat cw2 <- matrix(rep(cw, nrow(x)), ncol=ncol(x), byrow=TRUE) if (st > 2) { y <- adj.width(x=dat[hd,],cw=cw, space=1) x[hd,] <- y$x cw2[hd,] <- y$cw } rtf.add.row <- function(rows=1:nrow(x)){ ret <- "{\\pard\n" for (i in rows) if (i <= nrow(x)){ sel <- which(cw2[i,]>0) ret <- paste(ret, .add.table.row( col.data = x[i,sel], col.widths = cw2[i,sel], col.justify = col.just[i,sel], font.size = fs, border.top = i %in% c(1), border.bottom = if (i > st-2) i %in% c(st-1,nrow(x),max(rows)) else x[i,sel] %in% var.ul #x is the subtable with header ), sep='') if (i < st) if (!all(cw2[i,] == cw2[i+1,])) ret <- paste(ret,'{\\pard\\par}','', sep='') } ret <- paste(ret, "}\n\n", sep = "") rtf$.rtf <- paste(rtf$.rtf, ret, sep='') } rtf <- rtf fs <- rtf$.font.size rtf$.rtf <- gsub('Times New Roman', 'Courier New', rtf$.rtf) # make "Courier New" as default rtf$.rtf <- gsub('field{\\fldinst{page}}', '', rtf$.rtf, fixed=TRUE) # delete page number tmp2 <- .add.table.row( col.data = paste(footns, collapse='\\line '), col.widths = sum(cw)+addSpaceFoot, col.justify = 'L', font.size = fs) rtf.add.row(rows=c(1:(st-1), 1:nline.body-1+st)) rtf$.rtf <- paste(rtf$.rtf, '{\\pard\\par}', ifelse(footer,'\\footer',''), tmp2, sep='') } #end of the for loop return(rtf) }#end rtf_table_out_as_sas } #-------------Manually Convert R object into HTML code-------------# df2html<-function( #convert a table into part of HTML code datF, #a data.frame for table output tabTit="", #table title fnote=NULL, #footnote ind=1 ){ datF<-as.data.frame(datF) dim1<-dim(datF) nr<-dim1[1] nc<-dim1[2] cnm<-colnames(datF) rnm<-rownames(datF) #currently the rownames would not be printed out. out<-paste0('<a name=\"IDX',ind,'\"></a>') out<-c(out, '<div align=\"left\">') tabSum2<-paste0('<table class=\"Table\" cellspacing=\"1\" cellpadding=\"', nc+2, '\" rules=\"groups\" frame=\"box\" border=\"1\" bordercolor=\"#000000\" ', 'summary=\"', tabTit, '\" >') #style="table-layout: fixed; width: 100%" out<-c(out, tabSum2, '<colgroup>', rep('<col>',nc), '</colgroup>', '<thead>') #For table header tabHead<-c('<tr>', paste0('<td class="l NoteContent" colspan=\"', nc, '\">', tabTit, '<br>', paste(rep("-",138),collapse=''), '</td>'), '</tr>', '<tr>') for(i in 1:nc){ tabHead<-c(tabHead, paste0('<th class=\"c b Header\" scope=\"col\">', cnm[i], '</th>')) } out<-c(out, tabHead, '</tr>', '</thead>', '<tbody>') #for table body tabBody<-NULL for(j in 1:nr){ tabBody<-c(tabBody, '<tr>') for(i in 1:nc){ tabBody<-c(tabBody, paste0('<td class=\"l Data\">', datF[j,i], '</td>')) } tabBody<-c(tabBody, '</tr>') } out<-c(out, tabBody, '</tbody>', '<tfoot>', '<tr>') out<-c(out, paste0('<td class=\"l NoteContent\" colspan=\"',nc,'\">', paste(rep("-",138),collapse=''), '<br>', fnote, '</td>'), '</tr>', '</tfoot>') out<-c(out, '</table>', '</div>', '<p style="page-break-after: always;"><br></p><hr size="3">') return(out) } fig2html<-function( #convert a png figure into part of HTML code figNm='plot.png', # the png file name figTit="", #figure title figH="480", figW="640", fnote=NULL, #footnote ind=1 ){ out<-paste0('<a name=\"IDX',ind,'\"></a>') figTit1<-c('<div align=\"left\">', paste0('<table class=\"Table\" cellspacing=\"1\" cellpadding=\"1', '\" rules=\"groups\" frame=\"box\" border=\"1\" bordercolor=\"#000000\" ', 'summary=\"', figTit, '\" >'), '<colgroup>','<col>', '</colgroup>', '<thead>', '<tr>' ) out<-c(out, figTit1, paste0('<td class=\"l NoteContent\" colspan=\"1\">', figTit, '</td>'), '</tr>', '</thead>', '<tbody>', '<tr>' ) out<-c(out, '<td>', paste0('<img alt=\" \" src=\"', figNm, '\" style=\" height: ', figH, 'px; width: ', figW, 'px;\" border=\"0\">'), '</td>', '</tr>', '</tbody>','<tfoot>','<tr>') out<-c(out, paste0('<td class=\"l NoteContent\" colspan=\"1\">',fnote, '</td>'), '</tr>', '</tfoot>') out<-c(out, '</table>', '</div>', '<p style="page-break-after: always;"><br></p><hr size="3">') return(out) } cLink<-function( #generate a link in content table tit="tmplink", ind=1 ){ out<-'<li class=\"ContentItem\">' out<-c(out, '<span><b>&#183;</b><a href=\"', paste0('body.htm#IDX', ind,'\" target=\"body\">',tit,'</a>'), '</span><br></li>') return(out) } #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~# #revise a html table code #make it into multi-level header toMultH <- function( tbc, # a vector of html table code split1=";" #the string character spliting the header ){ wh.h <- grep('<th>', tbc) if(length(wh.h)>1){return(tbc)} tbc.h <- tbc[1:(wh.h-1)] if(wh.h==length(tbc)){return(tbc)} tbc.b <- tbc[(wh.h+1):length(tbc)] hh <- tbc[wh.h] hh <- gsub("<th>", "", hh, fixed=TRUE) hh <- gsub("<tr>", "", hh, fixed=TRUE) hh <- gsub("</tr>", "", hh, fixed=TRUE) hh <- strsplit(hh, split="</th>")[[1]] hh <- hh[-length(hh)] #remove the last empty element hh <- strsplit(hh, split=split1, fixed=TRUE) hh.l <- sapply(hh, length) short <- hh.l<max(hh.l) hh[short] <- lapply(hh[short], function(x){ c(x, rep(" ", max(hh.l)-length(x)))}) hh3 <-matrix(unlist(hh), nrow=max(hh.l)) hh3 <- apply(hh3, 1, function(x){ r1 <- "<tr> <th colspan=\'" colspan <- 1 if(length(x)>1){ for(i in 1:(length(x)-1)){#requre ncol for the table is 2+ if( gsub(" ", "", x[i])==gsub(" ", "", x[i+1])){ colspan <- colspan + 1 }else { r1 <- paste(r1, colspan, "\'>", x[i], "</th> <th colspan=\'") colspan <- 1 } } } r1 <- paste(r1, colspan, "\'>", x[length(x)], "</th> </tr>'") return(r1) #<th colspan='2'> }) return(c(tbc.h, hh3, tbc.b)) }
/scratch/gouwar.j/cran-all/cranData/BEACH/inst/app/functions/shinyFun.r
#Author: Danni Yu ([email protected]) #define global variables if(TRUE){ fL<<-'https://www.fda.gov/drugs/informationondrugs/approveddrugs/ucm279174.htm' FDA.Link <<- fL } #Begin 1. ---------------------------------------------------------------------# if(TRUE){ #Optimal basket design phase 1a/b study #Clinical Benifit and Biological Response are {0, 1} for {no or yes}. #Output@: ranked table {dose, Disease, baselineBiomarker, expectedUtility} #Output@: tree plot DT_frame <- function( blBMK=c('B0','B1'), #Baseline Biomarkers, required input tumorType=c('T0','T1','T2'), #Types of tumors, required input dose=c(20, 100), #numeric values of dose levels, required input #parameters prior_ti=c(0.1, 0.2, 0.2, 0.3, 0.05, 0.15),#PrioInfo Tumor Incidence: #length is length(blBMK)*length(tumorType) #values obtained from prior knowledge prior_prop=c(0.1, 0.9), #proportion of patients in the subgroup of dose #and bmk length is either length(dose) or #length(dose)*length(blBMK)*length(tumorType) #values obtained from prior knowledge prob_stop0 = c(0.75, 0.05), #Prob(not stop|dose) matching to the levels in #dose length is length(dose), the #proportions obtained from early phase trials prob_BR1 = c(0.1, 0.75), #Prob(BioResp=1|stop=0, dose, tumor, bmk), #length is either length(dose) or #length(dose)*length(blBMK)*length(tumorType) #values obtained from early phase trials prob_CB1_BR = c(0.8, 0.1), #Prob(ClinBenefit=1|BioResp=1) and #Prob(CB=1|BR=0). The lengh is either 2, or #2*length(dose)*length(blBMK)*length(tumorType) showTree = TRUE, #if FASLE only return the tree table showProb = TRUE, #if TRUE show the probablities on the tree and #return the probability table showBar = TRUE, #show the barplot of expected U(dose|{T,B}) #other args for plotting th.arrow = 0.8, #horizontal space between an arrow and target th.utDB = 1, #vertical space between dose sign and utility topRatio = 0.2, #the top ratio of joint p-values (or utilities) #that need to be colored topCol = 'red', #the color for the top joint p-values payoff = c(100, -100) #payoff value for CB=1 and CB=0 ){ #an internal function trunc values to 0, 1 trunc01 <- function(val){ val[val>1]<-1 val[val<-0]<-0 return(val) } #cleanup the payoff values if(is.character(payoff)){ payoff <- as.numeric(strsplit(payoff, split=',', fixed=TRUE)[[1]]) if(length(payoff)==1){ payoff<-c(max(0, payoff), min(0, payoff)) }else{payoff <- payoff[1:2]} } #cleanup the top ratio if(is.null(topRatio)) topRatio <- 0.2 topRatio <- trunc01( as.numeric(topRatio) ) #cleanup the input if(length(blBMK)==1){ blBMK<-strsplit(as.character(blBMK), split=',', fixed=T)[[1]] } if(length(tumorType)==1){ tumorType<-strsplit(as.character(tumorType), split=',', fixed=T)[[1]] } if(length(dose)==1){ dose<-strsplit(as.character(dose), split=',', fixed=T)[[1]] } if(length(prior_ti)==1){ prior_ti<-as.numeric(strsplit(as.character(prior_ti), split=',', fixed=T)[[1]]) } if(length(prior_prop)==1){ prior_prop<-as.numeric(strsplit(as.character(prior_prop), split=',', fixed=T)[[1]]) } if(length(prob_stop0)==1){ prob_stop0<-as.numeric(strsplit(as.character(prob_stop0), split=',', fixed=T)[[1]]) } if(length(prob_BR1)==1){ prob_BR1<-as.numeric(strsplit(as.character(prob_BR1), split=',', fixed=T)[[1]]) } if(length(prob_CB1_BR)==1){ prob_CB1_BR<-as.numeric(strsplit(as.character(prob_CB1_BR), split=',', fixed=T)[[1]]) } #check wether the probablities are matching to the actions if(showProb){ con1 <- length(prior_ti) == length(blBMK)*length(tumorType) con2 <- length(prior_prop) == length(dose) | length(prior_prop)==length(dose)*length(blBMK)*length(tumorType) con3 <- length(prob_stop0)==length(dose) | length(prob_stop0)==length(dose)*length(blBMK)*length(tumorType) con4 <- length(prob_BR1) == length(dose) | length(prob_BR1)==length(dose)*length(blBMK)*length(tumorType) con5 <- (length(prob_CB1_BR)==2)| ( length(prob_CB1_BR)==2*length(dose)*length(blBMK)*length(tumorType) ) if(!all(c(con1, con2, con3, con4, con5))){showProb<-FALSE} } #construct the output matrix if(TRUE){ numL.ClinBenif<- 2 numL.BioResp <- 2 numL.stop <- 2 numL.dose <- length(dose) numL.tumorType<- length(tumorType) numL.blBMK <- length(blBMK) ClinBenif <- rep(c('yes', 'no'), times=numL.BioResp*numL.stop*numL.dose*numL.tumorType*numL.blBMK) BioResp <- rep(rep(c('yes', 'no'), each=numL.ClinBenif), times=numL.stop*numL.dose*numL.tumorType*numL.blBMK) stop0 <- rep(rep(c('yes', 'no'), each=numL.ClinBenif*numL.BioResp), times=numL.dose*numL.tumorType*numL.blBMK) dose.in <- rep(rep(dose, each=numL.ClinBenif*numL.BioResp*numL.stop), times=numL.tumorType*numL.blBMK) BMK.in <- rep(rep(blBMK, each=numL.ClinBenif*numL.BioResp*numL.stop*numL.dose), times=numL.tumorType) tumor.in <- rep(rep(tumorType), each=numL.ClinBenif*numL.BioResp*numL.stop*numL.dose*numL.blBMK) numRow <- length(BMK.in) if(any(c(length(ClinBenif), length(BioResp), length(stop0), length(dose.in), length(tumor.in))!=numRow)){ stop('Error in level definition: check input value for blBMK, tumorType, dose') } mat <- cbind(tumorType=tumor.in, blBMK=BMK.in, dose=dose.in, stop0=stop0, BioResp=BioResp, ClinBenif=ClinBenif) fun1<-function(x, lastCol=NULL){ if(length(x)<=1) return(x) sel <- c(FALSE, x[2:length(x)]==x[1:(length(x)-1)]) if(!is.null(lastCol)) sel <- sel & (lastCol=="") x[sel] <- "" return(x) } mat.tab <- mat[mat[,"stop0"]=='no', ] m11 <- matrix(fun1(mat.tab[,1]), ncol=1) for(i in 2:ncol(mat.tab)){ m11 <- cbind(m11, fun1(mat.tab[,i], m11[,ncol(m11)])) } dimnames(m11) <- dimnames(mat.tab) mat.tab <- m11 if(is.matrix(mat.tab)) { mat.tab[which(mat.tab[,'dose']!=''), 'stop0'] <- 'no' } } #build arrows' coordinates if(showTree){ tot.col <- ncol(mat.tab) tot.row <- nrow(mat.tab) tot.col2<- tot.col+(tot.col-3)+2 #to enable the fitting lines longer text.size1 <- 3/log(tot.row) th <- th.arrow/log(tot.row) y.tt <- which(mat.tab[,1]!='') pnt <- data.frame(x=c(0, rep(1, length(y.tt))), y=c(1, y.tt), pch=rep(22,length(y.tt)+1), cex=rep(3,length(y.tt)+1)) arr <- data.frame(x0=rep(0, length(y.tt))+th*0.8, y0=rep(1, length(y.tt)), x1=rep(1, length(y.tt))-th*0.8, y1=y.tt-th, lty=rep(1, length(y.tt)), lwd=rep(1, length(y.tt)), col=rep('gray80', length(y.tt))) y.tt0 <-y.tt; dum1 <- 1 for(i in 2:tot.col){ y.tt <- which(mat.tab[,i]!='') lty1 <- 1; lwd1 <- 1; col1='gray80'; if (i>=4) {col1 <- 'black'} if (i==5) {lty1<-4; } if(i <= 3){ pnt <- rbind(pnt, data.frame(x=rep(i, length(y.tt)), y=y.tt, pch=22, cex=3) ) arr <- rbind(arr, data.frame(x0=rep(i-1, length(y.tt))+th*0.8, y0=rep(which(mat.tab[,i-1]!=''), each=length(y.tt)/length(y.tt0)), x1=rep(i, length(y.tt))-th*0.8, y1=y.tt, lty=rep(lty1, length(y.tt)), lwd=rep(lwd1, length(y.tt)), col=rep(col1, length(y.tt)))) }else{ arr <- rbind(arr, data.frame(x0=rep(i+dum1-2, length(y.tt))+th , y0=rep(which(mat.tab[,i-1]!=''), each=length(y.tt)/length(y.tt0)), x1=rep(i+dum1, length(y.tt))-th, y1=y.tt, lty=rep(lty1, length(y.tt)), lwd=rep(lwd1, length(y.tt)), col=rep(col1, length(y.tt)))) dum1 <- dum1+1 } y.tt0 <-y.tt } par(mar=c(0.2, 0.2, 0.2, 0.2), mfrow=c(1,1)) plot(0~0, col='white', ylim=c(0, tot.row+3), xlim=c(0, tot.col2+ 0.5), axes=F, ylab='', xlab='') dum2 <- 0; pos.col<-NULL; th.p <- 0.5; #threshold for probability X-axis position #joint probability for Pr(br=1,...), Pr(br=0, ...), Pr(br=1,...), Pr(br=0, ...), etc. num.mat.L <- nrow(mat.tab)/2 print(num.mat.L) j.prob <- rep(1, num.mat.L) for(i in 1:tot.col){ if(i>3) { dum2 <- dum2+1; th.p <- 1;} text(x=i+dum2, y=1:tot.row, labels=mat.tab[,i], cex=text.size1) pos.col <- c(pos.col, i+dum2) if(showProb){ # add probabilities to the tree and the the expected Utility for each action if(i==2){ text(x=i+dum2-th.p, y=which(mat.tab[,i]!=''), labels=prior_ti, cex=text.size1, col='gray') print(prior_ti) j.prob <- j.prob * rep(prior_ti, each=num.mat.L/length(prior_ti)) print(j.prob) }else if(i==3){ if(length(prior_prop)==length(dose)) prior_prop <- rep(prior_prop, numL.blBMK*numL.tumorType) text(x=i+dum2-th.p, y=which(mat.tab[,i]!=''), labels=prior_prop, cex=text.size1, col='gray') j.prob <- j.prob * rep(prior_prop, each=num.mat.L/length(prior_prop)) print(j.prob) }else if (i==4){ if(length(prob_stop0)==length(dose)) prob_stop0 <- rep(prob_stop0, numL.blBMK*numL.tumorType) text(x=i+dum2-th.p, y=which(mat.tab[,i]!=''), labels=prob_stop0, cex=text.size1, col='gray') j.prob <- j.prob * rep(prob_stop0, each=num.mat.L/length(prob_stop0)) print(j.prob) }else if (i==5){ if(length(prob_BR1)==numL.dose && numL.dose<numL.blBMK*numL.tumorType) prob_BR1 <- rep(prob_BR1, numL.blBMK*numL.tumorType) text(x=i+dum2-th.p, y=which(mat.tab[,i]=='yes'), labels=prob_BR1, cex=text.size1, col='gray') #the prob are Pr(br=1|...), Pr(br=0|...), Pr(br=1|...), Pr(br=0|...), etc. prob_BR <- as.vector(rbind(prob_BR1, 1-prob_BR1)) j.prob <- j.prob * prob_BR print(j.prob) }else if (i==6){ if(length(prob_CB1_BR)==2) prob_CB1_BR <- rep(prob_CB1_BR, numL.blBMK*numL.tumorType) #Pr(CB=1|BR=1,...), Pr(CB=1|BR=0,...), Pr(CB=1|BR=1,...), Pr(CB=1|BR=0,...), etc. text(x=i+dum2-th.p, y=which(mat.tab[,i]=='yes'), labels=prob_CB1_BR, cex=text.size1, col='gray') #for U(CB=0|....) #Pr(CB=0,BR=1|...), Pr(CB=0,BR=0|...),Pr(CB=0,BR=1|...), Pr(CB=0,BR=0|...), etc. j.prob0 <- round(payoff[2]*j.prob * trunc01(1-prob_CB1_BR), 3) #for U(CB=1|....) #Pr(CB=1,BR=1|...), Pr(CB=1,BR=0|...),Pr(CB=1,BR=1|...), Pr(CB=1,BR=0|...), etc. j.prob <- round(payoff[1]*j.prob * prob_CB1_BR, 3) #color the top 10% num.col <- round(length(j.prob)*topRatio) sub.u <- j.prob+j.prob0 top.p <- sort(sub.u, decreasing=TRUE)[1:num.col] col.p <- rep('gray', length(j.prob)) col.p[sub.u%in%top.p] <- topCol print(j.prob) text(x=i+dum2+1, y=which(mat.tab[,i]=='yes'), labels=j.prob, cex=text.size1, col=col.p) text(x=i+dum2+2.5, y=which(mat.tab[,i]=='yes'), labels=j.prob0, cex=text.size1, col='gray') #add the utility into the treat leave mat.tab <- cbind(mat.tab, U=rep("", nrow(mat.tab)), U0=rep("", nrow(mat.tab)), topColor=rep("", nrow(mat.tab))) print(prob_CB1_BR) print(j.prob) print(mat.tab) mat.tab[mat.tab[, i]=='yes', 'U']<-j.prob mat.tab[mat.tab[, i]=='yes', 'U0']<-j.prob0 mat.tab[mat.tab[, i]=='yes', 'topColor']<-col.p #get the index for top p values in output table wh.top.p<- which(mat.tab[,'topColor']==topCol) } } } points(x=pnt$x, y=pnt$y, pch=pnt$pch, cex=pnt$cex, col='gray80') arr$col <- as.character(arr$col) arrows(x0=arr$x0, y0=arr$y0, x1=arr$x1, y1=arr$y1, length=0.1, lty=arr$lty, lwd=arr$lwd, col=arr$col) nms <- c('Tumor\nType (T)', 'Baseline\nBiomarker (B)', '\nDose', 'Stop due\nto toxicity', 'Biological\nResponse', 'Clinical\nBenefit') mtext(text=nms, side=3, at=pos.col, padj=1.1) #It is alway true: P(BR|stop=1)=0 note1 <- c('P(stop=0|dose)', 'P(BR=1|stop=0, dose, TI)', 'P(CB=1|BR)') text(x=pos.col[-(1:3)]-1, y=tot.row, labels=note1, col='darkgreen', cex=text.size1) #Assume {dose, stop} is independent from the tumor incident of a biomarker in the tumor type. #TI is independent from dose, so P({T,B}|dose)=P({T,B}) note2 <- c('PriorInfo\nTumorIncidence(TI)', 'Proportion\nDoseLevel') text(x=c(pos.col[1]-0.5, pos.col[2]+0.5), y=tot.row, labels=note2, col='blue', cex=text.size1) if(showProb){ note3 <- c(paste0('U=', payoff[1], '*Prob(CB=1, BR,\nstop=0, dose, {T,B})'), paste0('U=', payoff[2], '*Prob(CB=0, BR,\nstop=0, dose, {T,B})')) pos.note3 <- tot.col2 + c(-1, 0.5) text(labels=note3, x=pos.note3, y=rep(tot.row+1, 2), cex=text.size1*0.7, col=c('red', 'magenta')) #add the expected utility mat.tab <- cbind(mat.tab, U_dTB=rep("", nrow(mat.tab)), U_dTB_color=rep("", nrow(mat.tab)), U_dTB_topColor=rep("", nrow(mat.tab))) dum.u <- 0; dum.col <- '' for(r in nrow(mat.tab):1){ if(mat.tab[r,'dose']=="" & mat.tab[r,'U']!=''){ payoff.pos <-as.numeric(mat.tab[r, 'U']) payoff.neg <-as.numeric(mat.tab[r, 'U0']) dum.u <- dum.u+ payoff.pos + payoff.neg if(mat.tab[r,'topColor']!='') dum.col<-mat.tab[r,'topColor'] }else if (mat.tab[r,'U']!=''){ payoff.pos <-as.numeric(mat.tab[r, 'U']) payoff.neg <-as.numeric(mat.tab[r, 'U0']) dum.u <- dum.u+ payoff.pos + payoff.neg mat.tab[r, 'U_dTB'] <- dum.u dum.u <- 0 if(mat.tab[r,'topColor']!='') { dum.col<-mat.tab[r,'topColor'] mat.tab[r, 'U_dTB_color']<-dum.col } } } top.U_dTB <- sort(as.numeric(mat.tab[,"U_dTB"]), decreasing=T) top.U_dTB <- top.U_dTB[1:ceiling(length(top.U_dTB)*topRatio)] u.tDB <- mat.tab[,'U_dTB']; wh.utDB <- which(u.tDB!='') mat.tab[wh.utDB, 'U_dTB_topColor']<-'black' mat.tab[wh.utDB&u.tDB%in%as.character(top.U_dTB), 'U_dTB_topColor']<-'red' u.tDB <- u.tDB[wh.utDB]; #u.tDB.col<-mat.tab[wh.utDB, 'U_dTB_color'] u.tDB.col<-mat.tab[wh.utDB, 'U_dTB_topColor'] note4 <- paste0('U(d,T,B)= ', u.tDB) if(showBar){ for(k in 1:length(u.tDB)){ lines(x=0+c(0, as.numeric(u.tDB[k])), y=rep(wh.utDB[k]-th.utDB, 2), lwd=8, col=rgb(0, 0, 255, alpha=80, maxColorValue=255) ) } lines(x=c(0,0), y=c(0,nrow(mat.tab)), col=rgb(0, 0, 255, alpha=80, maxColorValue=255)) } #u.tDB.col[u.tDB.col=='gray'] <- 'black' text(labels=note4, x=3, y=wh.utDB-th.utDB, cex=text.size1, col=u.tDB.col) } } return(mat.tab) } #Obtain combination annotation anno_tt_bmk <- function(bmk, tt, other.note=''){ bmk <- strsplit(as.character(bmk), split=',', fixed=TRUE)[[1]] tt <- strsplit(as.character(tt), split=',', fixed=TRUE)[[1]] ot <- paste(rep(tt, each=length(bmk)), rep(bmk, length(tt)), sep='_') ot <- paste(ot, collapse=',') ot <- paste(other.note, ot) return(ot) } } #End 1. -----------------------------------------------------------------------# #Begin 2. ---------------------------------------------------------------------# #1. Extension to have the CSF analysis #2. Generalized to user-defined variables #3. For discrete variables if(TRUE){ #expected loss function for discrete X variables #L(theta,a)=0 if x in the range else abs(lev-a)*abs(theta-th) #f(theta|data) is a binomial distriubtion #Users can define their own expected loss function however the input must #be [th, n, p_pos] and the output must be a vector of expected loss under #each Bayes decision levels my.eLoss <<- function( th, #the vector of thresholds (delta) of decision rule n, #the number of patients in a cohort p_pos, #the posterior probability of responding to drug #is the value update by data and affect decsion loss d.fun=pbinom #probability function (lower.tail=T) ){ #defin the distribution as binomial #d.fun=pbinom #the density function of p_pos #user can re-define the loss function from here to the end.... th <- sort(as.numeric(th)) len_a<- length(th) #~~~data construction~~~# #the number of decision levels is the number thresholds plus 1 xs <- 1:n #get all numbers in the binomial distribution xs_lev <- rep(1, n) #get decision levels for each number for(i in 1:len_a) xs_lev[xs>th[i]]<-i+1 #~~~get the expected loss for each action~~~# #a is the action level from 0 to len_a according to theta e_loss <- rep(0, len_a+1) #construct loss elements based on the higher bound for the lowest level i<-1 els.h<-abs(xs_lev - i)*abs(xs-th[i])*(1-d.fun(xs, size=n, prob=p_pos)) e_loss[i]<-sum(els.h[xs_lev>i]) #expected loss from level 2 to lev_a for(i in 2:len_a){#if taking the action as level i els.h<-abs(xs_lev - i)*abs(xs-th[i])*(1-d.fun(xs, size=n, prob=p_pos)) els.l<-abs(xs_lev - i)*abs(xs-th[i-1])*(1-d.fun(xs, size=n, prob=p_pos)) e_loss[i] <- sum(els.h[xs_lev>i]) + sum(els.l[xs_lev<i]) } #for highest level #construct loss elements based on the lower bound i <- len_a els.l<-abs(xs_lev - i-1)*abs(xs-th[i])*(1-d.fun(xs, size=n, prob=p_pos)) e_loss[i+1]<-sum(els.l[xs_lev<=i]) return(e_loss) } #improved function for Baysian decision theory with Critical Success Factor #available to add or remove variables #available to specify the Bayse loss function #available to select utility bar and the loss bar #Clinical Benifit and Biological Response are {0, 1} for {no or yes}. #Output@: ranked table {dose, Disease, baselineBiomarker, expectedUtility} #Output@: tree plot #function name: Bayesian Decision Theory Utility and Loss #fixing the expected utility and make loss function flexible BDT_UaL <- function( levVars="B1::T1::coh1::BR1,B1::T1::coh2::BR1,B1::T2::coh3::BR2", #variables and levels separated by "::" dr_lev="nogo::go,nogo::go,nogo::go", #order does matter. #decision rule labels incidence="0.3,0.3,0.1", #Biomarker incidence in the tumor type #values obtained from prior knowledge pBprior=NULL, #the hyper parameters "alph, beta" #if NULL, then alpha=1+incidence #beta=2-incidence #if not NULL, the value should be like #"1.3 1.7,1.3 1.7, 1.1 1.9," n_ij="10, 10, 10", #sample sizes for each cohort #values obtained from decision makers dr_th="0.1,0.5,0.6", #decision rule threshold (delta) #if 3 levels of decision rule such as #dr_lev="go::moreData::nogo," then #dr_th="0.9::0.3," drFunc=my.eLoss, #user-defined Bayes decision loss function #input: [th, n, p_pos] #output: a vector of Bayes decision loss showBar=TRUE, #show the barplot of utility & loss th.arrow= 0.8, #horizontal space between an arrow and target payoff= c(10, -1) #payoff value for utility, only two values #gain vs lost ){ #an internal function truncates values to 0, 1 trunc01 <- function(val){ val[val>1]<-1 val[val<-0]<-0 return(val) } #an internal function gets the hierarchical variables my.split1 <- function(mylab="", s1=",", s2="::"){ if(length(mylab)==1 & is.character(mylab)){ L1 <- strsplit(mylab, split=s1)[[1]] }else{L1 <- mylab} if(length(L1)==0) return('L1 in my.split1 is missing.') if(is.null(s2)) return(L1) if(all(is.character(L1))){ L2 <- strsplit(L1, split=s2) }else{ L2 <- mylab } return(L2) #mat1<-t(matrix(unlist(L2), ncol=length(L2))) } #cleanup the input parameters if(TRUE){ #sample size proportions if(is.null(n_ij) || all(n_ij=='')|all(incidence=='')| all(dr_th=='')) return(NULL) n_1 <- as.numeric(unlist(my.split1(n_ij))) n_rt<- n_1/sum(n_1) #incidences if(is.null(incidence)) return(NULL) incd<- as.numeric(unlist(my.split1(incidence))) p.0<-list() for(o in 1:length(incd)){ p.0[[o]]<-c(1+incd[o], 2-incd[o]) } if(!is.null(pBprior) && pBprior!="~" && gsub(" ", "", pBprior)!=""){ p.0p<-my.split1(pBprior, s2=" ") p.0p<-lapply(p.0p, function(x){x[x!=""]}) for(o in 1:length(p.0)){ p.0[[o]] <- p.0[[o]]+as.numeric(p.0p[[o]]) } #note the length p.0 == the leve of plans } num.p0 <- length(p.0) #if using default threshold if(dr_th=="~"){ th1 <- list() for(o in 1:length(p.0)) th1[[o]] <- p.0[[o]][1]/sum(p.0[[o]]) }else{ th1 <- lapply(my.split1(dr_th),as.numeric) } print(th1) #cleanup the payoff values if(is.character(payoff)){ payoff <- as.numeric(strsplit(payoff, split=',', fixed=TRUE)[[1]]) if(length(payoff)==1){ payoff<-c(payoff, 0) }else{ payoff <- payoff[1:2] } } } #construct the decision tree with user-defined variables if(TRUE){ if(is.null(levVars)) return(NULL) LV0 <- LV <- my.split1(levVars) num.var <- length(LV[[1]]) drLV <- my.split1(dr_lev) num.dr <- length(drLV[[1]]) if(length(LV)!=length(drLV) | length(LV)!=num.p0){ #print('Error: lengths of decision rule and layers do not match!') return(NULL) } iLV <- E.L <- U <- p.1 <- list() for(o in 1:length(LV)){ th2<-round(th1[[o]]*n_1[o]) p.1[[o]] <- p.0[[o]][1]/sum(p.0[[o]]) eL <- drFunc(th=th2, n=n_1[o], p_pos=p.1[[o]] ) E.L[[o]]<-eL #expected loss U[[o]] <- incd[o]*n_rt[o]*p.1[[o]]*payoff[1]+ incd[o]*n_rt[o]*(1-p.1[[o]])*payoff[2] #expected utility if(o>1){ o.wh <- which(LV0[[o]]!=LV0[[o-1]])[1] if(length(o.wh)==0) o.wh<-1 no.wh <- which(LV0[[o]]==LV0[[o-1]]) LV[[o]][ no.wh[no.wh<o.wh] ]<-'' } iLV[[o]] <- c(LV[[o]][1:(num.var-1)], paste0(LV[[o]][num.var], ", n=", n_1[o], "\nI=", incd[o], ", U=", round(U[[o]],3), ", p=", round(p.1[[o]],3) ), paste0(drLV[[o]][1],": go if r>", th2[1], ", E(L)=", round(eL[1],3))) if(num.dr==1) next for(h in 2:num.dr){ if(h==num.dr){ iLV[[o]] <- c(iLV[[o]], rep('', num.var), paste0(drLV[[o]][h], ": stop if r<=",th2[h-1], ", E(L)=", round(eL[h],3)) ) }else{ iLV[[o]] <- c(iLV[[o]], rep('', num.var), paste0(drLV[[o]][h], ": ",th2[h-1], "<= r <",th2[h], ", E(L)=", round(eL[h],3)) ) } } } varMat <- t(matrix(unlist(iLV), nrow=num.var+1)) #E.L[[o]]: expected Bayes decision loss #U[[o]]: utility of plan } #build arrows and coordinates to show the decision tree if(TRUE){ tot.col <- ncol(varMat) max.nchar <- apply(varMat, 2, function(x){max(nchar(x))}) cex.1char<- 0.1 tot.row <- nrow(varMat) tot.col2<- tot.col+2 #to enable the fitting lines longer text.size1 <- 3/log(tot.row) th.a <- th.arrow/log(tot.row) #about arrow locaiton #for Layer 1 lty1 <- 1; lwd1 <- 1; col1='gray80'; y.tt <- which(varMat[,1]!='') pnt <- data.frame(x=c(0, rep(1, length(y.tt))), y=c(1, y.tt), lab=c('', varMat[y.tt,1]), pch=rep(22,length(y.tt)+1), cex=rep(3,length(y.tt)+1)) arr <- data.frame(x0=rep(0, length(y.tt)), y0=rep(1, length(y.tt)), x1=rep(1, length(y.tt)), y1=y.tt, lty=rep(1, length(y.tt)), lwd=rep(1, length(y.tt)), col=rep(col1, length(y.tt))) shf <- sum(max.nchar[1])*cex.1char y.tt0 <- y.tt for(i in 2:tot.col){ y.tt <- which(varMat[,i]!='') pnt <- rbind(pnt, data.frame(x=rep(i+shf, length(y.tt)), y=y.tt, lab=varMat[y.tt,i], pch=22, cex=3) ) wh.a1<-which(!y.tt%in%y.tt0) y.tt0a <- y.tt for(a in wh.a1){ y.tt0a[a] <- y.tt0a[a-1] } arr <- rbind(arr, data.frame(x0=rep(i-1+shf, length(y.tt)), y0=y.tt0a, x1=rep(i+shf, length(y.tt)), y1=y.tt, lty=rep(lty1, length(y.tt)), lwd=rep(lwd1, length(y.tt)), col=rep(col1, length(y.tt)))) shf <- sum(max.nchar[1:i])*cex.1char y.tt0 <- y.tt } par(mar=c(0.2, 0.2, 0.2, 0.2), mfrow=c(1,1)) plot(y~x, data=pnt, col='gray80', pch=pnt$pch, ylim=c(0, tot.row), xlim=c(0, tot.col2+shf+0.5), axes=F, ylab='', xlab='') text(x=pnt$x, y=pnt$y, labels=pnt$lab, adj=-0.07) arrows(x0=arr$x0, y0=arr$y0, x1=arr$x1, y1=arr$y1, length=0.1, lty=arr$lty, lwd=arr$lwd, col=arr$col) } #add barplot of utility and loss if(showBar){ u.x0<-rep(0, length(LV)) u.y0<-which(varMat[,ncol(varMat)-1]!='') u.x1<-unlist(U) col.bar1 <- rgb(0, 0, 255, alpha=80, maxColorValue=255) abline(v=0, col=col.bar1) for(i in 1:length(u.y0)){ lines(x=c(u.x0[i], u.x1[i]), y=c(u.y0[i], u.y0[i]), lwd=8, col=col.bar1) } l.x0<-rep(tot.col2+shf, nrow(varMat)) l.y0<-1:nrow(varMat) l.x1<-l.x0-unlist(E.L) col.bar2 <- rgb(255, 0, 0, alpha=80, maxColorValue=255) abline(v=tot.col2+shf, col=col.bar2) for(i in 1:length(l.y0)){ lines(x=c(l.x0[i], l.x1[i]), y=c(l.y0[i], l.y0[i]), lwd=8, col=col.bar2) } } return(list(dat=varMat, BayesLoss=E.L, U=U, p=p.1)) } } #define global variables for FDA_log analysis if(TRUE){ #get a subset key.words <<- c('all', 'NSCLC|lung', 'urothelial', 'gastrointestinal', 'msi', 'breast', 'head', 'hcc', 'other') mySelect<-function(vec1, sp=NULL, ctype='all', fdaLink=FALSE, allkeys=key.words ){ if(!is.null(fdaLink)&&as.logical(fdaLink)){ vec1 <- readLines(fL) #vec1 <- vec1[grepl('<li>', vec1)] vec1 <- vec1[grepl('approv', vec1)] if(length(vec1)==1){ vec1<-vec1[grepl('href=\"#updates\"', vec1, fixed=T)] vec1<-strsplit(split='<li>', vec1, fixed=TRUE)[[1]] vec1<-gsub('\t| ','', vec1) vec1 <- vec1[grepl('approv', vec1)] } if(length(vec1)==0){ return(data.frame(FDA_log='Fail to reach the link.')) } } if(is.null(sp) || is.null(ctype)){ return(data.frame(FDA_log='no data')) } if(!ctype%in%c('all')){ if(ctype=='other'){ ctype <- paste(allkeys[!allkeys%in%c('all','other')], collapse='|') vec1<-vec1[!grepl(ctype, vec1, ignore.case=T)] }else{ vec1<-vec1[grepl(ctype, vec1, ignore.case=T)] } if(length(vec1)==0){ return(data.frame(FDA_log='The disease is not found.')) } } if(sp==''|sp=='~'){ if(is.data.frame(vec1)){ dat1 <- data.frame(FDA_log=vec1[,1]) }else if (is.vector(vec1)){ dat1<- data.frame(FDA_log=vec1) }else{ dat1<-data.frame(FDA_log='no data') } return(dat1) } vec2<- vec1[grepl( paste(paste0("(?=.*",strsplit(as.character(sp), split='&')[[1]], ")"), collapse=""), vec1, perl=T, ignore.case=T)] dat1<-data.frame(FDA_log=vec2) return(dat1) } } #End 2. -----------------------------------------------------------------------# #Begin 3. ---------------------------------------------------------------------# #1.add contineus variables #2.add benchmark reference if(TRUE){ #A function for P(y.trt-y.ref<x) given the equal length samples of y.trt, y.ref prob.diff <- function(x, y.diff=NULL, y.trt=NULL, y.ref=NULL){ if(!is.null(y.diff)){ dif1 <- y.diff[is.finite(y.diff)] return( mean(dif1<x, na.rm=T) ) }else if(!is.null(y.trt) & !is.null(y.ref) & length(y.trt)==length(y.ref)){ dif1 <- (y.trt-y.ref) dif1 <- dif1[is.finite(dif1)] return( mean(dif1<x, na.rm=T) ) }else{return(0)} } #functions getting the random samples from given distribution #rbinom with n and pi #rlnorm with meanlog and sdlog #expected loss function for either discrete or continues X variables #L(theta,a)=0 if x in the range else abs(lev-a)*abs(theta-th) #f(theta|data) is a binomial distriubtion #Users can define their own expected loss function however the input must #be [th, n, p_pos] and the output must be a vector of expected loss under #each Bayes decision levels eLoss.diff <<- function( th=NULL, #the vector of thresholds (delta) of decision rule sample1, #a vector of samples under treatment assumption sample2, #a vector of samples under control assumption sample1.prob, #a vector of samples prob under treatment assumption sample2.prob, #a vector of samples prob under control assumption len_cutoffs=NULL #the number of cutoffs or thresholds of a decision rule ){ prob.1g2<-NULL #create the matrix of difference and the probablity if(!is.vector(sample1) | !is.vector(sample1.prob) | length(sample1)!=length(sample1.prob)){ stop('Sample1 input is wrong for eLoss.diff') }else if(!is.vector(sample2) | !is.vector(sample2.prob) | length(sample2)!=length(sample2.prob)){ stop('Sample2 input is wrong for eLoss.diff') }else{ n.r <- length(sample1) n.c <- length(sample2) sam1.mat<-matrix(sample1, nrow=n.r, ncol=n.c) sam1prob.mat<-matrix(sample1.prob, nrow=n.r, ncol=n.c) sam2.mat<-t(matrix(sample2, nrow=n.c, ncol=n.r)) sam2prob.mat<-t(matrix(sample2.prob, nrow=n.c, ncol=n.r)) prob.mat <- sam1prob.mat*sam2prob.mat diff.mat <- sam1.mat - sam2.mat y2sampleD <- as.vector(diff.mat) ord <- order(y2sampleD) y2sampleD <- y2sampleD[ord] y2sampleD.prob <- as.vector(prob.mat)[ord] prob.1g2 <- sum(y2sampleD.prob[y2sampleD>0]) } #Recomend threshold maximizing the loss difference if(is.null(th)||th%in%c("", "~", "-")){ if(is.null(len_cutoffs)){len_cutoffs <- 1} th.prob <- seq(0,1, by=1/(len_cutoffs+1)) th.prob <- th.prob[c(-1, -length(th.prob))] th <- quantile(y2sampleD, th.prob) recom.th <- TRUE }else{recom.th<-FALSE} #order the thereshold for a decision rule th <- sort(as.numeric(th)) len_a<- length(th) n <- length(y2sampleD) #~~~data construction~~~# #the number of decision levels is the number thresholds plus 1 xs <- y2sampleD #get the distribution consits of samples xs_lev <- rep(1, n) #get decision levels for each sample for(i in 1:len_a) { xs_lev[xs>th[i]]<-i+1 } #~~~get the expected loss for each action~~~# #a is the action level from 0 to len_a according to theta e_loss <- rep(0, len_a+1) #construct loss elements based on the higher bound for the lowest level #i<-1 els.h<-abs(xs_lev - 1)*abs(xs-th[1])*y2sampleD.prob e_loss[1]<-sum(els.h[xs_lev>1]) #expected loss from level 2 to lev_a for(i in 2:len_a){#if taking the action as level i els.h<-abs(xs_lev - i)*abs(xs-th[i])*y2sampleD.prob els.l<-abs(xs_lev - i)*abs(xs-th[i-1])*y2sampleD.prob e_loss[i] <- sum(els.h[xs_lev>i]) + sum(els.l[xs_lev<i]) } #for highest level #construct loss elements based on the lower bound els.l<-abs(xs_lev - len_a-1)*abs(xs-th[len_a])*y2sampleD.prob e_loss[len_a+1]<-sum(els.l[xs_lev<=len_a]) if(recom.th){ return(list(e_loss=e_loss, th=th, p.1g2=prob.1g2)) }else{ return(list(e_loss=e_loss, p.1g2=prob.1g2)) } } #A revised function of generating random variable from a lognormal distb rlnorm2 <- function(B=1000000, m, s){ location <- log(m^2 / sqrt(s^2 + m^2)) shape <- sqrt(log(1 + (s^2 / m^2))) smp <- rlnorm(n=B, location, shape) return(smp) } #improved function for Baysian decision theory with Critical Success Factor #take the difference between treatment variable and the benchmark control #available to add or remove variables #available to specify the Bayse loss function #available to select utility bar and the loss bar #Clinical Benifit and Biological Response are {0, 1} for {no or yes}. #Output@: ranked table {dose, Disease, baselineBiomarker, expectedUtility} #Output@: tree plot #function name: Bayesian Decision Theory Utility and Loss #fixing the expected utility and make loss function flexible BDT_UaL.diff <- function( levVars="B1::T1::coh1::BR1,B1::T1::coh2::BR1,B1::T2::coh3::BR2", #variables and levels separated by "::" dr_lev="No Go::Go,No Go::Go,No Go::Go", #order does matter. #decision rule labels incidence="0.3,0.3,0.1", #Biomarker incidence in the tumor type #values obtained from prior knowledge numRsp=NULL, #the hyper parameters "alph, 2-alpha" #if NULL, then alpha=1+incidence and beta=2-incidence, #and only trt ORR is onsidered without the benchmark control ORR #if not NULL, the value should be like #"1.3vs1.3,1.3vs1.2, 1.1vs1" matches "TRT_ORRvsCTR_ORR" muTTE=NULL, sdTTE=NULL, #the mean and sd of TTE variables #if not NULL, e.g. "5vs5, 9vs2, 10vs8" and "1vs1, 1vs1, 1vs1" #matches "TRTvsCTR" n_ij="10, 10, 10", #sample sizes for each cohort #or "10vs20,10vs80,10vs10" for "TRTvsCTR" #values obtained from decision makers dr_th="0.1,0.5,0.6", #decision rule threshold for ORR #if 3 levels of decision rule such as #dr_lev="go::moreData::nogo," then #dr_th="0.9::0.3," #input: [th, n, p_pos] #output: a vector of Bayes decision loss showBar=TRUE, #show the barplot of utility & loss th.arrow= 0.8, #horizontal space between an arrow and target payoff= c(10, -1), #payoff value for utility, only two values #gain vs lost bar.wid=8, #the width of the horizontal bar Bsample=5000 #number of bootstrapping samples ){ #a list of difference in ORR between trt and ctr RT.diff <- list() #a list of difference in tte between trt and ctr tte.diff<- list() #by default, the difference variable between trt and ctr is not used. #it will be TRUE if 'vs' shows in the string of numRsp useRspDiff<-FALSE #it will be TRUE if 'vs's shows in the string muTTE useTteDiff<-FALSE #an internal function gets the hierarchical variables #seperated by "::" for different levels of a variable #seperated by "," for different subgroups #seperated by "vs" for treatment vs control my.split1 <- function(mylab="", s1=",", s2="::"){ if(length(mylab)==1 & is.character(mylab)){ #the input is a string L1 <- strsplit(mylab, split=s1)[[1]] }else{ #when the input is already a vector L1 <- mylab } if(length(L1)==0) return('L1 in my.split1 is missing.') if(is.null(s2)) return(L1) if(all(is.character(L1))){ L2 <- strsplit(L1, split=s2) }else{ L2 <- mylab } return(L2) } #cleanup the input parameters if(TRUE){ #Cleanup sample size parameters if(is.null(n_ij) || all(n_ij=='')|all(incidence=='')) return(NULL) if(grepl('vs',n_ij)){ nL <- my.split1(n_ij, s2='vs') n_1.trt<- as.numeric(as.vector(sapply(nL,function(x){x[1]}))) n_1.ctr<- as.numeric(as.vector(sapply(nL,function(x){x[2]}))) n_1 <- n_1.trt #n_1 alwasy has values for treatment sizes if(length(n_1.trt)!=length(n_1.ctr)) return(NULL) } else { n_1 <- as.numeric(unlist(my.split1(n_ij))) n_1.trt <- n_1.ctr <- n_1 } n_rt<- n_1/sum(n_1) #incidences if(is.null(incidence)) return(NULL) incd<- as.numeric(unlist(my.split1(incidence))) #for treatment prior parameters of Beta Variable pi based on incidences p.0<-list() for(o in 1:length(incd)){ p.0[[o]]<-c(1+incd[o], 2-incd[o]) } #posterior parameters of Beta Variable pi updated by trt ORR #and get RT.diff if(!is.null(numRsp) && numRsp!="~" && gsub(" ", "", numRsp)!=""){ if(!(grepl("vs", numRsp)) && !is.null(n_1)){ #when no sample sizes for control or benchmark #only the Beta posterrior parameters are updated p.0p<-as.numeric(my.split1(numRsp, s2=NULL)) if(length(incd)!=length(p.0p)) return(NULL) if(length(p.0p)!=length(n_1)){ #use the probability only without the sample sizes #if(any(p.0p>1|p.0p<0)) return(NULL) for(o in 1:length(p.0)){ if(p.0p[o]>1){ p.0[[o]]<-p.0[[o]]+c(p.0p[o], n_1[o]-p.0p[o]) }else{ p.0[[o]]<-p.0[[o]]+c(p.0p[o], 1-p.0p[o]) } } } else { for(o in 1:length(p.0)){ if(p.0p[o]>1){ p.0[[o]]<-p.0[[o]]+c(p.0p[o], n_1[o]-p.0p[o]) }else{ p.0[[o]]<-p.0[[o]]+c(p.0p[o], 1-p.0p[o]) } } } #note: p.0 is a listing object. Each element is a vector of #the two Beta parameters. The total number of elements matches #the number of incidences or cohorts/arms. }else{ #when number of responders in control are inserted in numRsp #then the difference between trt and ref is given p.0p <- my.split1(numRsp, s2='vs') p.0p.trt<-as.numeric(sapply(p.0p, function(x){x[1]})) p.0p.ctr<-as.numeric(sapply(p.0p, function(x){x[2]})) if(is.null(n_1.ctr)) n_1.ctr <- n_1.trt if(!is.null(n_1.ctr) & length(p.0p)==length(n_1.ctr)){ for(o in 1:length(p.0p)){ if(p.0p.trt[o]>1){#if the new alpha>1 p.0[[o]] <- p.0[[o]]+c(p.0p.trt[o], n_1[o]-p.0p.trt[o]) }else{ p.0[[o]] <- p.0[[o]]+n_1[o]*c(p.0p.trt[o], 1-p.0p.trt[o]) #p.0p.trt[o] <- round(p.0p.trt[o], n_1[o]) p.0p.trt[o] <- p.0p.trt[o] } if(p.0p.ctr[o]>1){ prob.ctr<-p.0p.ctr[o]/n_1.ctr[o] }else{ prob.ctr<-p.0p.ctr[o]; p.0p.ctr[o]<-p.0p.ctr[o]*n_1.ctr[o] } if(F){ sam.trt<-rbinom(Bsample, size=n_1.trt[o], prob=p.0[[o]][1]/sum(p.0[[o]]) ) sam.ctr<-rbinom(Bsample, size=n_1.ctr[o], prob=prob.ctr ) sam.trt<-sam.trt[!is.na(sam.trt) & is.finite(sam.trt)] sam.ctr<-sam.ctr[!is.na(sam.ctr) & is.finite(sam.ctr)] } sam.trt <- sam.ctr <- 0:n_1.trt[o] sam.trt.prob<-dbinom(sam.trt, size=n_1.trt[o], prob=p.0[[o]][1]/sum(p.0[[o]]) ) sam.ctr.prob<-dbinom(sam.ctr, size=n_1.ctr[o], prob=prob.ctr ) RT.diff[[o]] <- list() RT.diff[[o]]$sample1 <- sam.trt RT.diff[[o]]$sample2 <- sam.ctr RT.diff[[o]]$sample1.prob <- sam.trt.prob RT.diff[[o]]$sample2.prob <- sam.ctr.prob print(paste('sum(sam.trt.prob)', sum(sam.trt.prob))); print(paste(p.0[[o]][1]/sum(p.0[[o]]), ',', prob.ctr)) print(quantile(sam.trt.prob)) print(quantile(sam.trt)) print(quantile(sam.ctr)) print(paste('sum(sam.ctr.prob)', sum(sam.ctr.prob))) } useRspDiff<-TRUE }else{return(NULL)} } #note: RT.diff[[o]] is a listing object for the o_th cohorts/arms. #Four objects are saved in the listting RT.diff[[o]]: #sample1, sample1.prob for treatment and #sample2, sample2.prob for control } #Note:the length p.0 == the level of plans or #cohorts num.p0 <- length(p.0) #When using the default threshold if(!is.null(dr_th) && dr_th%in%c("~", "")){ th1 <- list() #use prevalence for the thresholds for(o in 1:length(p.0)) th1[[o]] <- p.0[[o]][1]/sum(p.0[[o]]) }else{ #when the thresholds are defined in a string such as "3::5,4::6" #then 3 and 4 are the lower cutoff for cohort 1 and 2, #5 and 6 are the higher cutoff for cohort 1 and 2. th1 <- lapply(my.split1(dr_th),as.numeric) } #note: th1 is a listing object. Each element is a vector of ORR #cutoffs. The number of elements matches the number of incidences. #cleanup the two parameters for lognormal variables, such as TTE #Note: The benchmark control reference must be provided for the analysis tte.mu <- tte.sd <- list() if(!is.null(muTTE) & !is.null(sdTTE) & grepl('vs', muTTE) & grepl('vs', sdTTE)){ #a listing object of lognormal means. each element is the two means #of trt vs cntr tte.mu<-lapply(my.split1(muTTE, s2='vs'), as.numeric) tte.sd<-lapply(my.split1(sdTTE, s2='vs'), as.numeric) if(length(tte.mu)==length(tte.sd) & all(sapply(tte.mu, length)==2) & all(sapply(tte.sd, length)==2) & length(tte.mu)==length(incd) ){ for(o in 1:length(incd)){ cy.trt <- rlnorm2(B=Bsample, m=tte.mu[[o]][1], s=tte.sd[[o]][1]) cy.ctr <- rlnorm2(B=Bsample, m=tte.mu[[o]][2], s=tte.sd[[o]][2]) tte.diff[[o]] <- cy.trt-cy.ctr tte.diff[[o]] <- tte.diff[[o]][is.finite(tte.diff[[o]]) & !is.na(tte.diff[[o]])] } useTteDiff<-TRUE } } #cleanup the payoff values if(is.character(payoff)){ payoff <- as.numeric(strsplit(payoff, split=',', fixed=TRUE)[[1]]) if(length(payoff)==1){ payoff<-c(payoff, 0) }else{ payoff <- payoff[1:2] } } } #construct the decision tree with user-defined variables #calculate Utility and Loss if(TRUE){ #A listing object of plans. #Each element is a vector of critical variables. if(is.null(levVars)) return(NULL) LV0 <- LV <- my.split1(levVars) num.var <- length(LV[[1]]) #number of variables #A listing object of decision rules. #Each element is a vector of decision thresholds drLV <- my.split1(dr_lev) num.dr <- length(drLV[[1]]) if(length(LV)!=length(drLV) | length(LV)!=num.p0){ #print('Error: lengths of decision rule and layers do not match!') return(NULL) } #lost, utility, response probability pi. #p.2 is the posterior prob for benefit. iLV <- E.L <- U <- Utte <- p.1 <-p.2 <- list() for(o in 1:length(LV)){ #conver the ORR_trt decision thresholds into numRsp_trt th2.lab<-th2<-round(th1[[o]]*n_1[o]) #eLoss.diff(th, y2sampleD) if(useRspDiff){ #if benchmark ref is available then the threshold th2 change to be #the difference. But th2.lab still keep as the original one th2 <- round((th1[[o]]-p.0p.ctr[o]/n_1.ctr[o])*n_1[o]) print(th2); print(paste("length(RT.diff[[o]])", length(RT.diff[[o]]))); eL <- eLoss.diff(th=th2, sample1=RT.diff[[o]]$sample1, sample2=RT.diff[[o]]$sample2, sample1.prob=RT.diff[[o]]$sample1.prob, sample2.prob=RT.diff[[o]]$sample2.prob) #probability of the difference pi_trt-pi_ctr>0 print(paste0('p.1[[',o,']]=', p.1[[o]] <- eL$p.1g2)) eL <- eL$e_loss }else{ #expected response probability pi_trt p.1[[o]] <- p.0[[o]][1]/sum(p.0[[o]]) print(p.1[[o]]) eL <- my.eLoss(th=th2, n=n_1[o], p_pos=p.1[[o]] ) } E.L[[o]]<-eL #expected loss #expected utility based on ORR U[[o]] <- incd[o]*n_rt[o]*p.1[[o]]*payoff[1]+ incd[o]*n_rt[o]*(1-p.1[[o]])*payoff[2] #expected utility based on TTE if(useTteDiff){ #P(mu_trt-mu_ctr>0|...) p.2[[o]] <- mean(tte.diff[[o]]>0) Utte[[o]] <- incd[o]*n_rt[o]*p.2[[o]]*payoff[1]+ incd[o]*n_rt[o]*(1-p.2[[o]])*payoff[2] } if(o>1){ o.wh <- which(LV0[[o]]!=LV0[[o-1]])[1] if(length(o.wh)==0) o.wh<-1 no.wh <- which(LV0[[o]]==LV0[[o-1]]) LV[[o]][ no.wh[no.wh<o.wh] ]<-'' } iLV[[o]] <- c(LV[[o]][1:(num.var-1)], paste0(LV[[o]][num.var], ", n=", n_1[o], "\nI=", incd[o], ", U_orr=", round(U[[o]],3), ifelse(useRspDiff, ", p(trt>ref)=", ", p="), round(p.1[[o]],3), ifelse(useTteDiff, paste0("\nU_tte=",round(Utte[[o]],3), ", m_trt=", tte.mu[[o]][1], ", m_ref=", tte.mu[[o]][2], ", s_trt=", tte.sd[[o]][1], ", s_ref=", tte.sd[[o]][2]), "")), paste0(drLV[[o]][1],": go if r>", th2.lab[1], ", E(L)=", round(eL[1],3))) if(num.dr==1) next for(h in 2:num.dr){ if(h==num.dr){ iLV[[o]] <- c(iLV[[o]], rep('', num.var), paste0(drLV[[o]][h], ": stop if r<=",th2.lab[h-1], ", E(L)=", round(eL[h],3)) ) }else{ iLV[[o]] <- c(iLV[[o]], rep('', num.var), paste0(drLV[[o]][h], ": ",th2.lab[h-1], "<= r <",th2.lab[h], ", E(L)=", round(eL[h],3)) ) } } } varMat <- t(matrix(unlist(iLV), nrow=num.var+1)) #E.L[[o]]: expected Bayes decision loss #U[[o]]: utility of plan based on ORR #Utte[[o]]: utility based on tte } #build arrows and coordinates to show the decision tree if(TRUE){ tot.col <- ncol(varMat) max.nchar <- apply(varMat, 2, function(x){max(nchar(x))}) cex.1char<- 0.05 #affect distance between text and arrow tot.row <- nrow(varMat) tot.col2<- tot.col+2 #to enable the fitting lines longer text.size1 <- 3/log(tot.row) th.a <- th.arrow/log(tot.row) #about arrow locaiton #for Layer 1 lty1 <- 1; lwd1 <- 1; col1='gray80'; y.tt <- which(varMat[,1]!='') pnt <- data.frame(x=c(0, rep(1, length(y.tt))), y=c(1, y.tt), lab=c('', varMat[y.tt,1]), pch=rep(22,length(y.tt)+1), cex=rep(3,length(y.tt)+1)) arr <- data.frame(x0=rep(0, length(y.tt)), y0=rep(1, length(y.tt)), x1=rep(1, length(y.tt)), y1=y.tt, lty=rep(1, length(y.tt)), lwd=rep(1, length(y.tt)), col=rep(col1, length(y.tt))) shf <- sum(max.nchar[1])*cex.1char y.tt0 <- y.tt for(i in 2:tot.col){ y.tt <- which(varMat[,i]!='') pnt <- rbind(pnt, data.frame(x=rep(i+shf, length(y.tt)), y=y.tt, lab=varMat[y.tt,i], pch=22, cex=3) ) wh.a1<-which(!y.tt%in%y.tt0) y.tt0a <- y.tt for(a in wh.a1){ y.tt0a[a] <- y.tt0a[a-1] } arr <- rbind(arr, data.frame(x0=rep(i-0.5+shf, length(y.tt)), y0=y.tt0a, x1=rep(i+shf, length(y.tt)), y1=y.tt, lty=rep(lty1, length(y.tt)), lwd=rep(lwd1, length(y.tt)), col=rep(col1, length(y.tt)))) shf <- sum(max.nchar[1:i])*cex.1char y.tt0 <- y.tt } par(mar=c(0.2, 0.2, 0.2, 0.2), mfrow=c(1,1)) plot(y~x, data=pnt, col='gray80', pch=pnt$pch, ylim=c(0, tot.row), xlim=c(0, tot.col2+shf+0.5), axes=F, ylab='', xlab='') text(x=pnt$x, y=pnt$y, labels=pnt$lab, adj=-0.07) arrows(x0=arr$x0, y0=arr$y0, x1=arr$x1, y1=arr$y1, length=0.1, lty=arr$lty, lwd=arr$lwd, col=arr$col) } #add barplot of utility and loss if(showBar){ # bar.wid <- 8 u.x0<-rep(0, length(LV)) u.y0<-which(varMat[,ncol(varMat)-1]!='') u.x1<-unlist(U) if(useTteDiff){utte.x1<-unlist(Utte)}else{utte.x1<-NULL} col.bar1 <- rgb(0, 0, 255, alpha=80, maxColorValue=255) #blue col.bar1tte <- rgb(0, 100, 0, alpha=80, maxColorValue=255) #darkgreen abline(v=0, col=col.bar1) for(i in 1:length(u.y0)){ lines(x=c(u.x0[i], u.x1[i]), y=c(u.y0[i], u.y0[i]), lwd=bar.wid, col=col.bar1) if(useTteDiff){ lines(x=c(u.x0[i], utte.x1[i]), y=c(u.y0[i], u.y0[i])+0.1, lwd=bar.wid, col=col.bar1tte) } } l.x0<-rep(tot.col2+shf, nrow(varMat)) l.y0<-1:nrow(varMat) l.x1<-l.x0-unlist(E.L) col.bar2 <- rgb(255, 0, 0, alpha=80, maxColorValue=255) abline(v=tot.col2+shf, col=col.bar2) for(i in 1:length(l.y0)){ lines(x=c(l.x0[i], l.x1[i]), y=c(l.y0[i], l.y0[i]), lwd=bar.wid, col=col.bar2) } } return(list(dat=varMat, BayesLoss=E.L, U=U, p=p.1)) } } #End 3. -----------------------------------------------------------------------#
/scratch/gouwar.j/cran-all/cranData/BEACH/inst/app/functions/users/DT_frame2.r
############################################ ##Author @ Danni Yu ##Date @ 2016-05-31 ############################################ CleanEnvir <<- function(pattern = "tmp") { objs <- ls(pos = ".GlobalEnv") #print(objs) rm(list = objs[grep("tmp", objs)], pos = ".GlobalEnv") } #print('global') CleanEnvir() inGithub <- FALSE folder <-'BEACH' htmlPath <- '' #---------Configuration File---------------# options(stringsAsFactors=FALSE) local.path0 <- file.path('.','functions') local.path1 <- file.path('.','functions') local.path2 <- tempdir() local.path3 <- file.path(local.path2, 'www') if(!'www'%in%dir(local.path2)) {dir.create(local.path3)} #assign a static url to 'images' addResourcePath('images',local.path3) htmltem <- file.path('.', 'html_template') npath3<-nchar(local.path3)+2 #define the maximum number of widgets max.n1<-c(check=100, radio=100, dropdown=100, slide=100, date=100, dateR=100, num=100, text=100, textbox=100) #global variables defintion #the value can be changed under 'expert' textInput #indicate whether all sources files are output or only R script names allSourceIn1<<-FALSE #create a global variable for dynamic render plot dynamicCode<<-paste0("plot(0~0, col='white',axes=F, xlab='', ylab='',xlim=c(-3,3));", " text(x=0, y=0, labels=\'dynamicData is not defiend yet.\')") dynamicData<<-NULL dynamicData.xvar<<-NULL dynamicData.yvar<<-NULL #to check whether there is any CD cdpool<<-dir(local.path1) cdpool<<-cdpool[grepl('configuration', cdpool) & grepl('.csv', cdpool)] cdpool<<-c(' ', cdpool) cdpool2<<-gsub('_configuration_', '', cdpool) cdpool2<<-gsub('configuration_', '', cdpool2) cdpool2<<-gsub('_configuration', '', cdpool2) cdpool2<<-gsub('configuration', '', cdpool2) #define the split string for multi-level header muliHead.split <<- ";" #define colors RGBColors <- col2rgb(colors()[1:length(colors())]) HEXColors <- rgb(RGBColors[1,]/255, RGBColors[2,]/255, RGBColors[3,]/255) names(HEXColors) <- colors()
/scratch/gouwar.j/cran-all/cranData/BEACH/inst/app/global.r
if (TRUE) { # header #/*soh************************************************************************* # CODE NAME : server.r # CODE TYPE : Program # DATE OF UPDATE: 1-Feb-2019 # DESCRIPTION : Server code for BEACH app # SOFTWARE/VERSION# : R 3.3.0 # INFRASTRUCTURE : # ----------------------------------------------------------------------------- # Ver Author Program History Description # ---- --------------- -------------------------------------------- # 001 Danni Yu Program (2013-2019) # 002 Chenchen Yu Program (2013 2014) # ----------------------------------------------------------------------------- } #Header rm(list=ls()) #install packages if(TRUE){ dep.packages <- c("shiny", "DT", "haven", "xtable", "rtf", "plyr", "sas7bdat", "WriteXLS", #"SASxport", "rJava", "devtools"); na.packages <- dep.packages[!dep.packages %in% installed.packages()] if (length(na.packages)>0) install.packages(na.packages); newWay<<-TRUE #if(!"sas7bdat.parso" %in% installed.packages()) devtools::install_github('BioStatMatt/sas7bdat.parso', force=TRUE) } #required libraries if(TRUE){ library(shiny) library(animation) library(DT) #for render table library(sas7bdat) library(haven) #for loading SAS datasets #load a libray not in cran if("sas7bdat.parso" %in% installed.packages() ){ library(sas7bdat.parso) } library(xtable) library(rtf) library(plyr) library(WriteXLS) library(readxl) #library(SASxport) #a pre-defined function object for ploting functions when click a row in DT. click2plot.o<<-function(ids){ x=0; y=0; plot(y~x,col='white',axes=F,ylab='', xlab='') leg<-paste0('please define a global function\n', 'click2plot(ids=...)\nis not defined yet') legend('topleft', legend=leg, bty='n') } click2plot<-NULL } #required libraries #Key objects and functions if (TRUE){ use_haven<<-T tmpFig <<-"tmpFig.png" showBrush<<-FALSE click_data<<- near_points <<- brush_points <<-NULL currTabL <<- list() input0 <<- list() input0.code <<- new.code <<- NULL ault <<- '480, 480, NA' tfl.h <<- tfl.w <<- tfl.r <<- NA infilelab <<- 'Step 1 Upload data (csv, sas7bdat, xlsx, rdata, xpt)' infilenm <<- c('.csv', '.sas7bdat', '.xlsx', '.rdata', '.Rdata', '.xpt') na_sign <<- c('NA', '', '.', ' ', '-', 'NaN') #standard headers if(TRUE){ sop_head<<-paste( paste(readLines("sopHead.txt"), collapse="\n "), "\n ") } else { data('sopHead') } if(!exists('muliHead.split')){ muliHead.split <<- ";" } #get the current userid for usage track uids<<-NULL uid1<<-Sys.info()['user'] countFnm<<-'counter_m.Rdata' countFnm.strt<<-'counter_startDate.Rdata' if(!file.exists(countFnm) | !file.exists(countFnm.strt) ){ uids<<-uid1 #2016-01-06 add study name and tumor type uids<<-data.frame(userID=uids, studyName='', tumorType="", time=Sys.time()) try(save(uids, file=countFnm)) counter.startDate<<-format(Sys.time(), "%Y-%m-%d") try(save(counter.startDate, file=countFnm.strt)) }else{ try(load(countFnm.strt)) counter.startDate<<-counter.startDate load(file=countFnm) uid2<-data.frame(userID=uid1, studyName='', tumorType="", time=Sys.time()) uids<<-rbind(uids, uid2) try(save(uids, file=countFnm)) } #---------source code for shiny functions---------------# source(file=file.path(local.path1,'shinyFun.r')) source(file=file.path(local.path1,'RTF_functions_DY.r')) #function: read sas, csv or excel files. BeachRead<<-function(file, header=TRUE, nrow=-1, name=NULL, comment.char="", xlsx1=NULL, na.string=c('NA', '', '.', ' ', '-', 'NaN'), SF=FALSE, use_haven=T, ...){ #load a libray not in cran #library(sas7bdat.parso, lib.loc="libs") ot<-NULL if(is.null(name)){name<-file} is.sas<-grepl('.sas7bdat', tolower(name), fixed=TRUE) is.csv<-grepl('.csv', tolower(name), fixed=TRUE) is.xlsx<-grepl('.xls', tolower(name), fixed=TRUE) is.rdat<-grepl('.rda', tolower(name), fixed=TRUE) is.xpt<-grepl('.xpt', tolower(name), fixed=TRUE) if(is.sas){ ot.t <- try(ot<-haven::read_sas(file)) if(class(ot.t)[1]=='try-error' && "sas7bdat.parso" %in% installed.packages() && requireNamespace("sas7bdat.parso", quietly = TRUE)) { try(ot<-sas7bdat.parso::read.sas7bdat.parso(file)) } if(is.null(ot)){ if("sas7bdat.parso" %in% installed.packages() ){ return(paste("Error: fail to import", name)) }else{ return(paste("Error: fail to import", name, ". Please import sas7bdat.parso at GitHub.")) } } ot <- data.frame(ot) for(i in 1:ncol(ot)){ if(is.factor(ot[,i])) ot[,i] <- as.character(ot[,i]) } if(nrow==1) ot <- ot[1,] if(nrow==1 & !header) ot <- data.frame(matrix(colnames(ot), nrow=1)) }else if (is.csv){ tm<-try(ot<-read.csv(file=file, h=header, nrow=nrow, na=na.string, stringsAsFactors=SF, fileEncoding="UTF-8", comment.char=comment.char,...)) if(class(tm)=='try-error') tm<-try(ot<-read.csv(file=file, h=header, nrow=nrow, na=na.string, stringsAsFactors=SF, fileEncoding="Latin1", comment.char=comment.char, ...)) if(class(tm)=='try-error') tm<-try(ot<-readLines(con=file)) }else if (is.xlsx){ if(is.null(xlsx1)) xlsx1 <-1 tm<-try(ot<- readxl::read_excel(path=file, sheet=xlsx1, col_names=header, na=na.string, ...)) if(class(tm)=='try-error') tm<-try(ot<-readLines(con=file)) }else if (is.rdat){ load(file, ot<-new.env()) ot <- as.list(ot) names(ot) <- paste0(name, ".", names(ot)) }else if (is.xpt){ #ot.t <- try( ot <- SASxport::read.xport(file) ) ot.t <- try( ot <- haven::read_xpt(file) ) }else{ ot<-NA } return(ot) } if(!'www'%in%dir(local.path2)) {dir.create(local.path3)} options(stringsAsFactors=FALSE, shiny.usecairo=FALSE, shiny.maxRequestSize=1024*1024^2) options(warn=0, error = NULL) }#Key objects and functions #-----------------------------------# if(TRUE){#other setup# #define the users folder for Analysis Code cnt<-0 user_folder<-c('users/') function_r<-dir(local.path1, ".r") function_r<-c(function_r, dir(local.path1, ".R")) tmConf<<-'configuration_empty_dy1.csv' #clean up open device if(TRUE){ na_file<-dir() na_file<-na_file[substr(na_file,1,2)=='NA'|na_file=="Rplot.pdf"] na_file<-file.path(getwd(),na_file) if(length(na_file)>0){do.call(file.remove, as.list(na_file))} tm_png<-dir(local.path3) tm_png<-tm_png[substr(tm_png,1,3)=='tfl'|substr(tm_png,1,3)=='.nf'| substr(tm_png,nchar(tm_png)-5,nchar(tm_png))=='.rdata'] loatextf<-dir(local.path2) loatextf<-file.path(local.path2, loatextf) if(length(tm_png)>5 | length(loatextf)>5){ if(length(loatextf)>0) try(do.call(file.remove, as.list(loatextf))) tm_png<-file.path(local.path3, tm_png) if(length(tm_png)>0) try(do.call(file.remove, as.list(tm_png))) } } #set up temporary tflfile names if(TRUE){ randseed<-round(runif(1,1,10^7)) loatext<<-tempfile(pattern=paste0("loa",randseed), tmpdir=local.path2, fileext=".txt") tflfile<<-tempfile(pattern=paste0("tfl",randseed), tmpdir=local.path2, fileext="_") }else{tflfile<-NULL} #save history of Rscript in expert text1<-'#For text output' text2<-'#For figure output' }#other setup# #@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@# BeachServer <- function(input,output, session){ #close your app when the browser is closed session$onSessionEnded(function() { stopApp(NULL) }) rawrow1<<-list() #for changing colnames with row 1 in a table data. indataset<<-list() indataR <<-list() #-------Web Counter---------# output$counter<-renderPrint({ load(file=countFnm) if(is.null(uids)) return(NULL) uid.colnm<-c("userID", "studyName", "tumorType") uid<<-aggregate(Freq~., data=data.frame(uids[,uid.colnm], Freq=1), FUN=sum) tm<-aggregate(Freq~userID, data=uid, FUN=sum) colnames(tm)[2]<-"Freq.tot" uid<<-merge(uid, tm, by="userID") uid<<-uid[order(uid$Freq.tot, uid$Freq,decreasing=TRUE),] #print(paste("Start Date:", counter.startDate)) #print(uid[, c(uid.colnm, "Freq")]) }) #------change the width of widget panel and the color------# output$beachColor <- renderUI({ code0 <- selectInput_color(id='wpColor', label='Background color', choices=colors(), selected='azure3' ) return(shiny::HTML(code0)) }) output$wp.width <- renderUI({ #width of the widgets panel widget.panel.width<-paste0(input$wpW, "%") wp.out <- paste0("<div class=\"panel panel-default draggable\" ", "id=\"controls1\" ", "style=\"top:50%;left:auto;right:0%;bottom:auto;width:", widget.panel.width, ";height:auto", #widget.panel.height, ";position:absolute;cursor:move; ", "background-color: ", HEXColors[input$wpColor], ";z-index: 199;\">", # "<div id=\"set.ncol.widg\" class=\"shiny-html-output\"></div>", "<div id=\"widgetSide\" class=\"shiny-html-output\"></div>", "</div> <script>$(\".draggable\").draggable();</script> ") return(shiny::HTML(wp.out)) }) #-------Webpage Title in the data input panel---------# output$setTitle<-renderUI( try( { VdicTitle<<-reactive({ #note: only one or two rows should be defined. if (is.null(input$config) & input$config.sel==" "){ Vdic0<<-read.csv(file.path(tmConf),header=TRUE,check.names=FALSE, encoding='UTF-8') }else{ if(!is.null(input$config)){ isolate({Vdic0<<-read.csv((input$config)$datapath, header=TRUE,check.names=FALSE, encoding='UTF-8') }) } if(input$config.sel!=" "){ isolate({ Vdic0<<-read.csv(file.path(local.path1, cdpool[cdpool2==input$config.sel]), header=TRUE,check.names=FALSE, encoding='UTF-8') }) } } ret<-Vdic0 nCol<-ncol(ret) titleValue<-c("title_image","title_text") titleRowsID<-which((!is.na(ret$Type) & ret$Type%in%titleValue) | ret$Num==1) titleRows<-ret[titleRowsID,] return(titleRows) } ) if(nrow(r123<-VdicTitle())>0){ r1<-r123[r123$Type=='title_image',] r2<-r123[r123$Type=='title_text',] r1c<-r2c<-'' if(nrow(r1)>0&&grepl(".png", r1$Title, fixed=TRUE)){ r1c<-as.character(img(src=r1$Title[1], height="10%",width="100%")) } if(nrow(r2)>0){ r2c<-paste0('<h4 style="color:black; background-color:white; width:100%; height:10%;"> ', #r2$Title[1], Sys.getlocale(), "</h4>") r2$Title[1], "</h4>") } retTitle<-shiny::HTML(paste0(r1c,r2c)) #run the getData source code s1<-r123[ as.numeric(r123$Num)==1,'Source'] if(length(s1)>0&&grepl('.r', tolower(s1), fixed=TRUE)){ if(!grepl('users/', s1, fixed=TRUE)) s1<-file.path('users', s1) s1<-file.path(local.path0, s1) if(file.exists(s1)){ source(s1) } } #run the uesr-free functions eval(parse(text=r123[ as.numeric(r123$Num)==1,"PlotCode"])) }else{ retTitle<-shiny::HTML('<h4 style="color:black;"> BEACH-PARTY </h4>') } return(retTitle) }) ) #-------Update webpage accroding to user-defined CD---------# output$setconfig<-renderUI({ Vdic<<-reactive({ if (is.null(input$config) & input$config.sel==" "){ Vdic0<<-read.csv(file.path(tmConf),header=TRUE,check.names=FALSE, encoding='UTF-8') }else{ if(!is.null(input$config)){ isolate({Vdic0<<-read.csv((input$config)$datapath, header=TRUE,check.names=FALSE, encoding='UTF-8') }) } if(input$config.sel!=" "){ isolate({ Vdic0<<-read.csv(file.path(local.path1, cdpool[cdpool2==input$config.sel]), header=TRUE,check.names=FALSE, encoding='UTF-8') }) } } #Vdic0$Add<-unlist(lapply(Vdic0$Add,function(x){eval(parse(text=x))})) ret<-Vdic0[ as.numeric(Vdic0$Num)>0,] if(!'res'%in%colnames(ret)){ ret$res <- NA } if(!'width'%in%colnames(ret)){ ret$width <- NA } if(!'height'%in%colnames(ret)){ ret$height <- NA } #insert user folders if it is not exist in the source function list for(i in 1:nrow(ret)){ if(!is.na(ret$Source[i])&ret$Source[i]!=''&!ret$Source[i]%in%function_r){ xSel<-sapply(user_folder, function(x){ substr(ret$Source[i], 1, nchar(x))==x }) if(sum(xSel)==0){ ret$Source[i]<-paste0(user_folder[1],ret$Source[i]) } } } runSource<-unique(ret$Source[!is.na(ret$select.label)&!is.na(ret$Source)]) sapply(runSource,function(x){ source(file=file.path(local.path0,x))}) ret$Add<-unlist(lapply(ret$Add,function(x){eval(parse(text=x))})) ret<-ret[ret$Add,] return(ret) } ) UIdic<<-reactive(Vdic()[Vdic()$Add & !is.na(Vdic()$Request.Name),] ) UInames<-names(UIdic())[grepl('uiInput',names(UIdic()))] UInames<<-UInames[!sapply(UInames,function(x){all(is.na(UIdic()[,x]))})] temp<-strsplit(names(UIdic())[grepl('.label',names(UIdic()))],'.label',fixed=TRUE) temp1<-sapply(temp,function(x){ if(x[1] %in% c('check','radio','dropdown','slide', 'date', 'dateR', 'num', 'text', 'textbox')){ return(paste0(x,collapse='')) }else{ return(NULL) } }) #----params includes all the relative widgets----# params<<-sort(unlist(temp1)) max.n<<-c(check=length(grep('check',params)),radio=length(grep('radio',params)), dropdown=length(grep('dropdown',params)),slide=length(grep('slide',params)), date=length(grep('date',params)),dateR=length(grep('dateR',params)), num=length(grep('num',params)),text=length(grep('text',params)), textbox=length(grep('textbox',params)) ) max.n2<<-max.n#[max.n!=0] params.lab<<-paste0(params, '.lab') #--order params by its indes--# strsplit1 <- function(x, split){ out1 <- NULL for(i in 1:length(x)){ for(j in 1:length(split)){ if(grepl(split[j], x[i], fixed=T)){ t1 <- strsplit(x[i], split=split[j], fixed=TRUE)[[1]] if(length(t1)==1){ out1 <- rbind(out1, data.frame(m1=split[j], m2=0)) break }else{ if(!is.na(as.numeric(t1[2]))){ out1 <- rbind(out1, data.frame(m1=split[j], m2=as.numeric(t1[2]))) break } } } } } return(out1) } params.id <<- strsplit1(params, names(max.n)) params.ord <<- order(params.id$m1, params.id$m2) #params.ord <- order(params) #re-set the other tabs tmp<-readLines(file.path(local.path0,Vdic()$Source[1])) r.lib<-tmp[grepl('library(',tmp,fixed=TRUE)|grepl('require(',tmp,fixed=TRUE)] r.lib.temp<-gsub(' ', '', r.lib, fixed=TRUE) r.lib<-r.lib[!grepl('#library', r.lib.temp, fixed=TRUE)&!grepl('#require',r.lib.temp, fixed=TRUE)] r.lib<-sort(unique(r.lib)) r.lib.alert<<-paste0( #' #required packages: \n', paste0(r.lib, collapse='\n') ) #Get the libraries needed for running the analysis if(!is.null(tflfile)){ randseed<-round(runif(1,1,10^7)) loatext<<-tempfile(pattern=paste0("loa",randseed), tmpdir=local.path2, fileext=".txt") tflfile<<-tempfile(pattern=paste0("tfl",randseed), tmpdir='', fileext="_") } write.table(t(c("Request.Name","Type","Titles", "height", "width", "res", "Footnote", "Abbreviations.Footnote","Statistical.Analysis", "Test.Statistic.Footnote", as.vector(rbind(params.lab, params)))), file=loatext,append=FALSE,col.names=FALSE,row.names=FALSE) fileInput(inputId='config', label='Step 2 Input configuration file', accept=c('.csv', 'text/csv', 'text/comma-separated-values,text/plain'), multiple=FALSE) }) #----------Obtain number of analysis request for TFL------------# loaTF<<-reactive(eval(parse( text=paste0("c(",paste0("input$result_",1:400,collapse=','),")")))) AnalyN<<-reactive({ if(is.null(input$analysis)){ return(1) }else{ return(which(Vdic()$Request.Name==input$analysis)) } }) # Capture the corresponding configuration for the selected analysis AnalyC<<-reactive(which(Vdic()$Request.Name==input$analysis)[1]) #----------Generate Tabs------------# output$tabs<-renderUI({ tabset<-Vdic()[!is.na(Vdic()$Tab.label),c('Tab.value','Tab.label')] tabcode<-tabs(tab.id='Tabs',tab.label=tabset[,1],tab.value=tabset[,2]) return(shiny::HTML(tabcode)) }) # Generate the Tabs #----------Update webpage according to user-defined mock data------------# #indataset is a list object including all the uploaded dataset #indataset.i is a data.frame object, the 1st dataset in indataset. #indataR is a list obeject including all the elements in the uploaded R files output$file<-renderUI({ if(is.null(input$infile)){ return(conditionalPanel('true', radioButtons('csv_enc', 'Encoding format for CSV file', choices=c('UTF-8', 'unkown'), inline=TRUE), radioButtons('checknames', 'Change " " or "-" in column names into "."', choices=c(FALSE, TRUE), inline=TRUE), fileInput('infile', label=infilelab, accept=infilenm, multiple=TRUE))) }else{ #update the count file try(uids$studyName[nrow(uids)]<-ifelse(is.null(input$study), '', input$study)) try(uids$tumorType[nrow(uids)]<-ifelse(is.null(input$tumor), '', input$tumor)) try(save(uids, file=countFnm)) isolate({ input_infile <<- input$infile ###import the files under a pre-specified location if(nrow(input_infile)==1 & grepl('.csv', input_infile) & grepl('File_Names', input_infile) ){ input_infile_1 <- BeachRead(input_infile[1, 'datapath'], name=input_infile[1, 'name']) #check file name if(any(!colnames(input_infile_1)%in%c('datapath', 'name'))){ print("Files in 'File_Names...csv' are not loaded. The colum names must be 'datapath' and 'name'.") } else { input_infile_1$datapath <- file.path(input_infile_1$datapath, input_infile_1$name) input_infile <<- input_infile_1[,c('name', 'datapath')] } } if(nrow(input_infile)>1 | length(indataset)>0){ indataset0<-list() indataset0.wh <- NULL for(i in 1:nrow(input_infile)){ tmpload <- BeachRead((input_infile[i, 'datapath']), header=TRUE, name=input_infile[i,'name'], encoding=isolate(input$csv_enc), comment.char=isolate(input$comm_chr), check.names=as.logical(input$checknames)) if(is.list(tmpload) & grepl('.rda', tolower(input_infile[i,'name']))){ indataR <<- c(indataR, tmpload) }else{ indataset0.wh <- c(indataset0.wh, i) indataset0[[i]]<- tmpload } } indataset0 <- indataset0[!sapply(indataset0, is.null)] names(indataset0)<-input_infile[indataset0.wh, 'name'] indataset0<<-indataset0 wh1<<-names(indataset)[names(indataset)%in%names(indataset0)] if(length(wh1)>0){ indataset[wh1]<<-indataset0[wh1] indataset0<-indataset0[!names(indataset0)%in%wh1] } if(length(indataset0)>0){ indataset<<-c(indataset, indataset0) } }else{ indataset0<-list() tmpload <- BeachRead((input_infile)$datapath, header=TRUE, name=input_infile[1,'name'], encoding=isolate(input$csv_enc), comment.char=isolate(input$comm_chr), check.names=as.logical(input$checknames)) if( is.list(tmpload) & grepl('.rda', tolower(input_infile[1,'name'])) ){ indataR <<- c(indataR, tmpload) indataset.i <<- indataR[[1]] } else { indataset.i <<- tmpload indataset0[[1]]<-indataset.i names(indataset0)<-input_infile[,'name'] indataset<<-indataset0 } } }) # End of isolate if(length(indataR)>0){ indataR <<- indataR[unique(names(indataR))] indataset <<- c(indataset, indataR) indataset <<- indataset[unique(names(indataset))] } rawrow1 <<- lapply(indataset, function(x){x[1,]}) studyname1 <-na.omit(unique(unlist(lapply(indataset,function(x){ unique(x$STUDYID) })))) if(!is.null(studyname1)) studyname1 <-paste(unique(studyname1), collapse=", ") tumortype1 <-unlist(lapply(indataset,function(x){ unique(x$TUMOR_TYPE) })) if(is.null(studyname1)) studyname1 <- "" if(is.null(tumortype1)) tumortype1 <- "" if(!is.null(input$study)) studyname1 <- input$study if(!is.null(input$tumor)) tumortype1 <- input$tumor if(length(indataset)<2){ stnm<-inlinetext(text.id='study',text.label='Study Name ', text.value=studyname1) datanote<-paste0(input$infile$name,' has ', nrow(indataset.i), ' rows, ',ncol(indataset.i),' columns.') tmtp<-inlinetext(text.id='tumor',text.label='Tumor Type ', text.value=tumortype1) studyname <<- input$study tumortype <<- input$tumor datanote<-paste0('<h6>', datanote, ' </h6>') if(input$data_reload | (is.null(input$config) & input$config.sel==" ")){ return( conditionalPanel( condition='true', fileInput('infile', label=infilelab, accept=infilenm, multiple=TRUE), shiny::HTML(c(stnm, "<br>", tmtp, datanote)) ) ) }else{ return(conditionalPanel(condition='true', shiny::HTML(c(stnm, "<br>", tmtp, datanote)) ) ) } }else{ if(!is.null(tumortype1)) tumortype1<-paste(tumortype1, collapse=", ") stnm<-inlinetext(text.id='study',text.label='Study Name ', text.value=studyname1) datanote<-paste0(names(indataset),' has ', sapply(indataset, nrow), ' rows, ', sapply(indataset, ncol),' columns.') tmtp<-inlinetext(text.id='tumor',text.label='Tumor Type ', text.value=tumortype1) studyname <<- input$study tumortype <<- input$tumor datanote<-paste0('<h6>', datanote, ' </h6>') if(input$data_reload | (is.null(input$config) & input$config.sel==" ")){ return( conditionalPanel('true', radioButtons('csv_enc', 'Encoding format for CSV file', choices=c('UTF-8', 'unkown'), inline=TRUE), radioButtons('checknames', 'Change "_" in column names into "."', choices=c(FALSE, TRUE), inline=TRUE), fileInput('infile', label=infilelab, accept=infilenm, multiple=TRUE), shiny::HTML(c(stnm, "<br>", tmtp, datanote)) )) }else{ return(conditionalPanel(condition='true', shiny::HTML(c(stnm, "<br>", tmtp, datanote)) ) ) } } } }) # Widget to upload dataset #----------Get data.frame objects (subset of CD) only for widgets----------# output$getWidgets<-renderUI({ #a row is a Request.name check.param<<-reactive({widgets.param(uidic=UIdic(),wid='check',max.n=max.n2)}) radio.param<<-reactive({widgets.param(uidic=UIdic(),wid='radio',max.n=max.n2)}) dropdown.param<<-reactive({widgets.param(uidic=UIdic(),wid='dropdown',max.n=max.n2)}) slide.param<<-reactive({widgets.param(uidic=UIdic(),wid='slide',max.n=max.n2)}) date.param<<-reactive({widgets.param(uidic=UIdic(),wid='date',max.n=max.n2)}) dateR.param<<-reactive({widgets.param(uidic=UIdic(),wid='dateR',max.n=max.n2)}) num.param<<-reactive({widgets.param(uidic=UIdic(), wid='num', max.n=max.n2)}) text.param<<-reactive({widgets.param(uidic=UIdic(),wid='text',max.n=max.n2)}) textbox.param<<-reactive({widgets.param(uidic=UIdic(),wid='textbox',max.n=max.n2)}) return(NULL) }) widgetOrd<<-reactive({ widgets.order(analysis=input$analysis, UIdic1=UIdic(), UInames=UInames, ncol.widg=as.numeric(input$ncol.widg.rd)) }) output$widgets<-renderUI({ #HTML code of all the widgets eval(parse(text=unique(widgetOrd()$code))) }) output$getData<-renderUI({#Declare global variables# # if(!is.null(input$infile)|!is.null(input$infileR)){ tm.Vdic<-Vdic() if(!is.na(tm.Vdic$select.label)) source(file.path(local.path0, tm.Vdic$Source[1])) # } return(NULL) }) # Data manipulation for the uploaded dataset output$getTFL<-renderUI({ #only table data is output to local.path3 (a temporary folder) if(F){ tflname<-sapply(AnalyN(),function(x){ ifelse(all(is.na(widgetOrd()$names)), #Condition paste0(tflfile,Vdic()$Num[x]), #if TRUE paste0(tflfile,Vdic()$Num[x],'x', #if FALSE paste0(#Paste all UIs together sapply(widgetOrd()$names,function(y){ y0<-eval(parse(text=paste0('input$',y))) if(!is.null(y0)){y0[is.na(y0)]<-''} y0<-paste0(y0[length(y0):1],collapse='_')#Paste all Params for each UI substring(y0, max(nchar(y0)-30,1)) }),collapse='')) ) }) tflname<-gsub(" ",'',tflname) tab.name<-file.path(local.path3,paste0(input$submitcode,gsub("[[:punct:]]","",tflname),'.rdata')) } if('Table' %in% Vdic()$Type[(AnalyN())] ){ AnalyNt<-reactive(AnalyN()[Vdic()$Type[AnalyN()]=='Table']) tmp<-eval(parse(text=Vdic()$tmp[AnalyNt()[1]])) sapply(AnalyNt(),function(x){ if (eval(parse(text=Vdic()$Condition[AnalyNt()[1]]))){ tmptab<-NULL }else{ tmptab<-eval(parse(text=Vdic()$PlotCode[x])) } # save(tmptab,file=tab.name[Vdic()$Layout[x]]) }) } return(NULL) }) # Generate png files if the output is plot output$status<-renderUI({ if(is.null(input$infile)&is.null(input$infileR)){ tmpcode<-'<span class=\"label label-important\" style=\"background-color:red; color:black;\">Data not loaded</span>' }else{ tmpcode<-'<span class=\"label label-success\" style=\"color:black;\">Data loaded</span>' } return(shiny::HTML(tmpcode)) }) # Status of data manipulation process output$select<-renderUI({ selectN<-which(Vdic()$Tab.value==input$Tabs) if (all(is.na(Vdic()$select.label[selectN])))return(NULL) label<-unique(Vdic()$select.label[selectN]) label<-label[!is.na(label)] selection<-unique(Vdic()$Request.Name[selectN]) return(selectInput(inputId="analysis",label=strong(label),choices=selection, width="80%")) }) # Generate the downdrop list #-----Generate code for output$widgets widgetCode<-widgets.code(UInames=UInames,max.n=max.n1) eval(parse(text=widgetCode)) #-------Output results to the current screen------------# output$save_data_ext<-renderUI({ choiceN<-AnalyN()[Vdic()$Type[AnalyN()]=='Table'] choiceP<-AnalyN()[Vdic()$Type[AnalyN()]=='Figure'] if(length(choiceN)==0 & length(choiceP)==0)return(NULL) if(length(choiceN)==0 & length(choiceP)>0){ return( conditionalPanel(condition='true', div( downloadButton('getEPS','download EPS plot'), downloadButton('getPDF','download PDF plot') ) )) } if(length(choiceN)>0 & length(choiceP)==0){ choice<-sapply(choiceN, function(x){ ifelse(substr(Vdic()$Title[x],1,5)=='paste', eval(parse(text=Vdic()$Title[x])), Vdic()$Title[x]) }) return( conditionalPanel(condition='true', checkboxGroupInput('multdat', 'Please Choose a table to save', choices=choice, selected=NULL, inline =TRUE), radioButtons('multdat_ext', 'Format', c('csv','rdata','xpt','xls','SAS code'='sas'), selected = NULL, inline = TRUE), downloadButton("save_data","Save Data") ) ) } if(length(choiceN)>0 & length(choiceP)>0){ choice<-sapply(choiceN, function(x){ ifelse(substr(Vdic()$Title[x],1,5)=='paste', eval(parse(text=Vdic()$Title[x])), Vdic()$Title[x]) }) return( conditionalPanel(condition='true', div( downloadButton('getEPS','download EPS plot'), downloadButton('getPDF','download PDF plot') ), checkboxGroupInput('multdat', 'Please Choose a table to save', choices=choice, selected=NULL, inline =TRUE), radioButtons('multdat_ext', 'Format', c('csv','rdata','xpt','xls','SAS code'='sas'), selected = NULL, inline = TRUE), downloadButton("save_data","Save Data") ) ) } }) output$TFL<-renderUI({ plotcode <- NULL currTabL <<- list() currTabL_i <- 1 #redefine fig size/resolution according to the text bar on top. if(is.null(input$hwr)) hwr.c <- '' else hwr.c <- as.character(input$hwr) tfl.h<<-ifelse(is.na(as.numeric(strsplit(hwr.c,split=';')[[1]])[1]), 480, as.numeric(strsplit(hwr.c, split=';')[[1]])[1]) tfl.w<<-ifelse(is.na(as.numeric(strsplit(hwr.c,split=';')[[1]])[2]), 480, as.numeric(strsplit(hwr.c, split=';')[[1]])[2]) tfl.r<<-ifelse(is.na(as.numeric(strsplit(hwr.c,split=';')[[1]])[3]), 72, as.numeric(strsplit(hwr.c, split=';')[[1]])[3]) if (all(!Vdic()$Type[AnalyN()] %in% c('Figure','Table'))|| all(eval(parse(text=Vdic()$Condition[AnalyN()])))){ return(NULL) } for (i in AnalyN()){ input0.code <- Vdic()$PlotCode[i] pdf.label <<- paste("H1", Vdic()$Tab.label[i], "H2", Vdic()$Request.Name[i]) myInput <<- Vdic()[i,UInames] mylab <<- Vdic()[i,gsub('Input', 'lab', UInames)] names(myInput) <<- mylab myInput <<- myInput[!is.na(myInput)] for(m0 in 1:length(myInput)){ x <- myInput[m0] if(grepl('date', x)) x <-paste0("paste(",x, ")") input0[[m0]] <- eval(parse(text=x)) } if(length(myInput) == length(input0)) names(input0) <- gsub("input$", "", myInput, fixed=TRUE) input0 <<- input0 #date and dateR widgets have to be a character before running eval. for(m1 in 1:length(input0)){ if(length(input0)>0 && grepl('date', names(input0)[m1], fixed=TRUE)){ date.value <- paste("c(", paste( paste0("\"", input0[[m1]], "\""), collapse=', '), ")") input0.code<- gsub(paste0('input$',names(input0)[m1]), date.value, input0.code, fixed=TRUE) } } new.code <<- input0.code input0.code <<- input0.code if(!is.na(Vdic()$Title[i])){ title<-ifelse(substr(Vdic()$Title[i],1,5)=='paste', eval(parse(text=Vdic()$Title[i])),Vdic()$Title[i]) titlecode<-paste0('<h3><textarea name=\"titlebox\" rows=\"1\" style=\"width:80%\">', title,'</textarea></h3>') }else{titlecode<-NULL} try( addResourcePath('images',local.path3) ) if(Vdic()$Type[i]=='Figure'){ if(length(input0.code)>0 && grepl("dynamicData", input0.code, fixed=TRUE)){ dynamicCode<<-input0.code tmpcode <- paste0(plotOutput('dynamicPlot', click='dynamicPlot_click', brush="dynamicPlot_brush"), #click data "<h4>Points near click</h4>", "\n", downloadButton('click_info_dl', 'save clicked data'), uiOutput('click_info_DT'), #brush data "<h4>Brushed points</h4>", "\n", downloadButton('brush_info_dl', 'save brushed data'), uiOutput('brush_info_DT') ) }else{ tmpFig1 <- NULL for(k in 1:length(i)){ tmpFig1 <- c(tmpFig1, tempfile(tmpdir=local.path3, fileext='.png')) png(tmpFig1[k], height=tfl.h, width=tfl.w, res=tfl.r ) plottry<-try(eval(parse(text=input0.code[k]))) if(class(plottry)[1]=='try-error') { plot(0,axes=F, col='white',ylab='',xlab='') legend('top', 'Plotting\nError', cex=5, bty='n', text.col='red') } dev.off() } tmpFig2 <- gsub(local.path3, "", tmpFig1, fixed=TRUE) tmpFig2 <- gsub('/', "", tmpFig2, fixed=TRUE) tmpcode<-paste0("<img src=\"images/", tmpFig2, "\" alt=\"Calculating...\" style=\"width:", 100*input$figSize, "% ; height: ", 100*input$figSize, "%\"/> \n") } }else if(Vdic()$Type[i]=='Table'){ if(class(try(tmptab<<-eval(parse(text=input0.code))))[1]=='try-error'){ tmptab<-'' } #save(tmptab, file=tab.name) outTable<-tmptab #update the current table list in the parent environment currTabL[[currTabL_i]] <<- outTable currTabL_i <- currTabL_i+1 if(class(try(tmpcode<-xtable(outTable)))[1]=='try-error'){ tmpcode<-outTable } if(input$useDT){#if TRUE using render table tmpcode<-paste0( "<div id=\"outTbl_DT\" style=\"width:",input$figSize*100, "%;", "height:auto\" class=\"shiny-html-output\"></div>" ) }else{ tmpcode<-capture.output(print(tmpcode,type="html", include.rownames=FALSE,include.colnames=TRUE)) if(is.na(tmpcode[2])){ tmpcode[2]<-''} tmpcode <- toMultH(tbc=tmpcode, split1=muliHead.split) tmpcode[3]<-paste0("<TABLE style=\'width:", input$figSize*100, "%;\' >") } } plotcode<-c(plotcode,titlecode,tmpcode) } return(shiny::HTML(plotcode)) }) # Generate TFL with title output$footnote<-renderUI({ footnote<-Vdic()$FootCode[AnalyC()] footnote<-gsub("\\\\n","\n",footnote) if(!is.na(footnote)&&gsub("", " ", footnote)!=''&&substr(footnote,1,5)=='paste') footnote<-eval(parse(text=footnote)) #cat(footnote) fo1<-paste(footnote, collapse=' ') shiny::HTML( paste0("<textarea name=\"footnotebox\" rows=\"4\" style=\"width:80%\"\">", fo1, "</textarea>")) }) # Generate footnote #------Output for user input code------# output$userExp<-renderUI({ isolate(input$expert) if(is.null(input$expert)||!(input$expert)){ return(NULL) } else { return( conditionalPanel( condition="true", div(shiny::HTML(paste0("<textarea name=\"Rscript\" rows=\"2\"", " style=\"width:100%\"", " placeholder=\"#For text output \"></textarea>")), actionButton('submit','execute')), div(shiny::HTML(paste0("<textarea name=\"RscriptF\" rows=\"2\"", " style=\"width:100%\"", " placeholder=\"#For plot output \"></textarea>")), actionButton('submit2','execute')), div(downloadButton('save_Rhist', 'save expert code history')) )) } }) output$Input_outExpert<-renderPrint({ if(TRUE){ myInput <<- Vdic()[AnalyN(),UInames] mylab <<- Vdic()[AnalyN(),gsub('Input', 'lab', UInames)] names(myInput) <<- mylab myInput <<- myInput[!is.na(myInput)] for(m0 in 1:length(myInput)){ x <- myInput[m0] if(grepl('date', x)) x <-paste0("paste(",x, ")") input0[[m0]] <- eval(parse(text=x)) } names(input0) <- gsub("input$", "", myInput, fixed=TRUE) input0 <<- input0 } input0 }) output$RoutExpert<-renderPrint({ if(is.null(input$submit)||input$submit==0){ return('For text output from Rscript') } isolate({ text1<<-c(text1, input$Rscript) eval(parse(text=input$Rscript), env=sys.frame()) }) }) output$RoutExpertF<-renderPlot({ if(is.null(input$submit2)||input$submit2==0){ return(NULL) } isolate({ text2<<-c(text2, input$RscriptF) eval(parse(text=input$RscriptF), env=sys.frame()) }) }) output$save_Rhist<-downloadHandler( filename=function(){paste0(input$study,"_",input$tumor,"_Rhist.r")}, content=function(file){ tmpout<-paste(text1,"\n#~~~~~~~~~~~~~~#\n", text2) colnames(tmpout)<-'' write(tmpout, file=file, row.names=FALSE, col.names=FALSE) } ) # Download Source code #-----Text bar for figure size/resolution output -----# output$hwrCtrl <- renderUI({ if(TRUE){ h1 <- eval(parse(text=Vdic()$height[(AnalyN())])) w1 <- eval(parse(text=Vdic()$width[(AnalyN())])) r1 <- eval(parse(text=Vdic()$res[(AnalyN())])) h2 <- ifelse(is.null(h1), 480, as.numeric(eval(parse(text=h1)))) w2 <- ifelse(is.null(w1), 480, paste(as.numeric(eval(parse(text=w1))), collapse=', ') ) r2 <- ifelse(is.null(r1), 72, as.numeric(eval(parse(text=r1))) ) hwr.default <<- paste( ifelse(is.na(h2)||h2==0, 480, h2), ifelse(is.na(w2)||w2==0, 480, w2), ifelse(is.na(r2)||r2==0, 72, r2), sep='; ') } textInput('hwr', 'Height(px for figure; #MaxRows/page for table: 1~35 or 1~50); width(px); resolution(px/inch).', value=hwr.default, width="50%" ) }) output$AnalysisTab<-renderUI({ selN<-!is.na(Vdic()$Tab.label) & is.na(Vdic()$Request.Name) unAnalyTab<-unique(Vdic()$Tab.value[selN]) cpCon<-paste0(paste0("input.Tabs!=","\'",unAnalyTab,"\'"), collapse='&&') selN.addbar<-!is.na(Vdic()$Tab.label) & grepl("dynamicData", Vdic()$PlotCode, fixed=TRUE) cpCon.addbar<-paste0(paste0("input.analysis!=","\'", unique(Vdic()$Request.Name[selN.addbar]),"\'"), collapse='&&') # print(cpCon.addbar) conditionalPanel(condition=cpCon, width='100%', div(class='row'), div(class='span6', uiOutput('select')), div(class='span2', actionButton(inputId="add_analysis",label="Add Analysis")), sliderInput('figSize', label="Relative Size", min=0.1, max=1, value=0.3, step=0.1, animate=FALSE), uiOutput('hwrCtrl'), div(class='span12', uiOutput("TFL"), uiOutput("footnote"), br(), uiOutput("save_data_ext"), conditionalPanel(condition="input.expert==true", div(verbatimTextOutput("Input_outExpert"), br(), verbatimTextOutput("RoutExpert"), br(), plotOutput("RoutExpertF") )), conditionalPanel(condition="input.usage==true", verbatimTextOutput("counter")) )) }) output$widgetSide<-renderUI({ selN<-!is.na(Vdic()$Tab.label) & is.na(Vdic()$Request.Name) unAnalyTab<-unique(Vdic()$Tab.value[selN]) cpCon<-paste0(paste0("input.Tabs!=","\'",unAnalyTab,"\'"), collapse='&&') conditionalPanel(condition=cpCon, uiOutput("widgets")) }) output$SpecialTab<-renderUI({ selN<-!is.na(Vdic()$Tab.label) & is.na(Vdic()$Request.Name) unAnalyTab<-unique(Vdic()$Tab.value[selN]) if (!is.null(input$Tabs) && (input$Tabs%in%unAnalyTab)){ eval(parse(text=readLines( file.path(local.path0,Vdic()$Source[which(Vdic()$Tab.value==input$Tabs)]) ))) } }) #-------List of Analysis, R code ------------# output$loa<-renderUI({ loaAdd<-reactive({ t.names <<- c("Request.Name","Type","Titles", "height","width", "res", "Footnote", "Abbreviations.Footnote","Statistical.Analysis", "Test.Statistic.Footnote", as.vector(rbind(params.lab,params)) ) if (is.null(input$add_analysis) || input$add_analysis==0){ tmprow <- data.frame(matrix(NA, nrow=0, ncol=length(t.names))) colnames(tmprow) <- t.names return(tmprow) } isolate({ tmp0<-sapply(params[1:length(params)],function(x){ if (x %in% widgetOrd()$names){ if(grepl('date', x)){ tmp<-eval(parse(text=paste0('paste(input$',x, ")"))) } else { tmp<-eval(parse(text=paste0('input$',x))) } tmp<-ifelse(is.null(tmp),'',tmp) tmp<-ifelse(length(eval(parse(text=paste0('input$',x))))>1, paste0(eval(parse(text=paste0('input$',x))),collapse=','), tmp) }else{tmp<-NA} return(tmp) }) tmp1<-rep(NA,length(params)) names(tmp1) <- params tmp1.lab <- widgetOrd()$labs names(tmp1.lab) <- widgetOrd()$names tmp1.nm <- params[params %in% names(tmp1.lab)] tmp1[tmp1.nm]<-tmp1.lab[tmp1.nm] footnote<-input$footnotebox if(is.na(footnote)){ footnote<-'' } footnote<-gsub("\\\\n","\n",footnote) if(!is.na(footnote)&&gsub("", " ", footnote)!=''&&substr(footnote,1,5)=='paste'){ footnote<-eval(parse(text=footnote)) } footnote2<-paste0(substr(footnote,1,10),'...') #title<-Vdic()$Title[AnalyC()] title<-input$titlebox if(!is.na(title) && grepl(title, 'paste', fixed=TRUE)){ title<-eval(parse(text=title)) } my.hwr <<- strsplit(input$hwr,split=';')[[1]] w1<<-eval(parse(text=Vdic()$width[AnalyC()])) tmprow<-data.frame(t(c(input$analysis,Vdic()$Type[AnalyC()],title, height=my.hwr[1], width=my.hwr[2], res=my.hwr[3], footnote, footnote2,Vdic()$StatModel[AnalyC()], Vdic()$StatNote[AnalyC()], as.vector(rbind(tmp1,tmp0)) ))) colnames(tmprow)<-t.names return(tmprow) }) }) # Add analysis by selection loaLoad<-reactive({ if (input$load_analysis==0||is.null(input$upfile)) return(NULL) isolate({ tmp<-read.csv((input$upfile)$datapath,header=TRUE, encoding='UTF-8', na = na_sign) if(!'height'%in%colnames(tmp)){ tmp$height <- NA } if(!'width'%in%colnames(tmp)){ tmp$width <- NA } if(!'res'%in%colnames(tmp)){ tmp$res <- NA } return(tmp) }) }) # Add analysis by upload myTTT <<- plyr::rbind.fill(loaAdd(),loaLoad()) if(!is.null(nrow(myTTT))) myTTT <<- myTTT[, colnames(loaAdd())] write.table(myTTT, loatext,append=TRUE,col.names=FALSE,row.names=FALSE) if((is.null(input$add_analysis)||is.null(input$load_analysis)) || input$add_analysis+input$load_analysis==0){ return(NULL) }else{ ret<-read.table(loatext,header=TRUE,check.names=FALSE) ret<-unique(ret) write.table(ret,loatext,append=FALSE,row.names=FALSE,col.names=TRUE) } LOA<<-reactive({ if((is.null(input$add_analysis)||is.null(input$load_analysis)) || (input$add_analysis+input$load_analysis)==0){ return(NULL) }else{ return(ret) } }) return(NULL) }) # Generate LOA output$LOA<-renderUI({ if((is.null(input$add_analysis) || is.null(input$load_analysis)) || input$add_analysis+input$load_analysis==0 ){ return(NULL) }else{ tf<-reactive({ tf<-isolate({loaTF()}) #is a TRUE/FALSE vector checking the availability of input$result_i #see checkboxTableInput in shinyFun.r addrow<-nrow(LOA())-length(tf) if(addrow>0){ tfb<-c(tf,rep(TRUE,addrow)) }else{ tfb<-tf } return(tfb) }) #TRUE/FALSE of LOA isolate({ sel_Table<-tf() tmploaTable<-LOA()[,c('Titles','Abbreviations.Footnote')] tmploaTable<-data.frame(ID=1:nrow(tmploaTable), tmploaTable) input$delete_loa }) if(nrow(tmploaTable)==0){return(NULL)} if(is.null(input$delete_loa)||!(input$delete_loa)){ shiny::HTML(checkboxTableInput( tmploaTable, table.id="LOAtable",id.name="result", checked=sel_Table, check.name= " ",labels=c("Title","Stat.Method","Footnote"))) }else{ shiny::HTML(checkboxTableInput( tmploaTable, table.id="LOAtable",id.name="result", checked=sel_Table, check.name= " ",labels=c("Title","Stat.Method","Footnote"), showSelectedOnly=TRUE)) } } }) # Display LOA output$rcode<-renderPrint({ if (all(is.null(loaTF()))||length(which(loaTF()))==0){ return(cat('')) }else{ loalistT<-LOA()[loaTF(),] loalistT$order<-1:nrow(loalistT) if(!'width'%in%colnames(loalistT)) loalistT$width <- NA if(!'height'%in%colnames(loalistT)) loalistT$height <- NA if(!'res'%in%colnames(loalistT)) loalistT$res <- NA temp.vdic <- Vdic() temp.vdic <- temp.vdic[,!colnames(temp.vdic)%in%c('width', 'height','res')] codelist<-merge(loalistT,Vdic(),by=c('Request.Name'),all.x=TRUE) codelist<<-codelist[order(codelist$order,codelist$Layout,decreasing=FALSE),] if(is.null(input$tumor) || is.na(input$tumor)) title0<-paste0("Study: ",input$study,"\t\t", " ") else title0<-paste0("Study: ",input$study,"\t\t","Tumor Type: ",input$tumor) r_out<-runcode(codelist=codelist, datPath=input$datPath, outPath=input$outPath, libs=paste0(r.lib.alert,collapse='\n'), sourceCode=Vdic()$Source[!is.na(Vdic()$Request.Name)&!is.na(Vdic()$Source)], subCode=subRcode, title=title0,devpath=devpath, params1=params[params.ord], paramLabs1=params.lab[params.ord], outBcode=Vdic()$PlotCode[Vdic()$Num==1] ) rcode<<-r_out cat(r_out) } }) # Generate R code output$scode<-renderPrint({ files<-file.path(local.path1, unique(Vdic()$Source[!is.na(Vdic()$Source)])) f1<-files[tolower(substring(files, nchar(files)-1,))==".r"] if(length(f1)>1) f1<-f1[!grepl('rcode.r', f1)] rF<-fLoop<-f1 while(length(fLoop)>0){ f0<-NULL for(i in 1:length(f1)){ f2<-file.path(local.path1, "users", checkSource(fnm=f1[i])) fLoop<-fLoop[fLoop!=f1[i]] if(length(f2)>0){ f0<-c(f0, f2) rF<-c(rF, f2) } } if(length(f0)>0){ fLoop<-f1<-f0 } } f1<-unique(rF) f1<-f1[length(f1):1] #so that source files can be run first if(allSourceIn1||input$showAllSource){ #copy all the source code into one file code00<-lapply(f1,readLines) code00<-lapply(code00, function(x){gsub("source", "###Search the copied code in this file\n### source", x)}) code00<-unlist(lapply(1:length(f1), function(x){c(" ", " ", paste0('#---Source ',x,': "',f1[x],'"---#'), " ", code00[[x]])})) code00<-c(paste0("if(TRUE) { #list of ", length(f1), " R source files"), paste0(" # source(file=paste0(local.path1, \'", gsub(local.path1, '', f1), "\'))"), paste0("} #end of ", length(f1), " R source files."), code00) } else {#only list the source files code00<-c(paste0("if(TRUE) { #list of ", length(f1), " R source files"), paste0(" source(file=paste0(local.path1, \'", gsub(local.path1, '', f1), "\'))"), paste0("} #end of ", length(f1), " R source files.") ) } code11<<-code00 cat(paste0(code00,collapse='\n')) }, width=60) # Generate Source code #------ Download LOA, R code, RTF output ------# output$save_loa<-downloadHandler( filename=function(){paste0(input$study,"_", input$tumor,"_loa.csv")}, content=function(file){ write.csv(LOA()[loaTF(),],file,row.names=FALSE, fileEncoding = 'UTF-8') }) # Download LOA #------ Download EPS plot ------# output$getEPS <- downloadHandler( filename="current_BEACH_EPS_Plot.eps", content =function(file){ postscript(file, title = paste("BEACH Output", pdf.label), height=tfl.h/tfl.r, width=tfl.w/tfl.r, pointsize = 1/tfl.r ) plottry<-try(eval(parse(text=input0.code[1]))) if(class(plottry)[1]=='try-error') { plot(0,axes=F, col='white',ylab='',xlab='') legend('top', 'Plotting\nError', cex=5, bty='n', text.col='red') } dev.off() } ) #------ Download PDF plot ------# output$getPDF <- downloadHandler( filename="current_BEACH_PDF_Plot.pdf", content =function(file){ pdf(file, title = paste("BEACH Output", pdf.label), height=tfl.h/tfl.r, width=tfl.w/tfl.r, pointsize = 1/tfl.r ) plottry<-try(eval(parse(text=input0.code[1]))) if(class(plottry)[1]=='try-error') { plot(0,axes=F, col='white',ylab='',xlab='') legend('top', 'Plotting\nError', cex=5, bty='n', text.col='red') } dev.off() } ) #--------save output as a RTF file------------# output$save_output<-downloadHandler( filename=function(){ if(input$onefileRTF=='one file'){ f1<-paste0(input$study,"_",input$tumor, "_", Sys.Date(), ".rtf") }else{ f1<-paste0(input$study,"_",input$tumor, "_", Sys.Date(), ".zip") } return(f1) }, content=function(file){ if(is.null(input$tumor) || is.na(input$tumor) || gsub(" ", '', input$tumor)=='') title0<-c(paste0("Study: ",input$study), '') else title0<-c(paste0("Study: ",input$study), paste0("Tumor Type: ",input$tumor)) loalistT<<-LOA()[loaTF(),] loalistT$order<-1:nrow(loalistT) codelist<-merge(loalistT, Vdic(),by='Request.Name',all.x=TRUE) codelist<-codelist[order(codelist$order,codelist$Layout,decreasing=FALSE),] codelist$width <- codelist$width.x codelist$height <- codelist$height.x codelist$res <- codelist$res.x codelist<<-codelist #define the page margin mag1<-1 #define the font size on each page fs <<- 8 if(input$landscp=="Landscape"){ pageW<-11 #page width pageH<-8.5 #page height nline<-52 #number of lines on a page nline.max<- 35 #maximum number of table rows on a page nline.min<- 5 #minimum number of table rows on a page } else { pageW<-8.5 #page width pageH<-11 #page height nline<-68 #number of lines on a page nline.max <- 50 #maximum number of table rows on a page nline.min <- 5 #minimum number of table rows on a page } maxH<-pageH-4*mag1 maxW<-pageW-2*mag1 if(input$onefileRTF=='one file'){ rtf<-RTF(file, width=pageW, height=pageH, font.size=fs,omi=rep(mag1, 4) ) rtf$.rtf <- gsub('\\rtf1\\ansi', '\\rtf1\\ansi\\BEACHoutput', rtf$.rtf, fixed=TRUE) } # rtf$.rtf <- gsub('Times New Roman', 'Courier New', rtf$.rtf) # make "Courier New" as default npage<-1 prd.status<-'' nfile<-0 zipfs<-NULL #reorder codelist according to heading levels all.tit <- codelist$Titles all.tit0<- strsplit(all.tit, split='HHH:', fixed=TRUE) all.tit0<-lapply(all.tit0, function(x){ if(gsub(" ", "", x[1])==""){return(x[-1])} else{ return(x)} }) totLayer<-max(sapply(all.tit0, length)) all.tit0<-lapply(all.tit0, function(x){ c(x, rep(NA, max(0, totLayer-length(x)))) }) mat.tit <-t( matrix(unlist(all.tit0), nrow=totLayer) ) if(ncol(mat.tit)>1){ wh.tit <- do.call(order, as.data.frame(mat.tit)) codelist<-codelist[wh.tit,] mat.tit <-mat.tit[wh.tit, ] } if(is.vector(mat.tit)){ mat.tit <- matrix(mat.tit, nrow=1) } mat.1<-matrix(TRUE, nrow=1, ncol=ncol(mat.tit)) mat.tit[is.na(mat.tit)] <- "" nr.mat <- nrow(mat.tit) mat.1<- rbind(mat.1, !apply(mat.tit, 2, function(x){x[2:nr.mat]==x[1:(nr.mat-1)]}) ) if(ncol(mat.1)>1){ mat.1<-t( apply(mat.1, 1, function(x){ wh.T<- which(x) if(length(wh.T)>0) x[wh.T[1]:length(x)] <- TRUE x }) ) } for (i in 1:nrow(codelist)){ if (!is.na(codelist[i,params.lab[1]])&&is.na(codelist[i,params[1]])) next if(!all(is.na(codelist[i,params]))){ #k.list<-params[!is.na(codelist[i,params])]\ k.list<-sort(params) for (k in k.list[length(k.list):1]){ tmp0<-unlist(strsplit(as.character(codelist[i,k]),',',fixed=TRUE)) tmp<-ifelse(any(is.na(as.numeric(tmp0))),paste0('c(\"',paste0(tmp0,collapse='\",\"'),'\")'), paste0('c(',codelist[i,k],')')) codelist$PlotCode[i]<- gsub(paste0('input$',k),tmp,codelist$PlotCode[i],fixed=TRUE) } } nfile<-nfile+1 #if all TFLs are NOT saved to one RTF file, a zip file will be downloaded if(input$onefileRTF!='one file'){ f2<-file.path(local.path2, paste0(input$study,"_",input$tumor, "_", Sys.Date(),'_', nfile, ".rtf")) zipfs<-c(zipfs, f2) rtf<-RTF(f2, width=pageW, height=pageH,font.size=fs, omi=rep(mag1, 4) ) rtf$.rtf <- gsub('\\rtf1\\ansi', '\\rtf1\\ansi\\BEACHoutput', rtf$.rtf, fixed=TRUE) } #Add Plot tmp<-eval(parse(text=codelist$tmp[i])) tflname<-ifelse(is.na(codelist[i,params[1]]), #Condition paste0(tflfile,codelist$Num[i]), #if TRUE paste0(tflfile,codelist$Num[i],'x', #if FALSE paste0(#Paste all UIs together sapply(params,function(y){ y0<-codelist[i,y] if(!is.null(y0)){y0[is.na(y0)]<-''} y0<-paste0(y0[length(y0):1],collapse='_') #Paste all Params for each UI substring(y0, max(nchar(y0)-30,1)) }),collapse='')) ) fig.name<-paste0(gsub("[[:punct:]]","",tflname),'.png') fig.name<-gsub(" ", "", fig.name) fig.name.i<-file.path(local.path3,fig.name) tab.name<-paste0(gsub("[[:punct:]]","",tflname),'.rdata') tab.name<-gsub(" ", "", tab.name) tab.name.i<-file.path(local.path3,tab.name) if(codelist$Type.y[i]=='Figure'){ figH<-eval(parse(text=codelist$height[i])) figW<-eval(parse(text=codelist$width[i])) figR<-eval(parse(text=codelist$res[i])) png(file=fig.name.i, height=figH, width=figW, res=figR) plottry<<-try(eval(parse(text=codelist$PlotCode[i]))) if(class(plottry)[1]=='try-error') { plot(0,axes=F, col='white',ylab='',xlab='') legend('top', 'Plotting\nError', cex=5, bty='n', text.col='red') }else if(grepl('gg', class(plottry))){ ggsave(fig.name.i, plottry, height=figH/100, width=figW/100, dpi=figR, limitsize=FALSE) } else {} dev.off() #Add Header title00<-title0 title00[2]<-paste(title0[2],' Page', npage, ' ', format(Sys.time(), "%H:%M %d%b%Y"), " ", prd.status) # main header npage<-npage+1 title<-codelist$Titles[i] for(t1 in 1:ncol(mat.tit)){ if(mat.1[i,t1] && mat.tit[i,t1]!=""){ addHeader(rtf, title=mat.tit[i,t1], font.size=10, TOC.level=t1) }else if (mat.tit[i,t1]!="") { addParagraph(rtf, mat.tit[i,t1]) }else{} } #addParagraph(rtf, title) addParagraph(rtf, title00) rtf$.font.size <- fs tmW<- min(eval(parse(text=codelist$width[i]))/90, maxW) tmH<- min(eval(parse(text=codelist$height[i]))/90, maxH) tmR<- eval(parse(text=codelist$res[i])) addPng(rtf, fig.name.i, width=tmW, height=tmH, res=tmR, col.justify='L') #footnote for figures #addNewLine(rtf, n=1) footnote<-codelist$Footnote[i] addParagraph(rtf, footnote) } #Add Table if(codelist$Type.y[i]=='Table'){ tab.h <<- codelist$height[i] tab.w <<- as.numeric( eval(parse(text=paste("strsplit(' ", codelist$width[i], " ', split=',')") ))[[1]] ) tmp<-eval(parse(text=codelist$tmp[i])) codelist$PlotCode[i] print( outTable <<- eval(parse(text= codelist$PlotCode[i])) ) print(outTable) tmptab <<- eval(parse(text= codelist$PlotCode[i])) #check colnames outTable.colNm<-colnames(outTable) ot1 <- strsplit(outTable.colNm, split=";", fixed=TRUE) ot1n<-sapply(ot1, length) if(max(ot1n)==1){ multiHeader<-FALSE }else{ multiHeader<-TRUE nheader <- max(ot1n) #add extra row if a column names' level is smaller than the others ot1ns <- ot1n < nheader outTable.colNm[ot1ns] <- paste0(outTable.colNm[ot1ns], sapply(nheader-ot1n[ot1ns], function(x){paste(rep('; ',x), collapse = '')}) ) colnames(outTable) <- outTable.colNm ot2 <- sapply(outTable.colNm, strsplit, split=';', fixed=TRUE) names(ot2) <- NULL ot2<-matrix( unlist(ot2), ncol=length(ot2)) var.ul <- unique(as.vector(ot2[-nrow(ot2),])) var.ul0 <- gsub(' ', '', var.ul) var.ul0 <- var.ul[var.ul0!=""] } footnote<-codelist$Footnote[i] footnote<-ifelse(is.na(footnote), '', footnote) nrTab<-nrow(outTable) ncTab<-ncol(outTable) print(paste("footnote: ", footnote)) if(is.null(footnote)) footnote<-" " if(!is.character(footnote)) footnote <- " " nrFoot<-1+length(strsplit(footnote, split='\n', fixed=TRUE)[[1]]) nline1<-max(1, nline-nrFoot - 10) #header lines tWidth<-pageW-mag1*2 nc<-nchar(as.character(outTable[,1])) #use the 1st column width for table width c1W<-pmax(max(nc)*0.079/2, 20*0.1) caW<-nc*0.1 if(pageW < 9){ lcW<-.711 if(ncol(outTable)>2){ othW<-(tWidth-c1W-lcW)/(ncol(outTable)-2) centW<-rep(othW,ncol(outTable)-2) cWs<-c(c1W,centW,lcW) }else{ cWs<-c(c1W, lcW) othW<-1 } } else{ if(ncol(outTable)>1){ othW<-(tWidth-c1W)/(ncol(outTable)-1) centW<-rep(othW,ncol(outTable)-1) cWs<-c(c1W,centW) }else{ cWs<-c(c1W,0) othW<-1 } } max_cW<-max(apply(outTable,2, function(x){max(nchar(x))})) max_rW1<-ceiling(max_cW/othW) if(multiHeader) nline1 <- nline.max else nline1<-max(min(nline1-max_rW1+1, nline.max), nline.min) #nline1 is the max number Table rows shown on each page if(tab.h<=nline.max & tab.h>=1){ nline1 <- tab.h } if(length(tab.w) == length(cWs) ){ cWs <- tab.w } nline1 <<- nline1 nrTab <<- nrTab for(j in 1:ceiling(nrTab/(nline1))){ #j matches the page number of the table #Add Header title00<-title0 title00[2]<-paste0(title0[2], ' Page ', npage, ' ', format(Sys.time(), "%H:%M %d%b%Y"), " ", prd.status) # main header npage<-npage+1 title<-codelist$Titles[i] for(k in 1:length(title00)) title00[k]<-paste0(title00[k], paste(rep(' ', max(0, pageW*7-nchar(title00[k]))), collapse='')) title00<-paste(c(title00, "\n"), collapse=' ') #add heading sections or bookmark for(t1 in 1:ncol(mat.tit)){ if(j==1 && mat.1[i,t1] && mat.tit[i,t1]!=""){ addHeader(rtf, title=mat.tit[i,t1], font.size=10, TOC.level=t1) }else if (mat.tit[i,t1]!="") { addParagraph(rtf, mat.tit[i,t1]) }else{} } #addParagraph(rtf, title) rtf$.font.size <- 10 #define the font size of titles addParagraph(rtf, title00) rtf$.font.size <- fs #redefine the font size of text bottLine<-min(nline1*j, nrTab) if(TRUE){#the table structure previously used. tableBL<- bottLine-((j-1)*nline1) tb1<-outTable[((j-1)*nline1+1):bottLine,] if(is.null(nrow(tb1))){ tb1<-data.frame(` `=tb1) } if(multiHeader){# 17-Mar-2016 rtf.table.out(rtf, tb=tb1, cell1=max(nheader+1,3), #number of levels in header and then plus 1 nheader=max(nheader,2), #number of levels in header colFormat=c("L", rep("C",ncol(outTable)-1)), nline.body= nline1, #min(tableBL, ncol(tb1)), #number of lines per page height=pageH, width=pageW, omi=rep(mag1, 4), cw=cWs, #column width var.ul=var.ul0 #key string for underline, must be the entire string #eg. if changing " X1" to "X1", then it will not have the underline ) if( exists("outTable") ) {rm('outTable'); outTable <<- tmptab} addParagraph(rtf,footnote) } else { rtf<-rtf_table_out_as_sas(rtf, tb1, cw=cWs, colFormat=c("L", rep("J",ncol(outTable)-1)), nline.body=tableBL, width=maxW, height=maxH, omi=rep(mag1, 4) ) addParagraph(rtf,footnote) } } if(bottLine<nrTab ) addPageBreak(rtf, width=pageW, height=pageH, font.size=fs, omi=rep(mag1, 4) ) } } #get a new RTF page for the next analysis if(i < nrow(codelist)) addPageBreak(rtf, width=pageW, height=pageH, font.size=fs, omi=rep(mag1, 4) ) #one file is for one analysis if(input$onefileRTF!='one file'){ done(rtf) print(paste(f2, 'is saved.')) } } if(input$onefileRTF=='one file'){ done(rtf) }else{ zipfs.gb<<-zipfs zip(zipfile=file, files=zipfs) } }) # Download rtf output #---------End of save output as a RTF file---------------# #--------save output as a shiny::HTML file------------# output$save_outputH<-renderUI({ if(is.null(input$outputH)||input$outputH==0){ return(NULL) } if(!dir.exists(htmlPath)){ return(shiny::HTML('Please input an existing director for HTML output!')) } isolate({ curP0<-getwd() tp<-try(setwd(input$hPath)) if(class(tp)[1]=="try-error"){ return(shiny::HTML('<h6>The path for HTML file output is not working.</h6>')) }else{setwd(curP0)} file00<-paste0(input$study,"_",input$tumor,"_", Sys.Date()) file0<-file.path(input$hPath, file00) file01<-file.path(file0, file00) if(file.exists(file0)){ setwd(file0) try(file.remove(dir())) if(file.exists(file00)){ setwd(file00) try(file.remove(dir())) }else{dir.create(file00, showWarnings=FALSE, recursive=TRUE)} }else{ #create a folder for linked files dir.create(file0, showWarnings=FALSE, recursive=TRUE) dir.create(file.path(file0, file00), showWarnings=FALSE, recursive=TRUE) } title0<-paste0("Study: ",input$study,"\t\t","Tumor Type: ",input$tumor) loalistT<-LOA()[loaTF(),] loalistT$order<-1:nrow(loalistT) codelist<-merge(loalistT, Vdic(),by='Request.Name',all.x=TRUE) codelist<-codelist[order(codelist$order,codelist$Layout,decreasing=FALSE),] ind<-0 #start HTML #remember to create a folder under htmlPath setwd(curP0) indexH<-readLines(con=file.path(htmltem, 'index.htm')) bodyH<-readLines(con=file.path(htmltem, 'body.htm')) bodyH<-gsub("Biomarker Analyses Output From BEACH Platform", title0, bodyH) contH<-readLines(con=file.path(htmltem, 'content.htm')) #one row in one codelist is one page in the study report for (i in 1:nrow(codelist)){#update source code in codelist$PlotCode if (!is.na(codelist[i,params.lab[1]])&&is.na(codelist[i,params[1]]))next if(!all(is.na(codelist[i,params]))){ k.list<-params[!is.na(codelist[i,params])] for (k in k.list[length(k.list):1]){ tmp0<-unlist(strsplit(as.character(codelist[i,k]),',',fixed=TRUE)) tmp<-ifelse(any(is.na(as.numeric(tmp0))), paste0('c(\"',paste0(tmp0,collapse='\",\"'),'\")'), paste0('c(',codelist[i,k],')')) codelist$PlotCode[i] <- gsub(paste0('input$',k), tmp,codelist$PlotCode[i], fixed=TRUE) } } #Add Header title<-codelist$Titles[i] tmpTit<-paste(title0, "/n", title) #Add Plot&Table tmp<-eval(parse(text=codelist$tmp[i])) tflname<-ifelse(is.na(codelist[i,params[1]]), #Condition paste0(tflfile, codelist$Num[i]), #if TRUE paste0(tflfile, codelist$Num[i],'x', #if FALSE paste0(#Paste all UIs together sapply(params,function(y){ y0<-codelist[i,y] if(!is.null(y0)){y0[is.na(y0)]<-''} y0<-paste0(y0[length(y0):1], collapse='_') #Paste all Params for each UI substring(y0, max(nchar(y0)-30,1)) }),collapse='')) ) tflname<-gsub('tfl', paste0('t',i,'fl'),tflname, fixed=TRUE) fig.name<-paste0(gsub("[[:punct:]]","",tflname),'.png') fig.name.i<-file.path(local.path3, fig.name) tab.name<-paste0(gsub("[[:punct:]]","",tflname),'.rdata') tab.name.i<-file.path(local.path3, tab.name) #insert figure if(codelist$Type.y[i]=='Figure'){ myres<-ifelse(is.null(codelist$res[i])||is.na(codelist$res[i]), 150, eval(parse(text=codelist$res[i]))) png(fig.name.i, height=eval(parse(text=codelist$height[i])), width=eval(parse(text=codelist$width[i])), res=myres) plottry<-try(eval(parse(text=codelist$PlotCode[i]))) if(class(plottry)[1]=='try-error') { plot(0,axes=F, col='white',ylab='',xlab='') legend('top', 'Plotting\nError', cex=5, bty='n', text.col='red') } dev.off() fig.name.1<-strsplit(fig.name.i, split="www/",fixed=TRUE)[[1]][2] file.copy(from=fig.name.i, file01) ind<-ind+1 bodyH<-c(bodyH, fig2html(figNm=fig.name.1, figTit=codelist$Titles[i], figH=eval(parse(text=codelist$height[i])), figW=eval(parse(text=codelist$width[i])) , fnote=codelist$Footnote[i], ind=ind )) contH<-c(contH, cLink(tit=codelist$Titles[i], ind=ind)) } #Insert Table if(codelist$Type.y[i]=='Table'){ #generate the temporary table tmp<-eval(parse(text=codelist$tmp[i])) tmptab<-eval(parse(text=codelist$PlotCode[i])) save(tmptab,file=tab.name.i) #load(tab.name.i) outTable<-tmptab ind<-ind+1 bodyH<-c(bodyH, df2html(datF=outTable, tabTit=tmpTit, fnote=codelist$Footnote[i], ind=ind)) contH<-c(contH, cLink(tit=codelist$Titles[i], ind=ind)) } } bodyH<-c(bodyH, '<br>', '</div>', '</body>', '</html>') contH<-c(contH, '<br>', '</ol>', '</body>', '</html>') write(bodyH, file=file.path(file01, 'body.htm')) write(contH, file=file.path(file01, 'content.htm')) indexH<-gsub("tmpfolder", file00, indexH, fixed=TRUE) file1<-paste0(file00,".htm") write(indexH, file=file.path(file0, file1)) setwd(curP0) return(shiny::HTML(paste('<h6>', file.path(file0, file1), 'and its folder are successfully downloaded.</h6>'))) }) }) # Download HTML output #---------End of save output as a HTML file---------------# output$save_data<-downloadHandler( filename=function(){ tt <- paste0('download_tmpData.', input$multdat_ext) return(tt) }, content=function(file){ #if (is.null(input$infile)&&is.null(input$infileR)) # return(NULL) choice<-sapply(AnalyN(),function(x){ ifelse(substr(Vdic()$Title[x],1,5)=='paste', eval(parse(text=Vdic()$Title[x])), Vdic()$Title[x]) }) outList <<- currTabL outdata <<- outList[[1]] sapply(1:length(currTabL), function(x){ assign(paste0('outmplkhdnttawr',x),currTabL[[x]],envir=globalenv() ) } ) if(input$multdat_ext=='rdata'){ save(currTabL,file=file) } else if(input$multdat_ext=='xls'){ WriteXLS(paste0('outmplkhdnttawr',1:length(currTabL)), ExcelFileName=file,SheetNames=1:length(input$multdat)) } else if(input$multdat_ext=='sas'){ if(!is.vector(currTabL[[1]])){ o1<-apply(currTabL[[1]], 2, paste, collapse='\t\t\t') }else{ o1 <- currTabL[[1]] } writeLines(o1,con=file) } else if(input$multdat_ext=='csv'){ write.csv(currTabL[[1]], file=file, row.names=FALSE, fileEncoding='UTF-8') } else if(input$multdat_ext=='xpt'){ #write.xport(currTabL[[1]], file=file, autogen.formats=FALSE) haven::write_xpt(currTabL[[1]], path=file) } }) # Download data output output$save_rcode<-downloadHandler( filename=function(){paste0(input$study,"_",input$tumor,".r")}, content=function(file){ writeLines(rcode,file)}) # Download R code output$save_scode<-downloadHandler( filename=function(){paste0(input$study,"_",input$tumor,"_source.r")}, content=function(file){ writeLines(code11,file) }) # Download Source code output$delete<-renderUI({#remove temporary files if(input$delete_tmpfile==0){ return(NULL) } else { cnt<-cnt+input$delete_tmpfile #for files under the tmpfile folder loatextf<-dir(local.path2) loatextf<-loatextf[nchar(loatextf)>3] if(length(loatextf)>0) loatextf<-loatextf[substr(loatextf,1,3)=='loa'] #for files under the www folder tm_png<-dir(local.path3) tm_png<-tm_png[nchar(tm_png)>3] if(length(tm_png)>0){ tmsel<-substr(tm_png,1,3)=='tfl'|substr(tm_png,2,4)=='tfl'|substr(tm_png,1,2)=='.n'| substr(tm_png,3,4)=='fl'| substr(tm_png,nchar(tm_png)-6,nchar(tm_png))=='.rdata' tm_png<-tm_png[tmsel] } if(length(tm_png)==0 & length(loatextf)==0){ return('Empty now.') }else{ if(length(loatextf)>0){ loatextf<-file.path(local.path2, loatextf) try( do.call(file.remove, as.list(loatextf)) ) } if(length(tm_png)>0){ tm_png<-file.path(local.path3,tm_png) try( do.call(file.remove, as.list(tm_png)) ) } return(paste('Done',cnt)) } } }) #define data subset output$subsetcode1<-renderUI({ if(is.null(input$submitcode)||input$submitcode==0){ subRcode<<-NULL }else{subRcode<<-isolate(input$subRcode)} return(conditionalPanel(condition='true', shiny::HTML("<textarea name=\"subRcode\" rows=\"4\" style=\"width:100%\" placeholder=\"#drag the right bottom corner to make this larger. #indataset is a list object including all the uploaded csv files. #indataset.i is indataset[[1]] by default. indataR is a list object including #all the objects in the uploaded R file. #Input your R code here to re-define indataset.i, for example indataset.i<<-indataset[[1]] indataset.i<<-indataset.i[1:10,] #or indataset.i<<-indataset[[1]]; indataset.i<<-indataset.i[1:10,]\"></textarea>") )) }) output$subsetcode2<-renderPrint({ if(input$submitcode==0 && length(indataset)>0){ indataset.i<<-indataset[[1]] return(NULL) }else if(input$submitcode!=0 && length(indataset)>0){ rpt.cls<-class(try(rpt<-eval(parse(text=subRcode)))) if(rpt.cls!='try-error'){ #source(file.path(local.path1,Vdic()$Source[1])) #source(file.path(local.path1,Vdic()$Source[2])) n.row<-nrow(indataset.i) n.col<-ncol(indataset.i) #sub<-colnames(indataset.i)[grep('subjid',tolower(colnames(indataset.i)))[1]] #n.sub<-length(unique(indataset.i[,sub])) #tmprnt<-paste0('#indataset.i is re-defined. It has ', #n.sub,' subjects, ', # n.row,' rows, ', n.col,' variables.') #print(tmprnt) } rpt }else{} }) output$showAS<-renderUI({#show all source code or not if(input$showAllSource){ allSourceIn1<<-TRUE }else{ allSourceIn1<<-FALSE } }) #######for dynamic output######## output$dynamicPlot <- renderPlot({ eval(parse(text=dynamicCode)) }) output$click_info_DT<-renderUI({ return(DT::dataTableOutput('click_info')) }) output$click_info <- renderDataTable({ # Because it's a ggplot2, we don't need to supply xvar or yvar; if this # were a base graphics plot, we'd need those. near_points <<- nearPoints(dynamicData, input$dynamicPlot_click, xvar=dynamicData.xvar, yvar=dynamicData.yvar, addDist = TRUE) near_points }, rownames = FALSE) output$click_info_dl<-downloadHandler( filename=function(){paste0(input$study,"_",input$tumor,"_clicked_dynamicData.csv")}, content=function(file){ tmpout<-nearPoints(dynamicData, input$dynamicPlot_click, xvar=dynamicData.xvar, yvar=dynamicData.yvar, addDist = TRUE) write.csv(tmpout, file=file, row.names=FALSE, fileEncoding='UTF-8') } ) # Download clicked data output$brush_info_DT<-renderUI({ return(DT::dataTableOutput('brush_info')) }) output$brush_info <- renderDataTable({ if(showBrush) # print(trytry<<-input$dynamicPlot_brush) brush_points<<-brushedPoints(dynamicData, input$dynamicPlot_brush, xvar=dynamicData.xvar, yvar=dynamicData.yvar) brush_points }, rownames = FALSE) ####End for dynamic output######## output$brush_info_dl<-downloadHandler( filename=function(){paste0(input$study,"_",input$tumor,"_brushed_dynamicData.csv")}, content=function(file){ tmpout<-brushedPoints(dynamicData, input$dynamicPlot_brush, xvar=dynamicData.xvar, yvar=dynamicData.yvar) write.csv(tmpout, file=file, row.names=FALSE, fileEncoding='UTF-8') } ) # Download clicked data ####Dynamic data table#### output$outTbl_DT<-renderUI({ return(DT::dataTableOutput('outTbl')) }) output$outTbl<-DT::renderDataTable({ if (all(!Vdic()$Type[AnalyN()] %in% c('Figure','Table'))|| all(eval(parse(text=Vdic()$Condition[AnalyN()])))){ return(NULL) } for (i in AnalyN()[1]){#only render the first table if(!is.na(Vdic()$Title[i])){ title<-ifelse(substr(Vdic()$Title[i],1,5)=='paste', eval(parse(text=Vdic()$Title[i])),Vdic()$Title[i]) titlecode<-paste0('<h3><textarea name=\"titlebox\" rows=\"1\" style=\"width:80%\">', title,'</textarea></h3>')}else{titlecode<-NULL} tflname<-ifelse(all(is.na(widgetOrd()$names)), #Condition paste0(tflfile,Vdic()$Num[i]), #if TRUE paste0(tflfile,Vdic()$Num[i],'x', #if FALSE paste0(#Paste all UIs together sapply(widgetOrd()$names,function(y){ y0<-eval(parse(text=paste0('input$',y))) if(!is.null(y0)){y0[is.na(y0)]<-''} y0<-paste0(y0[length(y0):1],collapse='_') #Paste all Params for each UI substring(y0, max(nchar(y0)-30,1)) }),collapse='')) ) tflname<-gsub(' ', '',tflname) fig.name<-paste0(input$submitcode,gsub("[[:punct:]]", "",tflname),'.png') tab.name<-file.path(local.path3,paste0(input$submitcode,gsub("[[:punct:]]", "",tflname),'.rdata')) if(Vdic()$Type[i]=='Table'){ #if(!file.exists(tab.name)){ if(class(try(tmptab<-eval(parse(text=input0.code))))[1]=='try-error'){ tmptab<-'' } # save(tmptab, file=tab.name) #}else{ # load(tab.name) #} rd_tmptab <<- tmptab return(tmptab) }else{return(NULL)} } }, rownames = FALSE) output$getDataSelected <- renderUI({ data_selected_col1 <<- unique(c( input$click_info_rows_selected, input$brush_info_rows_selected )) if(is.null(input$outTbl_rows_selected)){ data_selected <<- rbind( near_points[!is.na(near_points[,1]) & near_points[,1]%in%data_selected_col1,], brush_points[!is.na(brush_points[,1]) & brush_points[,1]%in%data_selected_col1,] ) } else{ data_selected <<- rd_tmptab[!is.na(rd_tmptab[,1]) & rd_tmptab[,1] %in% input$outTbl_rows_selected,] } return(NULL) }) output$pumpPlotOut<-renderPlot({ if(is.null(input$outTbl_rows_selected)||input$outTbl_rows_selected==0){ return(NULL) } isolate({ if(is.null(click2plot) || !is.function(click2plot)){ click2plot.o(input$outTbl_rows_selected) }else{ click2plot();#input$outTbl_rows_selected needs inside } }) }) ########################## } #close Shiny server# shinyServer(BeachServer)
/scratch/gouwar.j/cran-all/cranData/BEACH/inst/app/server.r
if (TRUE) { # header #/*soh************************************************************************* # CODE NAME : server.r # CODE TYPE : Program # DATE OF UPDATE: 1-Feb-2019 # DESCRIPTION : Server code for BEACH app # SOFTWARE/VERSION# : R 3.3.0 # INFRASTRUCTURE : MS WINDOWS XP # ----------------------------------------------------------------------------- # Ver Author Program History Description # ---- --------------- -------------------------------------------- # 001 Danni Yu program (2013-now) # 002 Chenchen Yu program (2013-2014) # # ----------------------------------------------------------------------------- } myVersionCtr <<- "BEACH1.3.3" BeachUI <- fluidPage( #------- CSS code: Formats of radiobutton & checkbox -------# headerPanel(windowTitle='BEACH', tags$head( tags$link(rel = "stylesheet", type = "text/css"), #href = "bootstrap_dy.css"), tags$style(type="text/css","label.radio { display: inline-block; }", "input[type=\'file\']{color: transparent;}", ".radio input[type=\"radio\"] { float: none; }", "label.checkbox { display: inline-block; }", ".checkbox input[type=\"checkbox\"] { float: none; }", #".shiny-output-error { visibility: hidden; }", #suppress red errors in shiny, to enable using visible #".shiny-output-error:before { visibility: hidden; }", "#TFL{max-width:95%; overflow-x:scroll; max-height:800px; overflow-y:scroll;}", "#Input_outExpert{max-width:95%; overflow-x:scroll; max-height:400px; overflow-y:scroll;}", "#widgetSide{max-width:100%; overflow-x:scroll; max-height:100%; overflow-y:scroll;}", "#add_analysis{height: 36px;}", "#rcode{max-height:1000px; overflow-y:scroll;}", "#scode{max-height:1000px; overflow-y:scroll;}", "#pumpPlotOut{overflow-x:scroll; overflow-y:scroll;}", ".shiny-text-output{max-width:95%; max-height:40%; overflow-y:scroll; }", "th{text-align: center; border: 1px solid black;}", "td{text-align: center; }", "table{border: 2px solid black;}" ))), #-----Start of Main Panel-----# absolutePanel( #for Analysis panel style = "background-color: #FFFFFF;", id = "controls1", class = "panel panel-default", fixed = FALSE, draggable=FALSE, top = "0%", left = "1%", right = "20%", bottom ="auto", width = "auto", height = "auto" , uiOutput('tabs'), uiOutput('AnalysisTab'), uiOutput('SpecialTab') ), #-----Start of Widget Panel-----# absolutePanel( #for widget/parameter panel style = "background-color: #F4F4F4;z-index: 200;", id = "controls1", class = "panel panel-default", fixed = FALSE, draggable = TRUE, top = "0%", left = "auto", right = "0%", bottom ="auto", width = "20%", height = "auto" , p(style="color:black;",strong(myVersionCtr)), checkboxInput("collSidebar", "Show the sidebar for data input", value=TRUE), checkboxInput("useDT", "use renderDataTable", value=FALSE), checkboxInput("pumpPlot", "Show plot in a single window", value=FALSE), radioButtons("ncol.widg.rd", "number of columns", c(1, 2, 3), inline=TRUE), sliderInput('wpW', 'Width of the widget panel', min=20, max=100, value=20, animate=TRUE), uiOutput('beachColor') ), uiOutput('wp.width'), #-----Start of Sidebar Panel for LOA input-----# absolutePanel( #for LOA panel style = "background-color: #F4F4F4;z-index: 500;", id = "controls2", class = "panel panel-default", fixed = FALSE, draggable = TRUE, top = "0%", left = "100%", right = "auto", bottom ="auto", width = "25%", height = "auto" , #------LOA------# p(style="color:black;",strong("List of Analysis")), fileInput('upfile', label='upload a LOA csv file', accept=c('.csv', 'text/csv', 'text/comma-separated-values,text/plain'), multiple=FALSE), actionButton("load_analysis","Load LOA"), downloadButton("save_loa","Save LOA"), checkboxInput('delete_loa', 'Only Selected', value=FALSE), wellPanel( uiOutput('LOA'), width="20%" ), radioButtons('landscp', 'RTF page layout', choices=c("Landscape", "Portrait"), selected="Portrait", inline=TRUE), radioButtons('onefileRTF', 'RTF output', choices=c('one file','multiple files'), selected='one file', inline=TRUE), downloadButton("save_output","OutputRTF"), #output as a RTF file br(), textInput('hPath', label='HTM file location:', value=htmlPath), actionButton("outputH","Overwrite the HTM file"), uiOutput('save_outputH'), checkboxInput('expert', 'expert', value=FALSE), uiOutput('userExp'), checkboxInput('usage', 'usage', value=FALSE), checkboxInput('showAllSource', 'Show all R source code', value=FALSE), #----Data Manipulation, No UI output-----# uiOutput("getData"), uiOutput("getWidgets"), uiOutput("loa"), uiOutput('DTsel'), uiOutput('getDataSelected'), #defined to data_selected uiOutput("getTFL") ), #-----Start of Sidebar Panel for data input-----# div('data-display-if'="input.collSidebar == true", absolutePanel( #for data input panel style = "z-index: 1000;", id = "controls1", class = "panel panel-default", fixed = FALSE, draggable = TRUE, top = "20%", left = "auto", right = "0%", bottom ="auto", width = "20%", height = "auto" , #------Logo------# wellPanel(style = "background-color: #dbdbdb;", #D52B1E Lilly Red 100% uiOutput("setTitle"), # helpText(a('feedback', # target="_blank", # href="")), #------Upload dataset------# checkboxInput('data_reload', 'Make csv files reloadable with risk of messing up data.'), uiOutput('status'), selectInput('comm_chr', "Comment Charactor in a CSV file", c("", "#", "*", "!", "~", "%", "^", "&")), uiOutput('file'), uiOutput("setconfig"), selectInput('config.sel', 'Select A CD in the pool', choices=cdpool2), uiOutput('subsetcode1'), actionButton("submitcode","Submit Code"), div(class='row'), uiOutput('subsetcode2'), actionButton("delete_tmpfile",'Clean trash on server.'), uiOutput('delete') ))) #-----End of Sidebar Panel-----# #-----Start pumpPlot single Window-----# div('data-display-if'="input.pumpPlot == true", absolutePanel( #for pumping out a single window style = "z-index: 999; background-color: #dbdbdb;", id = "controls1", class = "panel panel-default", fixed=FALSE, draggable=TRUE, top="1%", left="20%", right="40%", bottom ="auto", width = "50%", height = "auto" , plotOutput('pumpPlotOut') )) #-----End of Sidebar Panel-----# ) #Generate Tabs shinyUI(BeachUI)
/scratch/gouwar.j/cran-all/cranData/BEACH/inst/app/ui.r
#' @title Biological Entity Dictionary (BED) #' @author Patrice Godard #' @name BED #' @description An interface for the neo4j database providing #' mapping between different identifiers of biological entities. #' This Biological Entity Dictionary (BED) #' has been developed to address three main challenges. #' The first one is related to the completeness of identifier mappings. #' Indeed, direct mapping information provided by the different systems #' are not always complete and can be enriched by mappings provided by other #' resources. #' More interestingly, direct mappings not identified by any of these #' resources can be indirectly inferred by using mappings to a third reference. #' For example, many human Ensembl gene ID are not directly mapped to any #' Entrez gene ID but such mappings can be inferred using respective mappings #' to HGNC ID. The second challenge is related to the mapping of deprecated #' identifiers. Indeed, entity identifiers can change from one resource #' release to another. The identifier history is provided by some resources, #' such as Ensembl or the NCBI, but it is generally not used by mapping tools. #' The third challenge is related to the automation of the mapping process #' according to the relationships between the biological entities of interest. #' Indeed, mapping between gene and protein ID scopes should not be done #' the same way than between two scopes regarding gene ID. #' Also, converting identifiers from different organisms should be possible #' using gene orthologs information. #' #' - [Vignette](../doc/BED.html) #' - Available database instance: <https://github.com/patzaw/BED#bed-database-instance-available-as-a-docker-image> #' - Building a database instance: <https://github.com/patzaw/BED#build-a-bed-database-instance> #' - Repository: <https://github.com/patzaw/BED> #' - Bug reports: <https://github.com/patzaw/BED/issues> #' #' @import utils neo2R dplyr visNetwork stringr NULL
/scratch/gouwar.j/cran-all/cranData/BED/R/BED.R
###############################################################################@ #' Create a BEIDList #' #' @param l a named list of BEID vectors #' @param metadata a data.frame with rownames or #' a column "**.lname**" all in names of l. #' If missing, the metadata is constructed with **.lname** being the names #' of l. #' @param scope a list with 3 character vectors of length one named "be", #' "source" and "organism". #' If missing, it is guessed from l. #' #' @return A BEIDList object which is a list of BEID vectors with 2 additional #' attributes: #' #' - **metadata**: a data.frame with metadata about list elements. #' The "**.lname**" column correspond to the names of the BEIDList. #' - **scope**: the BEID scope ("be", "source" and "organism") #' #' @examples \dontrun{ #' bel <- BEIDList( #' l=list( #' kinases=c("117283", "3706", "3707", "51447", "80271", "9807"), #' phosphatases=c( #' "130367", "249", "283871", "493911", "57026", "5723", "81537" #' ) #' ), #' scope=list(be="Gene", source="EntrezGene", organism="Homo sapiens") #' ) #' scope(bel) #' metadata(bel) #' metadata(bel) <- dplyr::mutate( #' metadata(bel), #' "description"=c("A few kinases", "A few phosphatases") #' ) #' metadata(bel) #' } #' #' @export #' BEIDList <- function( l, metadata, scope ){ if(missing(metadata)){ metadata <- data.frame(.lname=names(l), stringsAsFactors=FALSE) } if(missing(scope)){ scope <- BED::guessIdScope(unlist(l)) warning( "Guessing ID scope:", sprintf("\n - be: %s", scope$be), sprintf("\n - source: %s", scope$source), sprintf("\n - organism: %s", scope$organism) ) } ## Checks ---- stopifnot(is.data.frame(metadata)) if(!".lname" %in% colnames(metadata)){ metadata <- dplyr::mutate(metadata, .lname=rownames(!!metadata)) } metadata$.lname <- as.character(metadata$.lname) stopifnot( is.list(l), all(names(l) %in% metadata$.lname), all(metadata$.lname %in% names(l)), is.list(scope), length(scope)==3, all(c("be", "source", "organism") %in% names(scope)), all(unlist(lapply(scope, length))==1), all(unlist(lapply(scope, is.character))) ) ## BEIDList object ---- toRet <- l attr(toRet, "metadata") <- metadata[ match(names(l), metadata$.lname),, drop=FALSE ] attr(toRet, "scope") <- scope class(toRet) <- c("BEIDList", class(toRet)) return(toRet) } ###############################################################################@ #' @export #' scope.BEIDList <- function(x, ...){ attr(x, "scope") } ###############################################################################@ #' @export #' metadata.BEIDList <- function(x, ...){ attr(x, "metadata") } ###############################################################################@ #' @export #' `metadata<-.BEIDList` <- function(x, value){ return(BEIDList(x, scope=scope(x), metadata=value)) } ###############################################################################@ #' Check if the provided object is a [BEIDList] #' #' @param x the object to check #' #' @return A logical value #' #' @export #' is.BEIDList <- function(x){ inherits(x, "BEIDList") } ###############################################################################@ #' @export #' length.BEIDList <- function(x){ y <- x class(y) <- "list" length(y) } ###############################################################################@ #' @export #' stack.BEIDList <- function(x, ...){ class(x) <- "list" return(stack(x)) } ###############################################################################@ #' @export #' format.BEIDList <- function(x, ...){ toRet <- sprintf( 'BEIDList of %s elements gathering %s BEIDs in total', length(x), length(unique(unlist(x))) ) toRet <- paste( toRet, sprintf( ' - Scope: be="%s", source="%s", organism="%s"', scope(x)$be, scope(x)$source, scope(x)$organism ), sep="\n" ) toRet <- paste( toRet, sprintf( ' - Metadata fields: "%s"', paste(colnames(metadata(x)), collapse='", "') ), sep="\n" ) return(toRet) } ###############################################################################@ #' @export #' print.BEIDList <- function(x, ...) cat(format(x, ...), "\n") ###############################################################################@ #' @export #' '[.BEIDList' <- function(x, i){ l <- x class(l) <- "list" l <- l[i] metadata <- metadata(x) metadata <- metadata[ match(names(l), metadata$.lname),, drop=FALSE ] return(BEIDList( l=l, metadata=metadata, scope=scope(x) )) } ###############################################################################@ #' @export #' '[<-.BEIDList' <- function(x, i, value){ stop("'[<-' is not supported for BEIDList: use 'c' instead") } ###############################################################################@ #' @export #' '[[<-.BEIDList' <- function(x, i, value){ stop("'[[<-' is not supported for BEIDList: use 'c' instead") } ###############################################################################@ #' @export #' 'names<-.BEIDList' <- function(x, value){ value <- unique(as.character(value)) stopifnot(length(x)==length(value)) metadata <- metadata(x) scope <- scope(x) l <- x class(l) <- "list" names(l) <- value metadata <- dplyr::mutate(metadata, .lname=!!value) return(BEIDList( l=l, metadata=metadata, scope=scope )) } ###############################################################################@ #' @export #' c.BEIDList <- function(...){ inputs <- list(...) il <- lapply(inputs, function(x){class(x) <- "list"; return(x)}) imd <- do.call(dplyr::bind_rows, lapply(inputs, attr, which="metadata")) l <- do.call(c, il) stopifnot( all(unlist(lapply(inputs, is.BEIDList))), all(unlist(lapply(inputs, identicalScopes, inputs[[1]]))), sum(duplicated(names(l)))==0 ) return(BEIDList( l=l, metadata=imd[ match(names(l), imd$.lname),, drop=FALSE ], scope=scope(inputs[[1]]) )) } ###############################################################################@ #' Convert a BEIDList object in a specific identifier (BEID) scope #' #' @param x the BEIDList to be converted #' @param be the type of biological entity to focus on. #' If NULL (default), it's taken from `scope(x)`. #' Used if `is.null(scope)` #' @param source the source of BEID to focus on. #' If NULL (default), it's taken from `scope(x)`. #' Used if `is.null(scope)` #' @param organism the organism of BEID to focus on. #' If NULL (default), it's taken from `scope(x)`. #' Used if `is.null(scope)` #' @param scope a list with the following element: #' - **be** #' - **source** #' - **organism** #' #' @param force if TRUE the conversion is done even between identical scopes #' (default: FALSE) #' @param restricted if TRUE (default) the BEID are limited to current version #' of the source #' @param prefFilter if TRUE (default) the BEID are limited to prefered #' identifiers when they exist #' @param ... additional parameters to the BEID conversion function #' #' @return A BEIDList #' #' @export #' focusOnScope.BEIDList <- function( x, be=NULL, source=NULL, organism=NULL, scope=NULL, force=FALSE, restricted=TRUE, prefFilter=TRUE, ... ){ if(is.null(be)){ be <- scope(x)$be } if(is.null(source)){ source <- scope(x)$source } if(is.null(organism)){ organism <- scope(x)$organism } if(!is.null(scope)){ be <- scope$be source <- scope$source organism <- scope$organism } taxid <- getTaxId(organism) stopifnot(length(taxid)==1) orgsn <- getOrgNames(taxid) orgsn <- orgsn$name[which(orgsn$nameClass=="scientific name")] stopifnot(length(orgsn)==1) ## if( !force && scope(x)$be==be && scope(x)$source==source && getTaxId(scope(x)$organism)==taxid ){ return(x) }else{ l <- x class(l) <- "list" md <- metadata(x) fscope <- scope(x) fscope$organism <- ifelse( fscope$organism=="any", organism, fscope$organism ) toRet <- convBeIdLists( l, from=fscope$be, from.source=fscope$source, from.org=fscope$organism, to=be, to.source=source, to.org=organism, restricted=restricted, prefFilter=prefFilter, ... ) toRet <- BEIDList( l=toRet[md$.lname], metadata=md, scope=list( be=be, source=source, organism=orgsn ) ) return(toRet) } } ###############################################################################@ #' @export #' filterByBEID.BEIDList <- function( x, toKeep, ... ){ l <- lapply( x, intersect, toKeep ) l <- l[which(unlist(lapply(l, length))>0)] metadata <- metadata(x) metadata <- metadata[ match(names(l), metadata$.lname),, drop=FALSE ] return(BEIDList( l=l, metadata=metadata, scope=scope(x) )) }
/scratch/gouwar.j/cran-all/cranData/BED/R/BEIDList.R
#' Find all BEID and ProbeID corresponding to a BE #' #' @param beids a character vector of gene identifiers #' @param be one BE. **Guessed if not provided** #' @param source the source of gene identifiers. **Guessed if not provided** #' @param organism the gene organism. **Guessed if not provided** #' @param entities a numeric vector of gene entity. If NULL (default), #' beids, source and organism arguments are used to identify BEs. #' Be carefull when using entities as these identifiers are not stable. #' @param canonical_symbols return only canonical symbols (default: TRUE). #' #' @return A data.frame with the following fields: #' #' - **value**: the identifier #' - **be**: the type of BE #' - **source**: the source of the identifier #' - **organism**: the BE organism #' - **symbol**: canonical symbol of the identifier #' - **BE_entity**: the BE entity input #' - **BEID** (optional): the BE ID input #' - **BE_source** (optional): the BE source input #' #' @export #' beIDsToAllScopes <- function( beids, be, source, organism, entities=NULL, canonical_symbols=TRUE ){ if(is.null(entities)){ stopifnot( is.character(beids), all(!is.na(beids)), length(beids)>0 ) ## if(missing(be) || missing(source) || missing(organism)){ toWarn <- TRUE }else{ toWarn <- FALSE } guess <- guessIdScope(ids=beids, be=be, source=source, organism=organism) if(is.null(guess)){ warning("Could not find the provided ids") if(missing(be) || missing(source) || missing(organism)){ stop("Missing be, source or organism information") } }else{ if(is.na(guess$be)){ warning( "The provided ids does not match the provided scope", " (be, source or organism)" ) if(missing(be) || missing(source) || missing(organism)){ stop("Missing be, source or organism information") } }else{ be <- guess$be source <- guess$source organism <- guess$organism } } if(toWarn){ warning( "Guessing ID scope:", sprintf("\n - be: %s", be), sprintf("\n - source: %s", source), sprintf("\n - organism: %s", organism) ) } ## if(source=="Symbol"){ stop('source cannot be "Symbol"') } query <- sprintf( paste( 'MATCH (bid:%s {%s:"%s"})', '-[:is_associated_to|is_replaced_by|targets*0..]->()', '-[:identifies]->(be)', '<-[:is_expressed_as|is_translated_in|codes_for*0..2]-(:Gene)', '-[:belongs_to]->(tid:TaxID)', '-[:is_named]->(o:OrganismName {value_up:"%s"})', 'WHERE bid.value IN $ids' ), paste0(be, "ID"), ifelse(be=="Probe", "platform", "database"), source, toupper(organism) ) ids <- beids }else{ stopifnot( is.numeric(entities), all(!is.na(entities)), length(entities)>0 ) warning( 'Be carefull when using entities as these identifiers are ', 'not stable.' ) query <- paste( 'MATCH (be)', '<-[:is_expressed_as|is_translated_in|codes_for*0..2]-(:Gene)', '-[:belongs_to]->(tid:TaxID)', 'WHERE id(be) IN $ids' ) ids <- unique(entities) } query <- paste( query, 'MATCH (be)', '<-[:identifies]-()<-[:is_associated_to|is_replaced_by|targets*0..]-', '(beid)', 'MATCH (tid)', '-[:is_named {nameClass:"scientific name"}]->(beo:OrganismName)', sprintf( 'OPTIONAL MATCH (beid)-[k:is_known_as%s]->(bes)', ifelse(canonical_symbols, " {canonical:true}", "") ), 'RETURN DISTINCT', 'beid.value as value, labels(beid) as be,', 'beid.database as db, beid.platform as pl,', 'beid.preferred as preferred,', 'bes.value as bes,', 'k.canonical as canBes,', 'beo.value as organism,', 'id(be) as BE_entity' ) if(is.null(entities)){ query <- paste( query, ', bid.value as BEID,', sprintf( 'bid.%s as BE_source', ifelse(be=="Probe", "platform", "database"), be ) ) } toRet <- bedCall( neo2R::cypher, query=query, parameters=list(ids=as.list(ids)) ) if(!is.null(toRet)){ toRet <- dplyr::mutate( toRet, "be"=stringr::str_remove( stringr::str_remove(toRet$be, "BEID [|][|] "), "ID$"), "source"=ifelse(is.na(toRet$db), toRet$pl, toRet$db) ) toRet <- dplyr::select(toRet, -"db", -"pl") ## toRet1 <- dplyr::arrange(toRet, desc(.data$canBes)) toRet1 <- dplyr::group_by( toRet1, .data$value, .data$preferred, .data$be, .data$source, .data$organism, .data$BE_entity ) toRet1 <- dplyr::summarise_all(toRet1, function(x)x[1]) toRet1 <- dplyr::select(toRet1, -"canBes") toRet1 <- dplyr::ungroup(toRet1) # toRet1 <- dplyr::distinct(dplyr::select(toRet, "bes")) toRet2 <- dplyr::select(toRet, -"value", -"preferred") toRet2 <- dplyr::filter(toRet2, !is.na(toRet2$bes)) ## toRet2 <- dplyr::mutate( toRet2, "value"=.data$bes, source="Symbol" ) toRet2 <- dplyr::rename(toRet2, "preferred"="canBes") ## toRet2 <- dplyr::distinct(toRet2) toRet <- dplyr::bind_rows(toRet1, toRet2) toRet <- dplyr::rename(toRet, "symbol"="bes") if(is.null(entities)){ toRet <- dplyr::select( toRet, "value", "preferred", "be", "source", "organism", "symbol", "BE_entity", "BEID", "BE_source" ) }else{ toRet <- dplyr::select( toRet, "value", "preferred", "be", "source", "organism", "symbol", "BE_entity" ) } } return(toRet) }
/scratch/gouwar.j/cran-all/cranData/BED/R/beIDsToAllScopes.R
#' Call a function on the BED graph #' #' @param f the function to call #' @param ... params for f #' @param bedCheck check if a connection to BED exists (default: FALSE). #' #' @return The output of the called function. #' #' @examples \dontrun{ #' result <- bedCall( #' cypher, #' query=prepCql( #' 'MATCH (n:BEID)', #' 'WHERE n.value IN $values', #' 'RETURN n.value AS value, n.labels, n.database' #' ), #' parameters=list(values=c("10", "100")) #' ) #' } #' #' @seealso [checkBedConn] #' #' @export #' bedCall <- function(f, ..., bedCheck=FALSE){ if(bedCheck) if(!checkBedConn()){ stop("No connection") } do.call(f, list(graph=get("graph", bedEnv), ...)) }
/scratch/gouwar.j/cran-all/cranData/BED/R/bedCall.R
#' Feeding BED: Imports a data.frame in the BED graph database #' #' Not exported to avoid unintended modifications of the DB. #' #' @param cql the CQL query to be applied on each row of toImport #' @param toImport the data.frame to be imported as "row". #' Use "row.FIELD" in the cql query to refer to one FIELD of the toImport #' data.frame #' @param periodicCommit use periodic commit when loading the data #' (default: 1000). #' @param ... additional parameters for [bedCall] #' #' @return the results of the query #' #' @seealso [bedCall], [neo2R::import_from_df] #' bedImport <- function( cql, toImport, periodicCommit=10000, ... ){ invisible(bedCall( neo2R::import_from_df, cql=cql, toImport=toImport, periodicCommit=periodicCommit, ... )) }
/scratch/gouwar.j/cran-all/cranData/BED/R/bedImport.R
###############################################################################@ ## Helpers (not exported) ---- #' @importFrom shiny callModule moduleServer <- function(id, module){ shiny::callModule(module, id) } highlightText <- function(text, value){ value <- sub('^"', '', sub('"$', '', value)) value <- gsub("[[:punct:]]", ".?", value) return(unlist(lapply( text, function(x){ if(is.na(x)){ return(x) } p <- gregexpr(value, x, ignore.case=TRUE)[[1]] if(p[1]>0){ toRet <- c(substr(x, 0, p[1]-1)) for(i in 1:length(p)){ toRet <- c( toRet, '<mark style="background-color:yellow;font-weight:bold;">', substr(x, p[i], p[i]+attr(p, "match.length")[i]-1), '</mark>', substr( x, p[i]+attr(p, "match.length")[i], min( p[i+1]-1, nchar(x)+1, na.rm=TRUE ) ) ) } toRet <- paste(toRet, collapse="") }else{ toRet <- x } return(toRet) } ))) } ###############################################################################@ ## Module ---- #' Shiny module for searching BEIDs #' #' @param id an identifier for the module instance #' @param toGene focus on gene entities (default=TRUE): matches from other #' BE are converted to genes. #' @param multiple allow multiple selections (default=FALSE) #' @param beOfInt if toGene==FALSE, BE to consider (default=NULL ==> all) #' @param selectBe if toGene==FALSE, display an interface for selecting BE #' @param orgOfInt organism to consider (default=NULL ==> all) #' @param selectOrg display an interface for selecting organisms #' @param tableHeight height of the result table (default: 150) #' #' @return A reactive data.frame with the following columns: #' - **beid**: the BE identifier #' - **preferred**: preferred identifier for the same BE in the same scope #' - **be**: the type of biological entity #' - **source**: the source of the identifier #' - **organism**: the BE organism #' - **entity**: internal identifier of the BE #' - **match**: the matching character string #' #' @examples \dontrun{ #' library(shiny) #' library(BED) #' library(DT) #' #' ui <- fluidPage( #' beidsUI("be"), #' fluidRow( #' column( #' 12, #' tags$br(), #' h3("Selected gene entities"), #' DTOutput("result") #' ) #' ) #' ) #' #' server <- function(input, output){ #' found <- beidsServer("be", toGene=TRUE, multiple=TRUE, tableHeight=250) #' output$result <- renderDT({ #' req(found()) #' toRet <- found() #' datatable(toRet, rownames=FALSE) #' }) #' } #' #' shinyApp(ui = ui, server = server) #' } #' #' @importFrom shiny reactive renderUI observe fluidRow column textInput NS selectizeInput reactiveValues withProgress req #' @importFrom DT datatable DTOutput renderDT formatStyle styleEqual #' @export #' beidsServer <- function( id, toGene=TRUE, multiple=FALSE, beOfInt=NULL, selectBe=TRUE, orgOfInt=NULL, selectOrg=TRUE, tableHeight=150 ){ if(toGene){ selectBe <- FALSE beOfInt <- c(listBe(), "Probe") } moduleServer(id, function(input, output, session) { ## Main UI ---- allOrg <- sort(listOrganisms()) allBe <- c(listBe(), "Probe") ni <- 1 if(selectOrg){ ni <- ni+1 } if(selectBe){ ni <- ni+1 } cw <- 12 %/% ni output$mainUI <- shiny::renderUI({ shiny::fluidRow(shiny::column(12, shiny::fluidRow( shiny::column( cw, shiny::textInput( inputId=shiny::NS(id, "beSearchTerm"), label="Search a gene", placeholder='e.g. snca, ENSG00000186868, "M-CSF receptor"', width="100%" ) ), if(selectBe){ shiny::column( cw, shiny::selectizeInput( inputId=shiny::NS(id, "beFocus"), label="Focus on BE", choices=allBe, selected=beOfInt, multiple=TRUE, width="100%" ) ) }, if(selectOrg){ shiny::column( cw, shiny::selectizeInput( inputId=shiny::NS(id, "beOrganisms"), label="Focus on organisms", choices=allOrg, selected=orgOfInt, multiple=TRUE, width="100%" ) ) } ), shiny::fluidRow( shiny::column( 12, DT::DTOutput( shiny::NS(id, "searchRes") ) ) ) )) }) ## Application state ---- appState <- shiny::reactiveValues( ## User choices orgOfInt=orgOfInt, beOfInt=beOfInt, ## Matches matches=NULL, genes=NULL, ## Filtered matches fmatches=NULL, fgense=NULL, geneEntity=NULL, ## Selection sel=NULL ) ## Select organisms ---- if(selectOrg){ shiny::observe({ selOrg <- input$beOrganisms if(length(selOrg)==0){ appState$orgOfInt <- allOrg }else{ appState$orgOfInt <- selOrg } appState$sel <- NULL }) } ## Select BE ---- if(selectBe){ shiny::observe({ selBe <- input$beFocus if(length(selBe)==0){ appState$beOfInt <- allBe }else{ appState$beOfInt <- selBe } appState$sel <- NULL }) } ## Search a given term ---- shiny::observe({ v <- input$beSearchTerm if(is.null(v)){ m <- g <- NULL }else{ shiny::withProgress( message="Searching genes", value=0, style="notification", expr={ m <- searchBeid(v) } ) if(is.null(m) || nrow(m)==0){ m <- g <- NULL }else{ .data <- NULL g <- dplyr::mutate(m, order=1:nrow(m)) g <- dplyr::mutate( g, url=getBeIdURL(.data$GeneID, .data$Gene_source) ) g <- dplyr::group_by(g, .data$Gene_entity, .data$organism) g <- dplyr::summarise( g, order=min(.data$order), value=ifelse( length(unique(.data$value)) <= 2, paste(unique(.data$value), collapse=", "), paste( c(head(unique(.data$value), 2), "..."), collapse=", " ) ), from=paste(unique(ifelse( .data$from %in% c("BESymbol", "BEName"), stringr::str_replace( .data$from, "^BE", paste(.data$be, " ") ), sprintf( '%s%s', .data$from, ifelse( !is.na(.data$symbol), ifelse( !is.na(.data$name), sprintf(': %s (%s)', .data$symbol, .data$name), sprintf(': %s', .data$symbol) ), ifelse( !is.na(.data$name), sprintf(' (%s)', .data$name), '' ) ) ) )), collapse=", "), symbol=paste(setdiff(.data$symbol, NA), collapse=", "), name=paste(setdiff(.data$name, NA), collapse=", "), GeneIDs=paste(unique(sprintf( '<a href="%s" target="_blank">%s</a>', url, highlightText( sprintf( '%s%s%s', ifelse(.data$preferred_gene, "<u><strong>", ""), .data$GeneID, ifelse(.data$preferred_gene, "</strong></u>", "") ), !!v ) )[order(.data$preferred_gene, decreasing=T)]), collapse=","), Gene_symbol=paste( setdiff(.data$Gene_symbol, NA), collapse=", " ), Gene_name=paste( setdiff(.data$Gene_name, NA), collapse=", " ) ) g <- dplyr::arrange(g, .data$order) g <- dplyr::select( g, "value", "from", "Gene_symbol", "Gene_name", "organism", "GeneIDs", "Gene_entity" ) g <- dplyr::ungroup(g) } } if(!is.null(m)){ m <- dplyr::rename(m, "match"="value") } if(!is.null(g)){ g <- dplyr::rename(g, "match"="value") } appState$matches <- m appState$genes <- g appState$sel <- NULL }) ## Filter matches ---- shiny::observe({ fmatches <- appState$matches[ which( appState$matches$organism %in% appState$orgOfInt & appState$matches$be %in% appState$beOfInt ), ] if(!is.null(fmatches) && nrow(fmatches)==0){ fmatches <- NULL }else{ if(!toGene && !is.null(fmatches)){ fmatches <- dplyr::distinct(dplyr::select( fmatches, "match", "from", "be", "beid", "source", "preferred", "symbol", "name", "entity", "organism" )) } } fgenes <- appState$genes[ which( appState$genes$organism %in% appState$orgOfInt ), ] if(!is.null(fgenes) && nrow(fgenes)==0){ fgenes <- NULL } appState$fmatches <- fmatches appState$fgenes <- fgenes appState$sel <- NULL }) ## Show the results ---- output$searchRes <- DT::renderDataTable({ v <- input$beSearchTerm if(toGene){ toShow <- appState$fgenes shiny::req(toShow) toShow <- dplyr::select( dplyr::mutate( toShow, Match=highlightText(.data$match, !!v), From=highlightText(.data$from, !!v), Symbol=highlightText(.data$Gene_symbol, !!v), Name=highlightText(.data$Gene_name, !!v), Organism=as.factor(.data$organism) ), "Match", # "From", "Symbol", "Name", "Organism", "GeneIDs", ) }else{ toShow <- appState$fmatches shiny::req(toShow) toShow <- dplyr::select( dplyr::mutate( toShow, Match=highlightText(.data$match, !!v), From=highlightText(.data$from, !!v), Symbol=highlightText(.data$symbol, !!v), Name=highlightText(.data$name, !!v), Organism=as.factor(.data$organism), ID=sprintf( '<a href="%s" target="_blank">%s</a>', getBeIdURL(.data$beid, .data$source), highlightText(.data$beid, !!v) ) ), "Match", # "From", "BE"="be", "Symbol", "Name", "Organism", "ID", "Source"="source", "Preferred"="preferred" ) } toShow <- DT::datatable( toShow, rownames=FALSE, escape=FALSE, selection=list( mode=ifelse(multiple, "multiple", "single"), target="row" ), options=list( dom="t", paging=FALSE, scrollResize=TRUE, scrollY=tableHeight, scrollCollapse=TRUE ) ) if(!toGene){ DT::formatStyle( toShow, "Preferred", backgroundColor=DT::styleEqual( c(TRUE, FALSE), c('darkgreen', 'transparent') ), color=DT::styleEqual( c(TRUE, FALSE), c('white', 'black') ) ) }else{ toShow } }) shiny::observe({ appState$sel <- input$searchRes_rows_selected }) ## Return the results ---- return(shiny::reactive({ sel <- appState$sel g <- appState$fgenes m <- appState$fmatches if( length(sel)==0 || is.null(g) || nrow(g)==0 || is.null(m) || nrow(m)==0 ){ return(NULL) }else{ if(toGene){ ge <- unique(g$Gene_entity[sel]) toRet <- unique(m[ which(m$Gene_entity %in% ge), c( "GeneID", "preferred_gene", "Gene_source", "organism", "Gene_entity" ) ]) colnames(toRet) <- c( "beid", "preferred", "source", "organism", "entity" ) if(nrow(toRet)>0){ toRet$be <- "Gene" toRet <- dplyr::left_join( toRet, g[,c("Gene_entity", "match")], by=c("entity"="Gene_entity") ) toRet <- toRet[ , c( "beid", "preferred", "be", "source", "organism", "entity", "match" ) ] } }else{ toRet <- m[ sel, c( "beid", "preferred", "be", "source", "organism", "entity", "match" ) ] } return(toRet) } })) }) } ###############################################################################@ #' @describeIn beidsServer #' #' @importFrom shiny uiOutput NS #' @export #' beidsUI <- function(id) { shiny::tagList( shiny::tags$head(shiny::tags$style(shiny::HTML( 'table.dataTable tr.selected td a {background-color: white !important;}' ))), shiny::uiOutput(outputId=NS(id, "mainUI")) ) }
/scratch/gouwar.j/cran-all/cranData/BED/R/beidsModule.R
#' Cached neo4j call #' #' This function calls neo4j DB the first time a query is sent and puts #' the result in the cache SQLite database. The next time the same query is #' called, it loads the results directly from cache SQLite database. #' #' Use only with "row" result returned by DB request. #' #' Internal use. #' #' @param ... params for [bedCall] #' @param tn the name of the cached table #' @param recache boolean indicating if the CQL query should be run even if #' the table is already in cache #' #' @return The results of the [bedCall]. #' #' @seealso [cacheBedResult], [bedCall] #' cacheBedCall <- function( ..., tn, recache=FALSE ){ cache <- checkBedCache() if(tn %in% rownames(cache) & !recache){ toRet <- loadBedResult(tn) }else{ toRet <- bedCall(...) cacheBedResult(value=toRet, name=tn) } return(toRet) }
/scratch/gouwar.j/cran-all/cranData/BED/R/cacheBedCall.R
#' Put a BED query result in cache #' #' Internal use #' #' @param value the result to cache #' @param name the name of the query #' #' @seealso [cacheBedCall], [loadBedResult] #' cacheBedResult <- function( value, name ){ ## Write cache in the user file space only if the "useCache" parameter ## is set to TRUE when calling `connectToBed()` (default: useCache=FALSE) if(!get("useCache", bedEnv)){ invisible(NULL) }else{ if(length(grep("^0000-", name))>0){ stop('names starting by "0000-" are reserved') } cache <- get("cache", bedEnv) cachedbFile <- get("cachedbFile", bedEnv) cachedbDir <- dirname(cachedbFile) file <- paste0(name, ".rda") save(value, file=file.path(cachedbDir, file)) cache[name, ] <- data.frame(name=name, file=file, stringsAsFactors=FALSE) save(cache, file=cachedbFile) assign( "cache", cache, bedEnv ) } } #' Get a BED query result from cache #' #' Internal use #' #' @param name the name of the query #' #' @seealso [cacheBedCall], [cacheBedResult] #' loadBedResult <- function(name){ value <- NULL cache <- get("cache", bedEnv) cachedbFile <- get("cachedbFile", bedEnv) cachedbDir <- dirname(cachedbFile) if(!name %in% rownames(cache)){ stop(sprintf("%s not in cache", name)) } load(file.path(cachedbDir, cache[name, "file"])) return(value) }
/scratch/gouwar.j/cran-all/cranData/BED/R/cacheBedResult.R
#' Check biological entities (BE) identifiers #' #' This function takes a vector of identifiers and verify if they can #' be found in the provided source database according to the BE type and #' the organism of interest. If an ID is in the DB but not linked directly nor #' indirectly to any entity then it is considered as not found. #' #' @param ids a vector of identifiers to be checked #' @param be biological entity. See [getBeIds]. **Guessed if not provided** #' @param source source of the ids. See [getBeIds]. **Guessed if not provided** #' @param organism the organism of interest. See [getBeIds]. #' **Guessed if not provided** #' @param stopThr proportion of non-recognized IDs above which an error is #' thrown. Default: 1 ==> no check #' @param caseSensitive if FALSE (default) the case is not taken into account #' when checking ids. #' #' @return invisible(TRUE). Stop if too many (see stopThr parameter) ids are not #' found. Warning if any id is not found. #' #' @examples \dontrun{ #' checkBeIds( #' ids=c("10", "100"), be="Gene", source="EntrezGene", organism="human" #' ) #' checkBeIds( #' ids=c("10", "100"), be="Gene", source="Ens_gene", organism="human" #' ) #' } #' #' @seealso [getBeIds], [listBeIdSources], [getAllBeIdSources] #' #' @export #' checkBeIds <- function( ids, be, source, organism, stopThr=1, caseSensitive=FALSE ){ ids <- as.character(ids) ## if(missing(be) || missing(source) || missing(organism)){ toWarn <- TRUE }else{ toWarn <- FALSE } guess <- guessIdScope(ids=ids, be=be, source=source, organism=organism) if(is.null(guess)){ warning("Could not find the provided ids") if(missing(be) || missing(source) || missing(organism)){ stop("Missing be, source or organism information") } }else{ if(is.na(guess$be)){ warning( "The provided ids does not match the provided scope", " (be, source or organism)" ) if(missing(be) || missing(source) || missing(organism)){ stop("Missing be, source or organism information") } }else{ be <- guess$be source <- guess$source organism <- guess$organism } } if(toWarn){ warning( "Guessing ID scope:", sprintf("\n - be: %s", be), sprintf("\n - source: %s", source), sprintf("\n - organism: %s", organism) ) } ## beInDb <- getBeIds( be=be, source=source, organism=organism, restricted=FALSE ) if(is.null(beInDb)){ stop("Could not find BE information") } ######### ids <- unique(ids) lids <- length(ids) if(caseSensitive){ notIn <- length(setdiff(ids, beInDb$id)) }else{ notIn <- length(setdiff(tolower(ids), tolower(beInDb$id))) } if(notIn > 0){ warning("Could not find ", notIn, " IDs among ", lids, "!") } if((notIn/lids) > stopThr){ stop("Too many missing IDs") } ######### invisible(TRUE) }
/scratch/gouwar.j/cran-all/cranData/BED/R/checkBeIds.R
#' Check BED cache #' #' This function checks information recorded into BED cache #' and resets it if not relevant. #' #' Internal use. #' #' @param newCon if TRUE for the loading of the system information file #' #' @seealso [clearBedCache], [lsBedCache] #' checkBedCache <- function(newCon=FALSE){ if(!checkBedConn()){ stop("Not connected to BED") } ## Write cache in the user file space only if the "useCache" parameter ## is set to TRUE when calling `connectToBed()` (default: useCache=FALSE) if(!get("useCache", bedEnv)){ invisible(NULL) }else{ dbSize <- bedCall( neo2R::cypher, 'MATCH (n) WITH n LIMIT 1 RETURN count(n);' )[,1] if(dbSize==0){ warning("Clearing cache") cache <- clearBedCache() }else{ dbVersion <- bedCall( neo2R::cypher, query=neo2R::prepCql(c( 'MATCH (n:System) RETURN', 'n.name as name, n.instance as instance, n.version as version' )) ) dbVersion$rbed <- utils::packageDescription( utils::packageName() )$Version ## cachedbFile <- get("cachedbFile", bedEnv) cachedbDir <- dirname(cachedbFile) sysFile <- file.path(cachedbDir, "0000-BED-system.rda") if(file.exists(sysFile)){ if(!exists("system", envir=bedEnv) | newCon){ load(file.path(cachedbDir, "0000-BED-system.rda"), envir=bedEnv) } system <- get("system", envir=bedEnv) if( any(!names(dbVersion) %in% names(system)) || dbVersion$name != system$name || dbVersion$instance != system$instance || dbVersion$version != system$version || dbVersion$rbed != system$rbed ){ message("Inconsitent cache == > clearing cache") cache <- clearBedCache() system <- dbVersion save(system, file=sysFile) assign( "system", system, bedEnv ) }else{ cache <- get("cache", bedEnv) } }else{ message("No recorded version ==> clearing cache") cache <- clearBedCache() system <- dbVersion save(system, file=sysFile) assign( "system", system, bedEnv ) } } invisible(cache) } }
/scratch/gouwar.j/cran-all/cranData/BED/R/checkBedCache.R